Java基础——Servlet(七)过滤器&监听器 相关

一、过滤器简介

Filter 位于客户端和请求资源之间,请求的资源可以是 Servlet Jsp html (img,javascript,css)等。用于拦截浏览器发给服务器的请求(Request)和服务器返回给浏览器的内容(Response)。一言以蔽之:过滤器是用来筛选请求的。

* 怎么实现一个过滤器? 思路如下:

1) 编写一个类, 实现javax.servlet.Filter 接口

-- destory();

-- init(FilterConfig config);

-- doFilter(ServletRequest req,ServletResponse resp, FilterChain chain);

2) 在 web.xml 中进行配置

二、处理乱码的过滤器

public class CharaFilter implements Filter{
    private String encoding="iso8859-1"; //默认
            
    public void destroy() {}
            
    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
        FilterChain chain) throws IOException, ServletException {
        System.out.println("----过滤器起作用了----");
                    
        request.setCharacterEncoding(encoding);
        //response.setCharacterEncoding(encoding);
                    
        chain.doFilter(request, response);
        }
            
    @Override
    public void init(FilterConfig config) throws ServletException {
        String confEncoding=config.getInitParameter("encoding");  //取得Filter配置文件中的初始化参数
        if(confEncoding!=null){
        encoding=confEncoding;
        }
    }    
}
//配置文件设置
<filter>
<filter-name>CharaFilter</filter-name>
<filter-class>filter.CharaFilter</filter-class>
              
<init-param>
 <param-name>encoding</param-name>
 <param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
    <filter-name>CharaFilter</filter-name>
    <url-pattern>/*</url-pattern> 
</filter-mapping>

三、验证是否有Session 的过滤器

public void doFilter(ServletRequest request, ServletResponse response,
    FilterChain chain) throws IOException, ServletException {
    
        HttpServletRequest req=(HttpServletRequest)request;
        HttpServletResponse rep=(HttpServletResponse)response;
                
        if(req.getSession().getAttribute("userInfo")==null){
        
        req.getRequestDispatcher("/login.jsp").forward(request, response);
                    
        /*
        //这里的 / 代表当前web应用的根路径  /Lession49
        req.getRequestDispatcher("/xxxx").forward(request, response);
                    
        //这里代表当前web服务器的根路径    ...  8080/
        rep.sendRedirect("/xxxx");
                    
        //如果想让sendRedirect准确
        rep.sendRedirect(req.getContextPath()+"/"+"xxxx");  //这里的getContextPath取得的是 web应的根路径 /Lession49
        */
                    
        }else{
        chain.doFilter(request, response);
        }
}
//配置文件的设置    
<filter>
    <filter-name>sessionFilter</filter-name>
    <filter-class>filter.SessionFilter</filter-class>
