博客
关于我
JavaWeb快速入门--Filter&Listener
阅读量:60 次
发布时间:2019-02-25

本文共 7576 字,大约阅读时间需要 25 分钟。

Filter:过滤器

Filter概念:

过滤器JavaWeb三大组件之一,当我们请求服务器的资源时,过滤器会在这组资源之前执行,它可以将我们的请求拦截下来,判断是否让我们访问这个资源,并完成一些特殊的功能。过滤器一般用于完成通用的操作。如:登录验证、统一编码处理、敏感字符过滤…

过滤器与Servlet很相似,同时使用的方式也比较类似,首先我们要写一个类,实现Filter接口,然后部署我们的Filter。当然在部署时,我们可以采用注解形式或xml形式。

执行顺序:执行过滤器-》执行放行后的资源-》执行放行代码下边的代码

@WebFilter("/*")public class MyFilter implements Filter {     //创建之后,马上执行;Filter会在服务器启动时就创建  public void init(FilterConfig filterConfig) throws ServletException {   }  //销毁之前执行!在服务器关闭时销毁  public void doFilter(ServletRequest request, ServletResponse response,      FilterChain chain) throws IOException, ServletException {         System.out.println("被执行了...");      //放行,如果不使用就不会继续执行了      filterChain.doFilter(servletRequest,servletResponse);  }  //每次过滤时都会执行  public void destroy() {   }}

在web.xml文件中部署Filter:我们只需去除我们的注解,并在web.xml中配置如下文件即可

myFilter
com.ly.filter.MyFilter
myFilter
/index.jsp

过滤器的生命周期

init(FilterConfig):在服务器启动时会创建Filter实例,并且每个类型的Filter只创建一个实例,在创建完Filter实例后,会马上调用init()方法完成初始化工作,这个方法只会被执行一次,用于加载资源。

doFilter(ServletRequest req,ServletResponse res,FilterChain chain):这个方法会在用户每次访问目标资源:<url-pattern>index.jsp</url-pattern>)时执行,如果需要“放行”,那么需要调用FilterChain的doFilter(ServletRequest,ServletResponse)方法,如果不调用FilterChain的doFilter()方法,那么目标资源将无法执行

destroy():服务器会在创建Filter对象之后,把Filter放到缓存中一直使用,通常不会销毁它。一般会在服务器关闭时销毁Filter对象,在销毁Filter对象之前,服务器会调用Filter对象的destory()方法,用来释放资源

多个过滤器执行顺序

  • 执行顺序:如果有两个过滤器:过滤器1和过滤器2

    1. 过滤器1
    2. 过滤器2
    3. 资源执行
    4. 过滤器2
    5. 过滤器1

  • 过滤器先后顺序问题:

    1. 注解配置:按照类名的字符串比较规则比较,值小的先执行,如: AFilter 和 BFilter,AFilter就先执行了。
    2. web.xml配置: <filter-mapping>谁定义在上边,谁先执行

