1.实现过滤器代码;
2.在项目web.xml文件添加过滤器标记<filter>和<filter-mapping>;
注意:前台页面设置contentType的charset值与web.xml里设置的值一致。
详细配置步骤
1.实现过滤器代码
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 package com.sp.Tools; 2 3 import java.io.IOException; 4 5 import javax.servlet.Filter; 6 import javax.servlet.FilterChain; 7 import javax.servlet.FilterConfig; 8 import javax.servlet.ServletException; 9 import javax.servlet.ServletRequest; 10 import javax.servlet.ServletResponse; 11 import javax.servlet.http.HttpServletRequest; 12 import javax.servlet.http.HttpServletResponse; 13 14 public class EncodingFilter implements Filter { 15 // 定义默认字符雿 16 private String encoding = "utf-8"; 17 18 public void init(FilterConfig filterConfig) throws ServletException { 19 // 从web.xml文件中读取字符集; 20 encoding = filterConfig.getInitParameter("encoding"); 21 } 22 23 public void doFilter(ServletRequest request, ServletResponse response, 24 FilterChain chain) throws IOException, ServletException { 25 HttpServletRequest httpRequest = (HttpServletRequest) request; 26 HttpServletResponse httpResponse = (HttpServletResponse) response; 27 // 设置请求的字符集 28 httpRequest.setCharacterEncoding(encoding); 29 // 设置响应的字符集 30 httpResponse.setCharacterEncoding(encoding); 31 chain.doFilter(httpRequest, httpResponse); 32 } 33 34 public void destroy() { 35 36 } 37 38 }
2.在项目web.xml文件添加过滤器标记<filter>和<filter-mapping>;
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 <filter> 2 <!--过滤器名称,自己起 --> 3 <filter-name>EncodingFilter</filter-name> 4 <!--过滤器类名称,包括包名一致、写全 --> 5 <filter-class>com.sp.Tools.EncodingFilter</filter-class> 6 <init-param><!--初始化参数,要指定的字符集编码 --> 7 8 <param-name>encoding</param-name><!--参数名称 --> 9 <param-value>utf-8</param-value> <!--参数值 --> 10 </init-param> 11 </filter> 12 <filter-mapping> 13 <filter-name>EncodingFilter</filter-name> 14 <url-pattern>/*</url-pattern> <!--“/*”表示项目下所有资源 --> 15 </filter-mapping>
注意:如果实现上述仍有乱码,可能是一下原因:
url="jdbc:mysql://localhost:3306/spdb1?characterEncoding=utf-8"
(红色字体如果没有,加上尝试一下)
ct = DriverManager.getConnection(url,"root","root");