Spring MVC 自带的字符编码过滤器以及Tomcat字符编码设置,彻底解决中文参数乱码问题

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/BeauXie/article/details/53389856

一、Spring MVC字符编码配置

java Web项目添加Spring支持后,可使用Spring自带的字符编码过滤器。源码在spring-web-4.1.0.RELEASE.jar包下的org.springframework.web.filter目录的CharacterEncodingFilter.java。

在web.xml文件中配置:

<!-- Spring字符集过滤 -->
	<filter>
		<description>字符集过滤器</description>
		<filter-name>encodingFilter</filter-name>
		<filter-class>
		  org.springframework.web.filter.CharacterEncodingFilter
		</filter-class>
		<init-param>
			<description>字符集编码</description>
			<param-name>encoding</param-name>
			<param-value>UTF-8</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>encodingFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

查看org.springframework.web.filter下的CharacterEncodingFilter.java源代码:
//........省略..............
	@Override
	protected void doFilterInternal(
			HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {

		if (this.encoding != null && (this.forceEncoding || request.getCharacterEncoding() == null)) {
			request.setCharacterEncoding(this.encoding);
			if (this.forceEncoding) {
				response.setCharacterEncoding(this.encoding);
			}
		}
		filterChain.doFilter(request, response);
	}
	//........省略..............
	
分析源代码发现,其作用相当于Servlet中的:
	request.setCharacterEncoding("UTF-8");  
	response.setCharacterEncoding("UTF-8"); 
因此,Spring自带的字符编码过滤器主要针对“POST”请求,对“GET”请求无效。

通过以上的配置,只能解决POST请求,对于GET请求无效,以往对于GET请求的参数乱码,解决方法是采用数据还原:
String userName= request.getParameter("userName");   
userName=new String(userName.getBytes("iso8859-1"),"UTF-8");  
而这种方法的局限性在于对于每个GET请求都要手动的去修改,因为tomcat服务器的默认编码是 ISO-8859-1’,因此我们可以通过修改Tomcat的配置文件来更改Tomcat的字符编码设置。

二、Tomcat字符编码配置
打开conf目录下的server.xml,在70行,修改之前代码如下:
<Connector port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" />
修改之后,代码如下:
<Connector port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" 
               URIEncoding="UTF-8"
               useBodyEncodingForURI="true"
               />
区别在于加上了 URIEncoding="UTF-8"useBodyEncodingForURI="true",这样Tomcat服务器对于Get请求的默认编码就变成了UTF-8,而不是原来默认的iso8859-1。


总结:
通过以上的配置,就可以彻底解决项目中参数中文乱码问题,但特别要主要的是,对于GET请求的中文参数,不能再在后台进行数据还原,否则会乱码!


猜你喜欢

转载自blog.csdn.net/BeauXie/article/details/53389856