</filter>
     
    <filter-mapping>
     <filter-name>sessionFilter</filter-name>
     <url-pattern>/Admin/*</url-pattern>
    </filter-mapping>

四、servlet监听器

servlet监听的对象:

它负责监听ServletContext、HttpSession、ServletRequest对象的生命周期时间,以及属性改变事件。用于监听一些重要事件的发生,监听器对象可以在事情发生前、发生后可以做一些必要的处理

Listener是Servlet的监听器,它可以监听客户端的请求、服务端的操作等。通过监听器,可以自动激发一些操作,比如监听在线的用户的数量。当增加一个HttpSession时,就激发sessionCreated(HttpSessionEvent se)方法,目前Servlet2.4和JSP2.0总共有8个监听器接口和6个Event类。

Listener接口   Event类
ServletContextListenerServletContextEvent
ServletContextAttributeListenerServletContextAttributeEvent
HttpSessionListenerHttpSessionEvent
HttpSessionActivationListener同上
HttpSessionAttributeListenerHttpSessionBindingEvent   //用于监听session中何时添加、删除或替换了某种类型的属性
HttpSessionBindingListener同上  //由属性自身来实现,以便属性知道它什么时候被添加到一个session中,或者什么时候从session中删除。
ServletRequestListenerServletRequestEvent

 4.1 ServletContextListener

用于监听W EB 应用启动和销毁的事件,监听器类需要实现javax.servlet.ServletContextListener 接口。

ServletContextListener 是 ServletContext 的监听者,如果 ServletContext 发生变化,如服务器启动时 ServletContext 被创建,服务器关闭时 ServletContext 将要被销毁。

--ServletContextListener接口的方法:

void contextInitialized(ServletContextEvent sce) //通知正在接受的对象,应用程序已经被加载及初始化。

void contextDestroyed(ServletContextEvent sce) //    通知正在接受的对象,应用程序已经被载出。

--ServletContextEvent中的方法:

ServletContext getServletContext() //    取得ServletContext对象 (application)

4.2 ServletContextAttributeListener

用于监听WEB应用属性改变的事件,包括:增加属性、删除属性、修改属性,监听器类需要实现javax.servlet.ServletContextAttributeListener接口。

--ServletContextAttributeListener接口方法:

void attributeAdded(ServletContextAttributeEvent scab)//若有对象加入Application的范围,通知正在收听的对象
void attributeRemoved(ServletContextAttributeEvent scab) //    若有对象从Application的范围移除,通知正在收听的对象
void attributeReplaced(ServletContextAttributeEvent scab)//若在Application的范围中,有对象取代另一个对象时,通知正在收听的对象

--ServletContextAttributeEvent中的方法:

java.lang.String getName()     回传属性的名称

java.lang.Object getValue() 回传属性的值

4.3 HttpSessionListener

HttpSessionListener 监听HttpSession的操作。当创建一个Session时,激发session Created(HttpSessionEvent se)方法;当销毁一个Session时,激发sessionDestroyed (HttpSessionEvent se)方法。

4.4 HttpSessionActivationListener

主要用于同一个Session转移至不同的JVM的情形,用于监听Http会话active、passivate情况。。

HttpSessionAttributeListener

4.5 HttpSessionAttributeListener监听HttpSession中的属性的操作。

当在 Session 增加一个属性时,激发attributeAdded(HttpSessionBindingEvent se) 方法;

当在Session删除一个属性时,激发attributeRemoved(HttpSessionBindingEvent se)方法;

当在Session属性被重新设置时,激发attributeReplaced(HttpSessionBindingEvent se) 方法。

这和ServletContextAttributeListener比较类似

4.6 HttpSessionBindingListener

注意:HttpSessionBindingListener接口是唯一不需要再web.xml中设定的Listener

当我们的类实现了HttpSessionBindingListener接口后,只要对象加入Session范围

(即调用HttpSession对象的 setAttribute方法的时候)或从Session范围中移出

(即调用HttpSession对象的removeAttribute方法的时候或 Session Time out的时候)时,容器分别会自动调用下列两个方法:

--    void valueBound(HttpSessionBindingEvent event)

--    void valueUnbound(HttpSessionBindingEvent event)

4.7    ServletRequestListener

它和ServletContextListener接口类似的,这里由ServletContext改为ServletRequest。

4.8    ServletRequestAttributeListener

它和ServletContextListener接口类似的,这里由ServletContext改为ServletRequest。

五、servlet监听器实例

//例一
1) 创建一个类,实现某个监听器接口
public class MyListener implements ServletContextListener{
    public void contextDestroyed(ServletContextEvent arg0) {
    System.out.println("上下文销毁了");  //网站关闭
    }
        
    public void contextInitialized(ServletContextEvent arg0) {
    System.out.println("上下文创建了");  //网站启动的时候
        }
}
        
2) 在web.xml  这个配置文件中进行配置
    <listener>
        <listener-class>cat.listener.MyListener</listener-class>
    </listener>
//例二 通过实现 MySessionListener 接口, 做一个简单在线人数计数器
        
public class MyListener implements ServletContextListener{
            
    public void contextDestroyed(ServletContextEvent arg0) {
    System.out.println("上下文销毁了");  //网站关闭
    }
        
    public void contextInitialized(ServletContextEvent arg0) {
    System.out.println("上下文创建了");  //网站启动的时候
    }
}
        

//配置文件的设置
<listener>
      <listener-class>cat.listener.MySessionListener</listener-class>
</listener>
  
  
//index.jsp设置
<% out.println("当前在线人数:"+    MySessionListener.getSessioCount()); %>

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值