RLuceac
RLuceac

Reputation: 382

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?

Upvotes: 3

Views: 6003

Answers (2)

Dimitar Pavlov
Dimitar Pavlov

Reputation: 300

If you are using JSP, you can't render the view with Spring because Spring is not compiling the JSP pages. Depending on the length of the view, a solution is to build your view by hand as String (Simple HTML no JSP tags) and return it as JSON.

EDIT: Take a look at this Render Spring MVC to String or PDF Biju Kunjummen answer

Upvotes: 1

RLuceac
RLuceac

Reputation: 382

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()) {
      res.setValStatus("SUCCESS");
      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') {
   $("#pp-result").html(response.htm);
 }

Thats all!

Upvotes: 4

Related Questions