完整maven项目搭建
1. 在eclipse中New选择maven项目,并选择web类型这个百度一下到处有;
2. 写简单的controller示例;
3. 配置web.xml,主要是DispatcherServlet;
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:spring/spring-servlet.xml
</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
4. 配置扫描MVC文件,并进行包扫描;
web.xml中:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:spring/spring-mvc.xml
</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
spring-mvc.xml中:
<context:component-scan base-package="com.wdm"/>
<mvc:annotation-driven/>
5. 配置返回对象转json
a. jackson直接引包,在pom.xml引入:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.7</version>
</dependency>
b. 配置fastjson,在spring-mvc.xml中:
<mvc:annotation-driven>
<mvc:message-converters register-defaults="true">
<bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>application/json;charset=UTF-8</value>
<value>text/html;charset=UTF-8</value>
<value>text/xml;charset=UTF-8</value>
<value>text/plain;charset=UTF-8</value>
</list>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
以上两种二选一即可实现controller返回对象直接json化
github地址:https://github.com/wdmyong/spring-cache
PS:
中间可能会踩的坑。
1. ContextLoaderListener(参考:http://www.cnblogs.com/wang-meng/p/5598731.html)
解决问题的方法很简单, 在web 启动的时候将applicationContext转到到servletContext中, 因为在web 应用中的所有servlet都共享一个servletContext对象. 那么我们就可以利用ServletContextListener去监听servletContext事件, 当web 应用启动的是时候, 我们就将applicationContext 装载到servletContext中。
(这篇讲的也不错:http://blog.csdn.net/gzu_imis/article/details/18989679)
2. json化上面讲了,两种方法之一即可解决。