过滤器,拦截中文乱码

package com.chenxb;

import javax.servlet.*;
import java.io.IOException;

public class Filter implements javax.servlet.Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("初始化。。。");
}

//过滤所有代码(注意:最后必须让过滤器继续运行)
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
servletResponse.setCharacterEncoding("utf-8");
System.out.println("执行前。。。");
filterChain.doFilter(servletRequest, servletResponse);
System.out.println("执行后。。。");
}

@Override
public void destroy() {
System.out.println("销毁。。。");
}
}

调取测试

package com.chenxb;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class FilterTest extends ServletContextSet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
PrintWriter writer = resp.getWriter();
writer.print("通过过滤器修复中文乱码");
}

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req,resp);
}
}

web.xml配置

<!--过滤器mapping-->
<filter>
<filter-name>Filter</filter-name>
<filter-class>com.chenxb.Filter</filter-class>
</filter>
<filter-mapping>
<filter-name>Filter</filter-name>
<!--/filter/的所有请求都被过滤-->
<url-pattern>/Filter/*</url-pattern>
</filter-mapping>

<servlet>
<servlet-name>FilterTest</servlet-name>
<servlet-class>com.chenxb.FilterTest</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FilterTest</servlet-name>
<!--没有过滤器的地址-->
<url-pattern>/FilterTest</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>FilterTest</servlet-name>
<!--有过滤器的地址-->
<url-pattern>/Filter/FilterTest</url-pattern>
</servlet-mapping>