How to render tile views in Spring MVC via AJAX?

Jared picture Jared · Aug 30, 2012 · Viewed 7k times · Source

I'm using Spring 3 MVC to build a web app that has a common layout and a "content" div that changes/refreshes frequently. The content markup is in its own Tile, and I want to be able to refresh that tile via AJAX without refreshing the entire page. I know how to fire the AJAX request from the client and handle it in the controller. I'm mostly confused about the Spring configuration (which views, view resolvers, etc). Does anyone have an example?

Answer

James picture James · Aug 31, 2012

Basically you could create a tiles view that only contains the content you want without the HTML skeleton around and render this view/tile in the controller that handles the ajax request.

Let's say you have a page foo.jsp. When calling http://example.com/myapp/foo, a whole html page with foo.jsp as the body's content should be rendered. When calling http://example.com/myapp/ajax/foo, only foo.jsp should be sent without the whole HTML skeleton, so that the client can load this via ajax and replace a part in the page.

You will end up with two view definitions, one that embeds foo.jsp in a whole page and one that only contains foo.jsp itself. app-layout.jsp would contain the whole HTML skeleton with a "body" attribute.

<definition name="foo" template="/WEB-INF/layouts/app-layout.jspx">
    <put-attribute name="body">
        <definition template="/WEB-INF/views/foo.jsp">
            <put-attribute name="message" value="hello"/>
        </definition>
    </put-attribute>
</definition>

<definition name="ajax.foo" template="/WEB-INF/views/foo.jsp">
    <put-attribute name="message" value="hello"/>
</definition>

The controller that handles the URL /ajax/foo would return the view "ajax.foo", the controller that handles the URL /foo would return the view "foo".

@Controller
@RequestMapping("/ajax")
public void class AjaxController {
   @RequestMapping("/foo")
   public String foo() {
       return "ajax.foo";
   }
}

@Controller
@RequestMapping("/")
public void class AppController {
   @RequestMapping("/foo")
   public String foo() {
       return "foo";
   }
}