Announcement Announcement Module
No announcement yet.
Spring MVC : Best way to handle JSON and HTML mapping Page Title Module
Move Remove Collapse
Conversation Detail Module
  • Filter
  • Time
  • Show
Clear All
new posts

  • Spring MVC : Best way to handle JSON and HTML mapping


    I'm quite new to JSON.

    I want to produce a JSON view and a HTML view for a list of clients.

    Should I use :
    1. 2 distincts URL (i.e. : /clients and /rest/clients)
    2. or only one URL (/clients) and using HTTP headers to differentiate HTML and JSON ?

    In the second case, I would have the following Controller :
    @RequestMapping(value = "/clients")
    public class ClientController {
    	// HTML output
    	@RequestMapping(method = RequestMethod.GET)
    	public String list() {}
    	// JSON output
    	@RequestMapping(method = RequestMethod.GET, consumes="application/json", produces="application/json")
    	public @ResponseBody RestClientList list() {}
    Thanks !

  • #2
    Best way I've seen so far is detailed here :

    It enabled me to use one Controller for both HTML and JSON output.

    Just make sure to configure 2 viewResolvers in Spring configuration :
    • first one handles .json suffix and generated json output (i.e. /clients.json).
    • the other generates html output (i.e. /clients).
    Here's a configuration extracted from the previous (really good) link :
    <bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
      <property name="order" value="1" />
      <property name="mediaTypes">
          <entry key="json" value="application/json" />
          <entry key="xml" value="application/xml" />
      <property name="defaultViews">
          <bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView" />
          <bean class="org.springframework.web.servlet.view.xml.MarshallingView">
              <bean class="org.springframework.oxm.xstream.XStreamMarshaller" />
      <property name="ignoreAcceptHeader" value="true" />
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
      <property name="order" value="2" />
      <property name="prefix" value="/WEB-INF/views/"/>
      <property name="suffix" value=".jsp"/>


    • #3
      Is there any mechanism to to this solely with roo?
      IOW, can one setup the ContentNegotiatingViewResolver with roo commands to handle HTML and JSON?

      I've tried:

      // JSON
      json all --deepSerialize
      web mvc json setup
      web mvc json all
      // HTML
      web mvc setup
      web mvc all --package ~.crud

      but the latter HTML config overwrites the JSON generated code.


      • #4
        Sorry, I've no sufficient knowledge on ROO.

        Perhaps you should ask on the ROO forum ? (