乱码问题现象
1、创建提交数据的表单form.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<form action="/e/t" method="post">
<input type="text" name="name">
<input type="submit">
</form>
</body>
</html>
2、创建EncodingController进行请求处理,返回提交的name字段
package indi.stitch.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
@Controller
public class EncodingController {
@PostMapping("/e/t")
public String test1(String name, Model model) {
model.addAttribute("msg",name);
return "test";
}
}
3、test.jsp用于向客户端返回处理后的数据
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
${msg}
</body>
</html>
4、进行提交测试
表单提交name“张三”
返回数据为乱码
处理方法
方法一:自定义过滤器,并在web.xml文件中进行配置
自定义过滤器
package indi.stitch.filter;
import javax.servlet.*;
import java.io.IOException;
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中配置自定义过滤器
<!--1、自定义过滤器-->
<filter>
<filter-name>encoding</filter-name>
<filter-class>indi.stitch.filter.EncodingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
处理结果:
方法二:使用Spring的过滤器,需要在init-param标签中为其传入encoding=utf-8的参数,直接在web.xml中进行配置即可
<!--2、使用Spring的过滤器-->
<filter>
<filter-name>encoding</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>
</filter>
<filter-mapping>
<filter-name>encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
处理结果: