1 问题简述

SpringMVC 出现中文乱码

2 环境

Tomcat 8.5.85,SpringMVC 5.3.1

前端表单如下:

1
2
3
4
5
<form th:action="@{/paramDemo/pojo}" method="post">
username: <label><input type="text" th:name="username"/></label>
password: <label><input type="text" th:name="password"/></label>
<input type="submit" value="登录">
</form>

Controlller 层方法

1
2
3
4
5
6
@RequestMapping("/paramDemo/pojo")
public String getParameterByPOJO(User user) {
System.out.println(user.getUsername());
System.out.println(user.getPassword());
return "success";
}

User 类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class User {
private String username;

private String password;

public User(String username, String password) {
this.username = username;
this.password = password;
}

public User() {
}
// getter、setter、toString() 等省略
}

浏览器在表单输入中文后,后端得到乱码

3 解决方法

(1)设置 Tomcat 的 VM 参数:-Dfile.encoding=utf-8

(2)web.xml 中配置过滤器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<!-- 配置编码过滤器,解决乱码 -->
<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>
<!-- 只设置 encoding 默认只设置 request 的编码 -->
<!-- forceEncoding 则会也设置 response 的编码 -->
<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>

(3)在 Tomcat 的配置文件 server.xml 的 Connector 标签添加属性:URIEncoding=”UTF-8”

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

(4)重启 Tomcat 和项目