第一季:9SpringMVC中如何解决POST请求中文乱码问题,GET的又如何处理呢
题目
SpringMVC中如何解决POST请求中文乱码问题,GET的又如何处理呢
/*
★测试入参为POJO
Spring MVC会按请求参数名和POJO属性名进行自动匹配,
自动为该对象填充属性值。支持级联属性
*/
分析
SpringMVC中有一个过滤器CharacterEncodingFilter
中有一个方法doFilterInternal
@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.doFi1ter(request, response);
}
解决
在web.xml中
<!--解决POST请求的请求乱码问题-->
<filter>
<filter-name>CharacterEncodingFilter </filter-name>
<filter-class>org.springframework.web.filter.characterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forcencoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>*</url-pattern>
</filter-mapping>
post解决
get有中文乱码了
解决:
在Tomcat配置文件server.xml中
在第一个Connector添加字段 URIEncoding="UTF-8"