filter 简要说明
filter开发步骤
-
导包
-
编写过滤器
-
包不要导入错误了
import javax.servlet.Filter;
-
实现Filter接口,重写对应的方法即可
-
web.xml中配置过滤器
-
chain.doFilter将请求转发给过滤器链下一个filter , 如果没有filter那就是你请求的资源
-
案例演示
public class CharterEncodingFilter implements Filter {
//过滤器初始化
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("过滤器初始化");
}
//chain:链
/*
* 1.过滤中的所有代码,再过滤特定请求的时候都会执行
* 2.必须要让过滤器继续同行
* 3.filterChain.doFilter(servletRequest, servletResponse);*/
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
servletRequest.setCharacterEncoding("utf-8");
servletResponse.setCharacterEncoding("utf-8");
servletResponse.setContentType("text/html;charest=UTF-8");
System.out.println("CharterEncodingFilter执行前");
filterChain.doFilter(servletRequest, servletResponse);//让请求继续走,他会去找下一个链,但是它下面已经没有了,所以就会去跳转页面了,根据xml中的配置从过滤器中出来应当进入servlet包下的show
System.out.println("CharterEncodingFilter执行后.........");
}
//过滤器销毁
//web服务器关闭时会被销毁
public void destroy() {
System.out.println("过滤器销毁..........");
}
}
xml配置
<servlet>
<servlet-name>ShowServlet</servlet-name>
<servlet-class>com.zhang.servlet.ShowServlet</servlet-class>
</servlet>
<!--未经过过滤器-->
<servlet-mapping>
<servlet-name>ShowServlet</servlet-name>
<url-pattern>/show</url-pattern>
</servlet-mapping>
<!--经过过滤器-->
<servlet-mapping>
<servlet-name>ShowServlet</servlet-name>
<url-pattern>/servlet/show</url-pattern>
</servlet-mapping>
<filter>
<filter-name>CharterEncodingFilter</filter-name>
<filter-class>com.zhang.filter.CharterEncodingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>CharterEncodingFilter</filter-name>
<!--只要是servlet请求都会经过过滤器-->
<url-pattern>/servlet/*</url-pattern>
</filter-mapping>
测试servlet
public class ShowServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.getWriter().write("你好世界");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
未过滤结果
过滤后结果
本文来自博客园,作者:Cn_FallTime,转载请注明原文链接:https://www.cnblogs.com/CnFallTime/p/15978686.html