Monday, June 6, 2011

Spring 2.5 With JSON View

Steps to configure JSON View as a view resolver.

1)      Create views.xml & put it into WEB-INF. Once you create a bean for jsonView it will automatically search for the views.xml file in WEB-INF folder.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"

<beans>
      <bean name="jsonView" class="org.springframework.web.servlet.view.json.JsonView">
            <property name="jsonWriter">
                  <ref bean="jsonWriter" />
            </property>
      </bean>

      <bean name="jsonWriter"
            class="org.springframework.web.servlet.view.json.writer.sojo.SojoJsonStringWriter">
            <property name="keepValueTypesMode">
                  <value>ALL</value>
            </property>
      </bean>
</beans>

2)      Creating bean’s for view resolver such as the application should support more than one view.

      <bean id="resourceViewResolver"
            class="org.springframework.web.servlet.view.ResourceBundleViewResolver">
            <property name="basename" value="views" />
            <property name="order" value="2" />
      </bean>
     

      <bean id="xmlViewResolver"
            class="org.springframework.web.servlet.view.XmlViewResolver">
            <property name="order" value="1" />
      </bean>

Generally we use to write view resolver bean configuration in servler.xml.
Observe the order attribute for above bean. We have configure to view resolver here.

3)      Returning jsonView as a view from Spring Controller.

JSONObject jsonObject = new JSONObject();
jsonObject.put("success", true);

return new ModelAndView("jsonView", jsonObject);

4)      You can check JSON response in firebug.



5)      Required libraries :-


                Jquery, extjs, YUI, etc library supports for the JSON.
                e.g. We can bind JSON data coming from server directly to the table provided by javascript lib.



 -/ Dinesh

No comments:

Post a Comment