使用SpringMVC自动封装并返回json数据
方法一,手动配置
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.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!-- Controller的组件扫描 -->
<context:component-scan base-package="com.codejams.controller"/>
<!-- 配置内部资源视图解析器 -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 配置url前缀 -->
<property name="prefix" value="/jsp/"/>
<!-- 配置url后缀 -->
<property name="suffix" value=".jsp"/>
</bean>
<!-- 配置处理器适配器 -->
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="messageConverters">
<list>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"></bean>
</list>
</property>
</bean>
</beans>
controller层
方法二,使用SpringMVC注解驱动
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"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- Controller的组件扫描 -->
<context:component-scan base-package="com.codejams.controller"/>
<!-- 配置内部资源视图解析器 -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 配置url前缀 -->
<property name="prefix" value="/jsp/"/>
<!-- 配置url后缀 -->
<property name="suffix" value=".jsp"/>
</bean>
<!-- 配置处理器适配器 -->
<!-- <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">-->
<!-- <property name="messageConverters">-->
<!-- <list>-->
<!-- <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"></bean>-->
<!-- </list>-->
<!-- </property>-->
<!-- </bean>-->
<!-- MVC注解驱动 -->
<mvc:annotation-driven/>
</beans>
注意:其他代码不变