Spring MVC and AJAX with JSON
You can use json-lib-ext-spring. There are other libs, this is the one I found. If you know or use another one, please leave a comment with the library name.
Do not forget to download Json-lib and its dependencies.
Now you have to configure your XML files:
Create a views.xml file under WEB-INF folder and paste the following code into it:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
<? xml version = "1.0" encoding = "UTF-8" ?> xsi:schemaLocation= "http://www.springframework.org/schema/beans < bean name = "jsonView" class = "net.sf.json.spring.web.servlet.view.JsonView" /> </ beans > |
Add this config to you spring configuration file:
1
2
3
4
5
6
7
8
9
|
<!-- json --> < bean id = "xmlFileViewResolver" class = "org.springframework.web.servlet.view.XmlViewResolver" > < property name = "location" > < value >/WEB-INF/views.xml</ value > </ property > < property name = "order" > < value >1</ value > </ property > </ bean > |
Make sure to set the order if you are using any other view resolvers.
Now you just have to use “jsonView” as the viewname and the model will be converted to JSONbefore being sent back to the client:
1
|
return new ModelAndView( "jsonView" , modelMap); |
Here is an example:
1
2
3
4
5
6
7
8
|
public ModelAndView getColumnsJson(HttpServletRequest request, HttpServletResponse response) throws Exception { Map<String,Object> modelMap = new HashMap<String,Object>( 2 ); modelMap.put( "rows" , service.generateColumns()); return new ModelAndView( "jsonView" , modelMap); } |
Happy coding!