0
点赞
收藏
分享

微信扫一扫

JavaWEB快速入门之过滤器&监听器

影子喵喵喵 2022-04-24 阅读 73

一、Filter过滤器


    1. 概述
        过滤器是JavaWeb三大组件之一(servlet、Listener、Filter),过滤器实际上就是对web资源(HTML、CSS、Servlet、JSP)进行拦截,做一些处理后再交给下一个过滤器或servlet处理,通常都是用来拦截request进行处理的,也可以对返回的response进行拦截处理
 

 3.Filter快速入门
        (1)编写一个Filter,定义类实现接口Filter,实现接口中的抽象方法

/**
  * 过滤器对象被销毁之前执行的方法 
  * 	服务器关闭或重载时,过滤器对象销毁
  */
public void destroy() {
	System.out.println("----过滤器被销毁----");
}
/**
  * 对请求进行过滤的方法 
  * 	ServletRequest 请求对象 
  * 	ServletResponse 响应对象 
  * 	FilterChain 过滤链对象
  * 		作用:将通过此过滤器的请求,传递给下一个过滤器或目标Servlet
*/
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
	System.out.println("----过滤器执行过滤方法----");
	System.out.println("----DemoFilter-doFilter执行之前----");
	// 对请求放行的方法
	chain.doFilter(request, response);
	System.out.println("----DemoFilter-doFilter执行之后----");
}
/**
  * 过滤器对象创建之后执行的方法,对过滤器进行初始化 
  * 	其中FilterConfig参数为当前过滤器的配置,获取过滤器的初始化参数
  * 	当服务器启动时,过滤器对象被创建
*/
public void init(FilterConfig fConfig) throws ServletException {
	System.out.println("----过滤器初始化----");
}

4.常用配置项 urlPatterns
 ① 以指定资源匹配。例如"/index.jsp"
 ② 以目录匹配。例如"/servlet/*"
 ③ 以后缀名匹配,例如"*.jsp"
 ④ 通配符,拦截所有web资源。"/*"

 

package com.zking.filter;
 
import java.io.IOException;
 
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
 
/**
 * 字符编码过滤器 
 * 	对所有的请求和响应对象设置字符集 
 * 	用来提高代码复用性和解决硬编码问题。
 *
 */
public class EncodingFilter implements Filter {
 
	private String encoding;
 
	@Override
	public void destroy() {
 
	}
 
	@Override
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
			throws IOException, ServletException {
		System.out.println("------字符集过滤器开始过滤------");
		// 对请求对象设置字符集
		servletRequest.setCharacterEncoding(encoding);
		// 对相应对象设置字符集
		servletResponse.setCharacterEncoding(encoding);
		servletResponse.setContentType("text/html;charset=" + encoding);
		// 放行
		filterChain.doFilter(servletRequest, servletResponse);
 
	}
 
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		String encoding = filterConfig.getInitParameter("encoding");
		this.encoding = encoding;
	}
 
}

 配置xml:

<filter>
	<filter-name>EncodingFilter</filter-name>
  	<filter-class>com.zking.filter.EncodingFilter</filter-class>
  	<!-- 把过滤器要用到的字符集定义在初始化参数里面 -->
  	<init-param>
  		<param-name>encoding</param-name>
  		<param-value>utf-8</param-value>
  	</init-param>
</filter>
<filter-mapping>
	<filter-name>EncodingFilter</filter-name>
  	<url-pattern>/*</url-pattern>
</filter-mapping>

  ServletContextEvent事件方法:
    event.getServletContext().getContextPath();//取得ServletContext对象,即上下文

 //session创建时调用
  public void sessionCreated(HttpSessionEvent event){
 
  }
 
  //session销毁时调用
  public void sessionDestroyed(HttpSessionEvent event){
 
  }

 

  HttpSessionEvent事件方法:
    event.getSession().getId();    //得到session的ID


  实现:HttpSessionAttributeListener (不用,性能差)
  重写:

  //增加属性时触发
  public void attributeAdded(HttpSessionBindingEvent event){
    
  }
 
  //删除属性时触发
  public void attributeRemoved(HttpSessionBindingEvent event){
    
  }
 
  //替换属性时触发
  public void attributeReplaced(HttpSessionBindingEvent event){
    
  }

 

 
<listener>
   <listener-class>com.listener.Application</listener-class>
</listener>

案例统计在线人数和在线用户:

① 编写监听事件

// 首先我们需要实现 Servlet规定的监听器接口
public class OnlineCountListener implements HttpSessionListener {
    // 实现该接口后会必须重写下面这两个方法
    @Override
    public void sessionCreated(HttpSessionEvent se) {
        // 该方法是会在 Session创建时被调用,也就是 Session创建的监听事件
 
        // 拿到上下文对象
        ServletContext context = se.getSession().getServletContext();
        Integer onlineCount = (Integer) context.getAttribute("onlineCount");
        // 在触发 Session创建监听事件时,如果 onlineCount变量为 0我们将其设置为 1,表示第一个用户在线
        if (onlineCount==null){
            onlineCount = new Integer(1);
            // 如果不为 0表示之前有用户在线,我们将在线人数 +1
        }else {
            int count = onlineCount.intValue();
            onlineCount = new Integer(count+1);
        }
        // 打印输出 方便测试,可以去掉
        System.out.println(onlineCount);
        // 将在线人数的变量赋值添加到上下文对象中,方便前端取值
        context.setAttribute("onlineCount",onlineCount);
    }
 
    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        // 这个方法则相反,会在Session被销毁时调用
 
        // 销毁部分则逻辑相反
        ServletContext context = se.getSession().getServletContext();
        Integer onlineCount = (Integer) context.getAttribute("onlineCount");
        if (onlineCount==null){
            onlineCount = new Integer(0);
        }else {
            int count = onlineCount.intValue();
            onlineCount = new Integer(count-1);
        }
        context.setAttribute("onlineCount",onlineCount);
    }
}
举报

相关推荐

0 条评论