【SpringMVC】CharacterEncodingFilter解决获取请求参数的乱码问题

1.get请求乱码

get请求的乱码是在Tomcat的配置文件conf service.xml 中配置接口的地方添加URIEncoding=UTF-8

    <Connector port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443"  URIEncoding="UTF-8"/>

2.获取请求参数的乱码问题

解决获取请求参数的乱码问题,可以使用SpringMVC提供的编码过滤器CharacterEncodingFilter,但是必须在web.xml中进行注册


<filter>
    <filter-name>CharacterEncodingFilterfilter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
    <init-param>
    
        <param-name>encodingparam-name>
        <param-value>UTF-8param-value>
    init-param>
    <init-param>
        <param-name>forceResponseEncodingparam-name>
        <param-value>trueparam-value>
    init-param>
filter>
<filter-mapping>
    <filter-name>CharacterEncodingFilterfilter-name>
    <url-pattern>/*url-pattern>
filter-mapping>

注:SpringMVC中处理编码的过滤器一定要配置到其他过滤器之前,否则无效

打开源码看一下

public class CharacterEncodingFilter extends OncePerRequestFilter {

	@Nullable
	private String encoding;  //使用的编码

	private boolean forceRequestEncoding = false;  //是否在请求时设置编码

	private boolean forceResponseEncoding = false;//是否在响应时设置编码
		.
		.
		.
	@Override
	protected void doFilterInternal(
			HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {

		String encoding = getEncoding();
		if (encoding != null) {
		//在过滤器中设置了编码,无论是否打开forceRequestEncoding请求前编码开关,当检查到 request.getCharacterEncoding() 设置的编码为null时,自动进行编码。
			if (isForceRequestEncoding() || request.getCharacterEncoding() == null) {
				request.setCharacterEncoding(encoding);
			}
			if (isForceResponseEncoding()) {
				response.setCharacterEncoding(encoding);
			}
		}
		filterChain.doFilter(request, response);
	}
	.
	.
	.
}

你可能感兴趣的:(SpringMVC,springMVC,乱码,Tomcat配置)