• 过滤器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>

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

  • 相关阅读:
    python 类
    hdu 5761 Rowe Bo 微分方程
    calendar 示例
    hdu 5753 Permutation Bo
    hdu 5752 Sqrt Bo
    finally 语句
    throws 和 throw
    python打开.pkl的文件并显示里面的内容
    Python 类变量,成员变量,静态变量,局部变量
    python 实例方法,类方法,静态方法,普通函数
  • 原文地址:https://www.cnblogs.com/mjsh/p/3205521.html
Copyright © 2020-2023  润新知