SpringMVC-07-乱码问题
模拟乱码问题
页面输入中文乱码
form.jsp–>/e/t—>test.jsp
form.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>表单</title>
</head>
<body>
<form action="/e/t" method="post">
<input type="text" name="name">
<input type="submit">
</form>
</body>
</html>
ControllerEncoding.java
@Controller
public class ControllerEncoding {
@PostMapping("/e/t")
public String test(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 servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) servletRequest;
HttpServletResponse resp = (HttpServletResponse) servletResponse;
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
filterChain.doFilter(servletRequest,servletResponse);
}
public void destroy() {
}
}
web.xml注册
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>com.cmy.filter.EncodingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
SpringMVC提供的过滤器
直接在web.xml中配置
<!--配置SpringMVC的乱码过滤器-->
<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>