关于拦截:

  • 拦截路径配置:

    1. 具体资源路径: /index.jsp 只有访问index.jsp资源时,过滤器才会被执行
    2. 拦截目录: /user/* 访问/user下的所有资源时,过滤器都会被执行
    3. 后缀名拦截: *.jsp 访问所有后缀名为jsp资源时,过滤器都会被执行
    4. 拦截所有资源:/* 访问所有资源时,过滤器都会被执行

  • 过滤器的四种拦截方式:REQUEST、FORWARD、INCLUDE、ERROR

拦截方式 功能描述
REQUEST 直接访问目标资源时执行过滤器。包括:在地址栏中直接访问、表单提交、超链接、重定向,只要在地址栏中可以看到目标资源的路径,就是REQUEST
FORWARD 转发访问执行过滤器。包括RequestDispatcher#forward()方法、<jsp:forward>标签都是转发访问
INCLUDE 包含访问执行过滤器。包括RequestDispatcher#include()方法、<jsp:include>标签都是包含访问
ERROR 当目标资源在web.xml中配置为中时,并且真的出现了异常,转发到目标资源时,会执行过滤器

注解配置:

  • @WebFilter(value="/index.jsp",dispatcherTypes = DispatcherType.REQUEST)
  • @WebFilter(value="/*",dispatcherTypes ={ DispatcherType.FORWARD,DispatcherType.REQUEST})

web.xml配置:<dispatcher>REQUEST</dispatcher>

案例:字符编码转换

@WebFilter("/*")public class CharchaterFilter implements Filter {       protected String encoding;		public void destroy() {   		// TODO Auto-generated method stub	}	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {   	    //将父接口转换为子接口		HttpServletRequest request=(HttpServletRequest)req;		HttpServletResponse response=(HttpServletResponse)res;				//获取请求方法		String method=request.getMethod();		//解决post请求中文数据乱码问题		if(method.equalsIgnoreCase("post")) {   			request.setCharacterEncoding("utf-8");		}		//处理响应乱码		response.setContentType("text/html;charset=utf-8");			chain.doFilter(request,response);	}	public void init(FilterConfig fConfig) throws ServletException {   		// TODO Auto-generated method stub	}}

案例:敏感词过滤

/** * 敏感词汇过滤器 */@WebFilter("/*")public class SensitiveWordsFilter implements Filter {       public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {           //1.创建代理对象,增强getParameter方法        ServletRequest proxy_req = (ServletRequest) Proxy.newProxyInstance(req.getClass().getClassLoader(), req.getClass().getInterfaces(), new InvocationHandler() {               @Override            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {                   //增强getParameter方法                //判断是否是getParameter方法                if(method.getName().equals("getParameter")){                       //增强返回值                    //获取返回值                    String value = (String) method.invoke(req,args);                    if(value != null){                           for (String str : list) {                               if(value.contains(str)){                                   value = value.replaceAll(str,"***");                            }                        }                    }                                        return  value;                }                //判断方法是否是: getParameterMap                //判断方法是否是:  getParameterValue                return method.invoke(req,args);            }        });        //2.放行        chain.doFilter(proxy_req, resp);    }    private List
list = new ArrayList
();//敏感词汇集合 public void init(FilterConfig config) throws ServletException { try{ //1.获取文件真实路径 ServletContext servletContext = config.getServletContext(); String realPath = servletContext.getRealPath("/WEB-INF/classes/敏感词汇.txt"); //2.读取文件 BufferedReader br = new BufferedReader(new FileReader(realPath)); //3.将文件的每一行 String line = null; while((line = br.readLine())!=null){ list.add(line); } br.close(); System.out.println(list); }catch (Exception e){ e.printStackTrace(); } } public void destroy() { }}
/** * 验证方法 */@WebServlet("/testServlet")public class TestServlet extends HttpServlet {       protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {           String name = request.getParameter("name");        String msg = request.getParameter("msg");        System.out.println(name+":"+msg);    }    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {           this.doPost(request, response);    }}

过滤器JavaWeb三大组件之一,当我们请求服务器的资源时,过滤器会在这组资源之前执行,它可以将我们的请求拦截下来,判断是否让我们访问这个资源,并完成一些特殊的功能。过滤器一般用于完成通用的操作。如:登录验证、统一编码处理、敏感字符过滤…

Listener:监听器

监听器JavaWeb的三大组件之一,在我们执行请求之前执行,主要用于监听Web服务器中的某一个执行动作,并根据其要求做出响应的响应。

目前Servlet中包含8个Listener接口,可以将其归纳为3类:

  • ServletContextListener:监听ServletContext对象的创建和销毁
* 方法:	* void contextDestroyed(ServletContextEvent sce) :ServletContext对象被销毁之前会调用该方法	* void contextInitialized(ServletContextEvent sce) :ServletContext对象创建后会调用该方法* 步骤:	1. 定义一个类,实现ServletContextListener接口	2. 复写方法	3. 配置		1. web.xml			
cn.itcast.web.listener.ContextLoaderListener
* 指定初始化参数
2. 注解: * @WebListener
  • 代码实现
@WebListenerpublic class ContextLoaderListener implements ServletContextListener {       /**     * 监听ServletContext对象创建的。ServletContext对象服务器启动后自动创建     *     * 在服务器启动后自动调用     * @param servletContextEvent     */    @Override    public void contextInitialized(ServletContextEvent servletContextEvent) {           //加载资源文件        //1.获取ServletContext对象        ServletContext servletContext = servletContextEvent.getServletContext();        //2.加载资源文件        String contextConfigLocation = servletContext.getInitParameter("contextConfigLocation");        //3.获取真实路径        String realPath = servletContext.getRealPath(contextConfigLocation);        //4.加载进内存        try{               FileInputStream fis = new FileInputStream(realPath);            System.out.println(fis);        }catch (Exception e){               e.printStackTrace();        }        System.out.println("ServletContext对象被创建了。。。");    }    /**     * 在服务器关闭后,ServletContext对象被销毁。当服务器正常关闭后该方法被调用     * @param servletContextEvent     */    @Override    public void contextDestroyed(ServletContextEvent servletContextEvent) {           System.out.println("ServletContext对象被销毁了。。。");    }}

转载地址:http://uim.baihongyu.com/

你可能感兴趣的文章
mysql 死锁 Deadlock found when trying to get lock; try restarting transaction
查看>>
mysql 死锁(先delete 后insert)日志分析
查看>>
MySQL 死锁了,怎么办?
查看>>
MySQL 深度分页性能急剧下降,该如何优化?
查看>>
MySQL 深度分页性能急剧下降,该如何优化?
查看>>
MySQL 添加列,修改列,删除列
查看>>
mysql 添加索引
查看>>
MySQL 添加索引,删除索引及其用法
查看>>
mysql 状态检查,备份,修复
查看>>
MySQL 用 limit 为什么会影响性能?
查看>>
MySQL 用 limit 为什么会影响性能?有什么优化方案?
查看>>
MySQL 用户权限管理:授权、撤销、密码更新和用户删除(图文解析)
查看>>
mysql 用户管理和权限设置
查看>>
MySQL 的 varchar 水真的太深了!
查看>>
mysql 的GROUP_CONCAT函数的使用(group_by 如何显示分组之前的数据)
查看>>
MySQL 的instr函数
查看>>
MySQL 的mysql_secure_installation安全脚本执行过程介绍
查看>>
MySQL 的Rename Table语句
查看>>
MySQL 的全局锁、表锁和行锁
查看>>
mysql 的存储引擎介绍
查看>>