zoukankan      html  css  js  c++  java
  • 过滤器filter

    方便自己查询,嫌低级的勿喷。。。。

    在Servlet中如果要定义一个过滤器,则直接让一个类实现javax.servlet.Filter接口即可,此接口定义的3个操作方法,如下:

    No 方法 类型
    1 public void init(FilterConfig filterConfig) throws ServletException 过滤器初始化(容器启动时初始化)是调用,可以通过FilterConfig取得配置的初始化参数
    2 public void doFilter(ServletRequest request,ServletResponse response,FilterChain chain) throws IOException,ServletException 完成具体的过滤操作,然后通过FilterChain让请求继续向下传递
    3 public void destroy() 过滤器销毁时使用

    在doFilter()方法中定义了ServletRequest、ServletResponse和FilterChain3个参数,从前面两个参数中可以发现,过滤器可以完成对任意协议的过滤操作。FilterChain接口的主要作用是将用户的请求向下传递给其他的过滤器或者Servlet,此接口的方法如下:

    No 方法 描述
    1 public void doFilter(ServletrRequest request.ServletResponse response) throws IOException,ServletException 将请求向下继续传递
    package org.lxh.filterdemo ;
    import java.io.* ;
    import javax.servlet.* ;
    public class EncodingFilter implements Filter {
        private String charSet ;//设置字符编码
        public void init(FilterConfig config) throws ServletException{//接收初始化的参数
            this.charSet = config.getInitParameter("charset") ;    //取得初始化参数
        }
        public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,ServletException{
            request.setCharacterEncoding(this.charSet) ;//设置统一的编码
            chain.doFilter(request,response) ;//将请求继续向下传递
        }
        public void destroy(){
        }
    }
    配置web.xml文件
    <
    filter> <filter-name>encoding</filter-name> <filter-class>org.lxh.filterdemo.EncodingFilter</filter-class> <init-param> <param-name>charset</param-name> <param-value>GBK</param-value> </init-param> </filter> <filter-mapping> <filter-name>encoding</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>

    "/*"表示对跟目录下的一切操作都需要过滤。

  • 相关阅读:
    Community Server 2.0 学习笔记:如何实现在线人数?
    CommunityServer2.0改造的一些心得[粗糙版]
    DotLucene源码浅读笔记(2) : Lucene.Net.Documents
    有意思.在线版的photoshop
    电子商务教程[资源]
    Lucene 1.9 多目录搜索的的一个bug
    小总结:DotLucene如何才能快速生成索引?
    DotLucene源码浅读笔记(1)补遗:编写简单中文分词器ChineseAnalyzer
    Windows下傻瓜式快速搭建Discuz论坛(也可以参考用于搭建其他php论坛)
    Lucene.net常见功能实现知识汇总
  • 原文地址:https://www.cnblogs.com/mjsh/p/3205521.html
Copyright © 2011-2022 走看看