如何解决SpringMVC接收到的请求参数为乱码的问题

2020-12-20  本文已影响0人  懂我yet

如何解决SpringMVC接收到的请求参数为乱码的问题

Get请求

直接设置tomcat目录下conf/server.xml文件,添加编码为utf-8

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

Post请求

原理

请求参数为乱码主要是因为编码的问题。需要在web配置文件中配置一个过滤器用来过滤请求,对请求进行编码。

假定最初设置的<span id="servlet">servlet</span>为:

<servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>

需要配置一个<span id="filter">过滤器</span>:

<!-- 配置编码过滤器 characterEncodingFilter 解决中文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>forceEncoding</param-name>
        <param-value>true</param-value>
    </init-param>
</filter>

说明:

然后是配置过滤器需要过滤哪些请求

<filter-mapping>
    <filter-name>characterEncodingFilter</filter-name>
    <servlet-name>springmvc</servlet-name>
</filter-mapping>

说明:

<span id="forceEncoding">forceEncoding</span>

在CharacterEncodingFilter中有一个setForceEncoding方法(org.springframework.web.filter.CharacterEncodingFilter#setForceEncoding),他会对变量forceRequestEncoding和forceResponseEncoding进行赋值,代码如下:

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

而在过滤的方法doFilterInternal方法(org.springframework.web.filter.CharacterEncodingFilter#doFilterInternal)中会通过forceRequestEncoding和forceResponseEncoding的值来判断是否需要对请求和响应进行编码:

protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
    String encoding = this.getEncoding();
    if (encoding != null) {
        if (this.isForceRequestEncoding() || request.getCharacterEncoding() == null) {
            request.setCharacterEncoding(encoding);
        }

        if (this.isForceResponseEncoding()) {
            response.setCharacterEncoding(encoding);
        }
    }

    filterChain.doFilter(request, response);
}
上一篇下一篇

猜你喜欢

热点阅读