1:使用过滤器,对所有请求进行过滤。
package com.kuang.filter; import javax.servlet.*; import java.io.IOException; public class EncodingFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { servletRequest.setCharacterEncoding("utf-8"); servletResponse.setCharacterEncoding("utf-8"); filterChain.doFilter(servletRequest,servletResponse); } @Override public void destroy() { } }
<!--过滤器--> <filter> <filter-name>encoding</filter-name> <filter-class>com.kuang.filter.EncodingFilter</filter-class> </filter> <filter-mapping> <filter-name>encoding</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
2:改变get,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>
3:在SpringMVC中配置乱码解决
<!--配置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>
4:检查Tomcat中是否为UTF-8
5:终极乱码解决类
https://www.bilibili.com/video/BV1aE41167Tu?p=13