Java Web 过滤器(Filter)

·  阅读 132

过滤网站的数据

  • 处理中文乱码
  • 登录验证
  • 。。。。

大致流程

  • 编写继承了Filter接口的类(是servlet中的Fliter)
  • 重写接口中的方法
  • 如何处理req和resp(过滤)
  • 最关键的是chain.doFilter(request, response);不能忘记
  • 在web.xml中配置filter

大致形状如下:

public class CharacterEncodingFilter implements Filter {
    int i=0;
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
         //初始化
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
          response.setCharacterEncoding("UTF8");
          request.setCharacterEncoding("UTF8");
          response.setContentType("text/html; charset=UTF-8");
          chain.doFilter(request, response);//!!!!!!!!!!!!!!!!
    }

    @Override
    public void destroy() {

    }
}
复制代码

随便写个需要过滤的servlet

public class ServletFilter extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.getWriter().println("中文经过了过滤");
    }

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

web.xml

<servlet>
    <servlet-name>servlet</servlet-name>
    <servlet-class>servlet.ServletFilter</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>servlet</servlet-name>
    <url-pattern>/s/filter</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>servlet</servlet-name>
    <url-pattern>/filter</url-pattern>
  </servlet-mapping>

  <filter>
    <filter-name>f</filter-name>
    <filter-class>filter.CharacterEncodingFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>f</filter-name>
<!--会过滤以/s/*结尾url-->
    <url-pattern>/s/*</url-pattern>
  </filter-mapping>
复制代码

会过滤以/s/*结尾url

============================================

分类:
后端
标签:
收藏成功!
已添加到「」, 点击更改