日期:2014-05-16  浏览次数:20433 次

使用内容协商让Spring MVC支持 json格式输出
  1. web.xml配置如下

?????
?<servlet>
??<servlet-name>dispatherContext</servlet-name>
??<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
??<load-on-startup>1</load-on-startup>
?</servlet>
?<servlet-mapping>
??<servlet-name>dispatherContext</servlet-name>
??<url-pattern>*.json</url-pattern>
?</servlet-mapping>

?

2.?? dispatherContext-servlet.xml 配置如下

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
?xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
?xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
??http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
?<context:component-scan base-package="com.zjhcsoft.mobi.web" />
?<context:annotation-config />
?<bean
??class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
??<property name="ignoreAcceptHeader" value="true" />
??<property name="defaultContentType" value="text/html" />
??<property name="mediaTypes">
???<map>
????<entry key="json" value="application/json" />
???</map>
??</property>
??<property name="favorParameter" value="false" />
??<property name="viewResolvers">
???<list>
????<bean class="org.springframework.web.servlet.view.BeanNameViewResolver" />
???</list>
??</property>
??<property name="defaultViews">
???<list>
????<bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView" />
???</list>
??</property>
?</bean>

</beans>

?

3.??

?

?@RequestMapping("/queryKPIDetail.json")
?public void queryKPIDetail(ModelMap modelMap,HttpServletRequest request) {
??//request请求参数
??String kpiId = request.getParameter("kpiId");
??String operateDate = request.getParameter("operateDate");
??
??
??List<Map<String, String>> list = jdbcBaseDAOImpl.queryForList(kpiSql);
??modelMap.put("mobi", list);
?}

?

4.http://localhost/login.json?phone=15988104039?访问即可返回json格式的数据