SpringMVC中如何解决POST请求中文乱码问题,GET的又如何处理

解决POST请求中文乱码问题

先来看一个类CharacterEncodingFilter,
package org.springframework.web.filter;

import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.util.Assert;
/**
这个CharacterEncodingFilter过滤器的源码
 */
public class CharacterEncodingFilter extends OncePerRequestFilter {
	//有两个成员变量
    private String encoding;
    private boolean forceEncoding;

    public CharacterEncodingFilter() {
        this.forceEncoding = false;
    }

    public CharacterEncodingFilter(String encoding) {
        this(encoding, false);
    }

    public CharacterEncodingFilter(String encoding, boolean forceEncoding) {
        this.forceEncoding = false;
        Assert.hasLength(encoding, "Encoding must not be empty");
        this.encoding = encoding;
        this.forceEncoding = forceEncoding;
    }

	//这里两个set方法可以给成员变量赋值
    public void setEncoding(String encoding) {
        this.encoding = encoding;
    }

    public void setForceEncoding(boolean forceEncoding) {
        this.forceEncoding = forceEncoding;
    }

    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        if (this.encoding != null && (this.forceEncoding || request.getCharacterEncoding() == null)) {
        	//当this.encoding中有值时会将请求的编码设置为对应值,设置为UTF-8即可解决中文乱码问题
            request.setCharacterEncoding(this.encoding);
            if (this.forceEncoding) {
            	//当this.forceEncoding为true时设置响应的编码值
                response.setCharacterEncoding(this.encoding);
            }
        }

        filterChain.doFilter(request, response);
    }
}

在项目的web.xml文件上面添加一个过滤器
<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>forceEncoding</param-name>
      <param-value>true</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>CharacterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

解决GET请求中文乱码问题

修改tomcat的server.xml文件,在等一个Connector标签添加URIEncoding="UTF-8"属性
<Connector URIEncoding="UTF-8" port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" />
posted @ 2020-03-10 10:29  岸北  阅读(1129)  评论(0编辑  收藏  举报