3.乱码问题集中解决
作者:互联网
环境:
form.jsp进行post请求
<%@ 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>
Encoding.java
@Controller public class Encoding { @PostMapping("/e/t1") public String test(String name, Model model){ model.addAttribute("msg",name); return "hello"; } }
在表单提交中文转发后会出现乱码
解决方案一:使用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里注册,注意这里是/*不然拦截不到 /*包括了jsp文件
<filter> <filter-name>encoding</filter-name> <filter-class>com.wu.filter.EncodingFilter</filter-class> </filter> <filter-mapping> <filter-name>encoding</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
方法二:使用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>
标签:utf,encoding,void,public,乱码,servletResponse,解决,servletRequest,集中 来源: https://www.cnblogs.com/wuyimin/p/14873329.html