RLuceac RLuceac - 4 months ago 22
Java Question

How to render Spring MVC view to a string

I have a form that was sent via ajax to the controller. In that controller the inputs are validated, and return a json object.

If there are errors, I return an property(string) in that json object that has the value "FAIL" so that I can analyse it in client side.

What I'm trying to do is to render a view, and put it in that json object as a string property, so that when there are no errors (SUCCESS), i can set a div with the html from that rendered view.

How can I do that?

is there a better way of doing that?


Done it!!

Here's my solution:

I used thymeleaf so I can render a page in my controller.

I use some parts of different info I found on the web.. Not remembet them all, so thanks and sorry to not put the link here....

First I send the form data via ajax to the controller. In the controller I create an object and set the status field to SUCCESS of FAIL, if fail i return set the error info on my object, if success I set a field to the html of my page response. So I send this object back to the client (JSON) and analise the fields.

Bellow is the code:

The controller:

@RequestMapping(value = "/calcdireto.json", method = RequestMethod.POST)
public @ResponseBody CalcDiretoResponse processFormAjaxJson(Model model,
    @ModelAttribute(value = "formBean") @Valid CalcDiretoFormBean cdBean,
    BindingResult result) {
CalcDiretoResponse res = new CalcDiretoResponse();
if (!result.hasErrors()) {
      final WebContext ctx = new WebContext(request,servletContext,request.getLocale());
      res.setHtml(this.templateEngine.process("subpage", ctx));     
      return res;
}   ...

And in the page:

if (response.valStatus == 'SUCCESS') {

Thats all!