Announcement Announcement Module
No announcement yet.
Suggested way to add support for file extensions in the request URI in Spring 3.2 Page Title Module
Move Remove Collapse
Conversation Detail Module
  • Filter
  • Time
  • Show
Clear All
new posts

  • Suggested way to add support for file extensions in the request URI in Spring 3.2

    I'm a little bit confused about how I should implement this in Spring Web MVC 3.2.

    What I want to do :
    • page.json -> json response
    • page.xml->xml response
    • page.html -> FreeMarker template to generate html
    • I want to ignore the "Accept" header since the extension is used

    My controller
    public class APIController {
    	//specific mapping for html to avoid @ResponseBody
    	@RequestMapping(value="/page.html", method=RequestMethod.GET)
    	public String handlePageHtmlGet(@RequestParam String data, ModelMap model, HttpServletResponse response){
    		return "page"; //name of the view
    	@RequestMapping(value="/page", method=RequestMethod.GET)
    	public PageResponse handlePageGet(@RequestParam String data, HttpServletResponse response){
    		return pageResponse;
    Note : PageResponse is just a regular POJO with Xml annotation.

    My dispatcher-servlet.xml

    <!-- Freemarker config -->
    <bean id="freemarkerConfig" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
      	<property name="templateLoaderPath" value="/WEB-INF/view/"/>
    <bean id="freeMarkerViewResolver" 
    	<property name="cache" value="true"/>
    	<property name="prefix" value=""/>
    	<property name="suffix" value=".ftl"/>
    	<property name="contentType" value="text/html;charset=UTF-8"/>
    This is working but here are my questions:
    • How to restrict the supported extensions (If I try page.atom (or anything else that is not supported) an XML representation is returned)
    • What is the purpose of ContentNegotiationManager in Spring 3.2?

  • #2
    You are confusing 2 things here, request mapping and result mapping.

    If you only want to accept those extensions then explicitly map them (/page will by default also map /page.*).

    Result mapping is done on different levels, where the file extension has precedence (by default). The result mapping is done/configured by the ContentNegotiationManager (I suggest a read of the reference guide and the javadocs of that class).


    • #3
      So I should do my mapping like that:
      @RequestMapping(value="/page{extension:\\.(?:json|xml)}", method=RequestMethod.GET)
      I read the ContentNegotiationManager reference guide and the javadocs and I'm ok with the default strategy/configuration.

      I'm confused because a class like ContentNegotiatingViewResolver(result mapping) has a list of mediaTypes and a method setUseNotAcceptableStatusCode. So I thought that the extension restriction could be done at that level.