Version: Next
乱码问题
form.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %><html><head><title>Title</title></head><body><form action="/e/t1" method="post"><input type="text" name="name"><input type="submit"></form></body></html>Controller
@Controllerpublic class EncodingController {@PostMapping("/e/t1")public String test1(String name, Model model) {model.addAttribute("msg", name);return "test";}}输入中文,出现乱码
过滤器解决
自定义过滤器
定义一个过滤器
public class EncodingFilter implements Filter {public void init(FilterConfig filterConfig) throws ServletException {}public void doFilter(ServletRequest request, ServletResponse response,FilterChain filterChain) throws IOException, ServletException {request.setCharacterEncoding("utf-8");response.setCharacterEncoding("utf-8");filterChain.doFilter(request, response);}public void destroy() {}}web.xml 在web.xml中配置这个过滤器 filter必须放在最前面
<filter><filter-name>encoding</filter-name><filter-class>com.bsx.filter.EncodingFilter</filter-class></filter><filter-mapping><filter-name>encoding</filter-name><url-pattern>/*</url-pattern></filter-mapping>
SpringMVC过滤器
直接配置web.xml,用过滤器org.springframework.web.filter.CharacterEncodingFilte
web.xml
<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>