过滤器CharacterEncodingFilter
1 import javax.servlet.*; 2 import java.io.IOException; 3 4 public class CharacterEncodingFilter implements Filter { 5 //初始化 6 @Override 7 public void init(FilterConfig filterConfig) throws ServletException { 8 System.out.println("初始化!"); 9 } 10 11 @Override 12 /* 13 1.设置字符编码 14 2,要设置chain链 经过Filter后要转发出去 15 */ 16 public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { 17 request.setCharacterEncoding("utf-8"); 18 response.setCharacterEncoding("utf-8"); 19 response.setContentType("text/html;charset=utf-8"); 20 System.out.println("执行前"); 21 filterChain.doFilter(request,response);//让我们的请求继续走,如歌不写,程序到此截至 22 System.out.println("执行后"); 23 } 24 25 @Override 26 public void destroy() { 27 System.out.println("销毁"); 28 } 29 }
//XML设置
<servlet>
<servlet-name>ShowServlet</servlet-name>
<servlet-class>com.zxy.servlet.ShowServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ShowServlet</servlet-name>
<url-pattern>/servlet/show</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>ShowServlet</servlet-name>
<url-pattern>/ggg/show</url-pattern>
</servlet-mapping>
<!--只要经过/servlet的任何请求,就会经过这个过滤器 -->
<!-- <url-pattern>/*</url-pattern> -->
<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>com.zxy.filter.CharacterEncodingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/servlet/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/ggg/*</url-pattern>
</filter-mapping>
注意:
1.设置Servlet时 例如只有一级查询时 如 /show 这是过滤器为 /servlet/* 时 无法过滤 要设置为 /* 作为小项目没事 当为当项目时过造成过多的负担
2.可以每一个servlet设置为二级 例如/servlet/show 或者/ggg/show filte设置为/servlet/* 和/ggg/* 一一对应;
标签:show,System,Filter,println,过滤器,out,servlet,CharacterEncodingFilter From: https://www.cnblogs.com/kidzxy/p/16793248.html