3

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?

3
  • Please add the code you tried Commented Sep 23, 2013 at 11:34
  • I dont have the code.. I have the code that I do the validation and the javascript code to analyse the json retun object. This is working... What I need is some info on how to render a view and return the html of the rendered view inside a string... Commented Sep 23, 2013 at 11:38
  • Depends on the view technology you are using. If you're using something like Velocity you could read a template into a string. Commented Sep 23, 2013 at 13:15

2 Answers 2

4

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!

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.