http://www.cnblogs.com/crazy-fox/archive/2012/02/18/2357675.html
sprngmvc 返回json:
方法一:springmvc设置默认返回json
<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="contentNegotiationManager">
<bean class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
<property name="ignoreAcceptHeader" value="true"/>
<property name="defaultContentType" value="application/json"/>
<property name="mediaTypes">
<map>
<entry key="page" value="text/html"/>
<entry key="json" value="application/json"/>
</map>
</property>
</bean>
</property>
<property name="viewResolvers">
<list>
<bean class="org.springframework.web.servlet.view.BeanNameViewResolver" />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
</list>
</property>
<property name="defaultViews">
<list>
<bean
class="org.springframework.web.servlet.view.json.MappingJackson2JsonView" />
</list>
</property>
</bean>
调用:
http://127.0.0.1:8080/Spring3.2/user/TP18001135
@RequestMapping(value="/{userid}")
public User viewUser(@PathVariable("userid")String userid)
throws Exception {
User user = getUserService().view(userid);
return user;
}
http://127.0.0.1:8080/Spring3.2/user/TP18001135
@RequestMapping(value="/{userid}")
public User viewUser(@PathVariable("userid")String userid)
throws Exception {
User user = getUserService().view(userid);
return user;
}
结果:
{
user: {
pkid: "TP18001135",
name: "TP18001135",
email: "[email protected]",
spAcccount: "TP18001135"
}
}
方法2,使用 @ResponseBody返回json:
配置文件:
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/jsp/" />
<property name="suffix" value=".jsp"></property>
控制器:
@RequestMapping(value = "/json/{userid}", method = RequestMethod.GET)
@ResponseBody
public User getUserJson(@PathVariable("userid")String userid) throws Exception {
User user = getUserService().view(userid);
return user;
}
返回结果:
{
pkid: "TP18001135",
name: "TP18001135",
email: "[email protected]",
spAcccount: "TP18001135"
}