一般在用spring MVC注解形式时(3.1或以上版本),在spring配置文件里采用下面配置就行了:
<mvc:annotation-driven/>
对于这个配置,spring 3.0会自动注入
-
DefaultAnnotationHandlerMapping
-
AnnotationMethodHandlerAdapter
-
AnnotationMethodHandlerExceptionResolver
而spring 3.1将变换成:
-
RequestMappingHandlerMapping
-
RequestMappingHandlerAdapter
-
ExceptionHandlerExceptionResolver
具体可参考源码:org.springframework.web.servlet.config.AnnotationDrivenBeanDefinitionParser.
下面问题来了,就拿spring 3.1来说,但是当@responsebody注解返回string时,中文字符会出现乱码现象,可用下面2中方案解决,推荐第二种:
1. 在controller方法的注释加上response返回时编码:@RequestMapping(value="getKeywordCategoryTree",produces="text/plain;charset=UTF-8")
2. Spring配置文件中修改<mvc:annotation-driven/>配置如下,修改对string的默认编码:
<!-- 当@responseBody是string时,字符串编码默认为IOS-9001,需要改成utf-8 -->
<mvc:annotation-driven>
<mvc:message-converters register-defaults="true">
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/plain;charset=UTF-8</value>
</list>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
如果spring初始化报错,可能是spring jar包版本不是3.1或者xml配置文件命名空间指定的不是3.1或以上,如下:
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.1.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd