有时候我们会遇到乱码问题,比如:
接收前端的字符串如果是中文字符时会出现乱码。
这里,我们先写一个test.jsp
<%--
Created by IntelliJ IDEA.
User: daodai
Date: 2020/7/31
Time: 19:48
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>test</title>
</head>
<body>
<form action="/hello" method="post">
<input type="text" name="username">111
<input type="submit" value="提交">
</form>
</body>
</html>
访问/test时,跳转到test页面
@GetMapping("/test")
public String test(Model model){
return "test";
}
在test页面上输入中文字符并进行提交,跳到hello页面,并显示输入的中文字符
@PostMapping("/hello")
public String hello1(String username,Model model){
model.addAttribute("msg", username);
return "hello";
}
<%--
Created by IntelliJ IDEA.
User: daodai
Date: 2020/7/30
Time: 22:10
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>hello</title>
</head>
<body>
${msg}
</body>
</html>
然而这样显示的内容是乱码。
要解决这个问题就要使用filter
- 先创建Filter的实现类
public class EncodingFilter implements Filter {
public void init(FilterConfig filterConfig) throws ServletException {
}
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
servletRequest.setCharacterEncoding("utf-8");
servletResponse.setCharacterEncoding("utf-8");
filterChain.doFilter(servletRequest,servletResponse);
}
public void destroy() {
}
}
- web.xml中进行配置
注意:url-pattern中如果使用/,.jsp文件不做处理。所以这边要用/*。
<filter>
<filter-name>encoding-filter</filter-name>
<filter-class>com.kuang.filter.EncodingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>encoding-filter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</filter>