0

Until now when sending ajax requests, in our controller we did return JsonMessage and decorate the data in the client side. But recently we are using a third-party UI framework which accepts a ready to use HTML as ajax callback.

Is there a way to do this without bringing all the html markup to the controller? something like a post-processor which accepts JSON and a template, renders it and then sends it to the client?

Note: The response is in JSON format, which has an attribute containing that HTML.

We use springframework 4.2.6.

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
Amir M
  • 354
  • 4
  • 16
  • just handled it like this http://stackoverflow.com/questions/22422411/how-to-manually-render-spring-mvc-view-to-html – Amir M May 31 '16 at 11:24

1 Answers1

0

Generally you need to add some method into controller which returns ModelAndView object.

Also you need to configure ViewResolver and set view name and corresponding model in the ModelAndView object. Like this

@Controller
public class DefaultController {
  @RequestMapping(value = "/html", produces = "application/json")
  public ModelAndView getUserHtml(HttpServletResponse response) throws Exception {
    response.setContentType("application/json");
    return new ModelAndView("user", Collections.singletonMap("user", this.user));
  }
}

And you'll see response like this

{
  "response": "<div><h1>Java Spring creating response from template</h1><h2>User</h2><p>username: superuser</p><p>password: secret</p><p>email: superuser@mail.com</p></div></html>"
}

Working sample project: https://github.com/sandarkin/so-q37526576

Roman Sandarkin
  • 416
  • 4
  • 5
  • I tried this, thanks, but this returns the html, not a json containing that html :\ – Amir M May 31 '16 at 07:07
  • OK. I have adjusted the sample project by forcibly setting the content type. And now http://localhost:8080/default/html will return json with the correct content type. – Roman Sandarkin May 31 '16 at 15:47