简体   繁体   中英

Spring MVC: generate ModelAndView programmatically

I am wondering is it possible to generate ModelAndView's output programatically and not via controller's return parameter. For example: I have the following method that returns a compiled html:

@RequestMapping(value = "/get-list", method = RequestMethod.GET, headers = BaseController.AJAX_HEADER)
public ModelAndView getList(@RequestParam(value = "page", required = true) Integer page,
            @ActiveUser User activeUser) {
        ModelAndView result = null;

        try {
            result = new ModelAndView("administration/events-log/list");
            result.addObject("events", eventsLogService.getList(page, Config.RECORDS_PER_PAGE));
        }
        catch (Exception e) {
            log(e, activeUser.getUsername());
        }

        return result;
    }

What I want is to create something like that:

@RequestMapping(value = "/get-list", method = RequestMethod.GET, headers = BaseController.AJAX_HEADER)
public @ResponseBody HashMap<String, Object> getList(@RequestParam(value = "page", required = true) Integer page,
            @ActiveUser User activeUser) {
        HashMap<String, Object> json = new HashMap<String, Object>();

        try {
            json.put("error", 0);
            ModelAndView result = new ModelAndView("administration/events-log/list");
            result.addObject("events", eventsLogService.getList(page, Config.RECORDS_PER_PAGE));

            json.put("content", result);

        }
        catch (Exception e) {
            /**/
        }

        return json;
    }

so the JSON object that will be sended back to the client will look: {'error': 0, 'content': compiled_html}

Any thoughts? Thank you

ModelAndView has no output. It just knows the name of the view. The rendering of the view is independent of Spring MVC.

If you simply want to send JSON that contains some HTML you can put the JSON code directly on your jsp. Change your java code like that:

result = new ModelAndView("path/to/json");
result.addObject("events", eventsLogService.getList(page, Config.RECORDS_PER_PAGE));
result.addObject("html", "administration/events-log/list");

Your JSON jsp can look like this:

<%@ page contentType="application/json" %>
{
  "error": "0",
  "content": "<jsp:include page="${html}" />"
}

Please note that this code is just for illustration. You may have adapt it to your situation. And you have to escape the included HTML to get valid JSON .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM