JSP页面实现servlet过滤器与servlet监听器(JSP中级技术)

来源:互联网 发布:淘宝店铺怎么发布产品 编辑:程序博客网 时间:2024/05/17 00:53

JSP页面实现servlet过滤器与servlet监听器(JSP中级技术)

一、servlet过滤器

我们将会探讨….

1、什么是servlet过滤器

2、servlet过滤器的开发步骤

3、实例

1、什么是servlet过滤器

•    servlet 过滤器(Filter )是小型的Web 组件,它们拦截请求和响应,以便查看、提取或以某种方式操作正在客户机和服务器之间交换的数据

•    实现过滤器只须在web.xml中设定相关设定,不需要修改其它Servlet、JSP和其他静态页面。因此开发者可以轻易的加入Filter机制。

 

•    过滤器是通常封装了一些功能的 Web 组件,这些功能虽然很重要,但是对于处理客户机请求或发送响应来说不是决定性的。

•    过滤器在Web开发中的一些主要应用:

•    对用户请求进行统一认证。

•    对用户的访问请求进行记录和审核。

•    对用户发送的数据进行过滤或替换。

•    转换图象格式。

•    对响应内容进行压缩,减少传输量。

•    对请求或响应进行加解密处理等。

2servlet过滤器的开发步骤

一、编写实现Filter接口的类

public classSimpleFilter implements Filter { //此处是接口,因此这三个方法必须都要实现。

   private FilterConfig filterConfig;

  

   public void init(FilterConfig config) throwsServletException {

            this.filterConfig = config;

   }

public voiddoFilter(ServletRequest request, ServletResponse response, FilterChain chain)

            throwsjava.io.IOException,ServletException{

            System.out.println("WithinSimpleFilter1:Filtering the Request...1");

                 //以上是请求资源之前进行拦截后的操作

HttpServletRequest req = (HttpServletRequest) request;

            ServletContextapplication = filterConfig.getServletContext();

application.log(req.getRemoteHost()+ " tried to access "+ req.getRequestURL() + " on " + newDate() + ".");//记录日志

            chain.doFilter(request,response); //提交给相应资源

                 //以上是响应到客户端之前拦截后的操作

            System.out.println("Within SimpleFilter1:Filtering the Response...1");

   }

           

   public void destroy() {

            this.filterConfig = null;

   }

}

•    (1)public voidinit(FilterConfig filterConfig)throws ServletException

•    由Web容器调用,初始化此Filter。

•    (2) public voiddoFilter(ServletRequest request,ServletResponse

•    response,FilterChain chain)throwsjava.io.IOException,ServletException

•    具体过滤处理代码。

•    doFilter() :

•    与 servlet 拥有一个 service()方法(这个方法又调用doPost() 或者doGet() 等方法)来处理请求一样,过滤器拥有单个用于处理请求和响应的方法doFilter() 。

•    这个方法接受三个输入参数:一个 ServletRequest 、ServletResponse和一个FilterChain 对象。

•    注意这里不是HttpServletRequest对象和HttpServletResponse对象

•    (3)public voiddestroy()

由Web容器调用,在过滤器被销毁之前调用。

 

此例使用Tomcat服务器讲解,把编译好的字节码文件,放在网站文件夹/WEB-INF/classes下,需建立对应的包文件夹。如本例过滤器类的全名com.ljheee.filter.SimpleFilter,需建立/WEB-INF/classes/com/ljheee/filter/ SimpleFilter.calss

关于使用Tomcat可参阅http://blog.csdn.net/ljheee/article/details/51049988

二、WEB-INF/web.xml中配置Filter

在<web-app>标签里添加

   <filter>                       

<filter-name>filter</filter-name>                      --自定义过滤器名

   <filter-class>com.ljheee.filter.SimpleFilter</filter-class>  --告诉Tomcat过滤器字节码文件位置

</filter>

<filter-mapping>

   <filter-name>filter</filter-name>

   <url-pattern>/*</url-pattern>                            -- 此处/*代表  所有页面均拦截

</filter-mapping>

•    也可以在此配置文件中指定要拦截的IP,在<filter>标签中参数

<filter>

     <filter-name>IPFilter</filter-name>

     <filter-class>com.wgw.filter.IPFilter</filter-class>

     <init-param>

            <param-name>filterIP</param-name>

            <param-value>192.168.70.82</param-value>   --要拦截的IP

     </init-param>

</filter>

相应的,在SimpleFilter类中,获取此键值对

public void init(FilterConfig config) throws ServletException{

            this.filterConfig=config;

            filterIP=config.getInitParameter("filterIP");  //获取被过滤的IP地址

            if(filterIP==null) filterIP="";             

}

有关<filter-mapping>的用法。参考《SRV.11.2 Specification of Mappings》


二、servlet监听器

1 Servlet监听器工作原理

 Servlet监听器是Web应用程序事件模型的一部分,当Web应用中的某些状态发生改变时,Servlet容器就会产生相应的事件,比如创建ServletContext对象(也就是application对象)时触发ServletContextEvent事件,创建HttpSession对象时触发HttpSessionEvent事件,Servlet监听器可接收这些事件,并可以在事件发生前、发生后可以做一些必要的处理。

2 Servlet监听器类型

         ServletContext[application]事件监听器:用于监听应用程序环境对象。

         HttpSession[session]事件监听器:用于监听用户会话对象。       

         ServletRequest[request]事件监听器:用于监听请求消息对象。

1.ServletContext事件监听器

•    对ServletContext对象进行监听的接口有ServletContextAttributeListener和ServletContextListener

•    其中ServletContextAttributeListener用于监听ServletContext对象中属性的改变,包括增加属性、删除属性和修改属性。ServletContextListener用于监听ServletContext对象本身的改变,例如ServletContext对象的创建和销毁。

2.HttpSession事件监听器

对会话对象进行监听的接口有:HttpSessionAttributeListener、HttpSessionListener、HttpSessionActivationListener和HttpSessionBindingListener。

•    其中HttpSessionAttributeListener用于监听HttpSession对象中属性的改变,例如属性的增加、删除和修改。

•    HttpSessionListener用于监听HttpSession对象的改变,例如HttpSession对象的创建与销毁。

•    HttpSessionActivationListener用于监听HttpSession对象的状态,例如HttpSession对象是被激活还是被钝化。

•    HttpSessionBindingListener用于监听HttpSession对象(该对象实现了HttpSessionBindingListener接口)的绑定状态,例如添加对象和移除对象。

3.ServletRequest事件监听器

    对请求消息对象进行监听的接口有ServletRequestListener和ServletRequestAttributeListener。

•    其中ServletRequestListener用于监听ServletRequest对象的变化,例如ServletRequest对象的创建和销毁。

•    ServletRequestAttributeListener用于监听ServletRequest对象中属性的变化,例如属性的增加、删除和修改。

这些监听器完成,对三个对象applicationrequestsession创建销毁,修改属性等方面的事件监听,自动执行一些设定的功能。

对应的都有BindingListenerAttributeListener两种listener;HttpSessionBindingListener和HttpSessionAttributeListener

BindingListener与AttributeListener的区别:

•    1.BindingListener有2个方法,valueBound(HttpSessinBindingEvent)和valueUnbount(HttpSessionBindingEvent)。实现BindingListener接口的对象被绑定到session时触发valueBound事件,解除绑定时触发valueUnbound事件。

•    2.AttributeListener接口有3个方法,attributeAdded(HttpSessionBindingEvent),attributeRemoved(HttpSessionBindingEvent),attributeReplaced(HttpSeesionEvent)。当在session中添加、移除或更改属性值时会触发相应的事件。

例:记录一个网站当前在线总人数。

(1)创建监听器类

public class OnlineListener implements HttpSessionListener{

    private intonlineCount;//定义一个代表在线人数的变量

    public OnlineListener(){onlineCount=0;}

    public voidsessionCreated(HttpSessionEvent sessionEvent) {//会话创建时的处理

        onlineCount++; 

        sessionEvent.getSession().getServletContext().setAttribute("online",newInteger(onlineCount));

    }

    public voidsessionDestroyed(HttpSessionEvent sessionEvent) {//会话销毁时的处理

        onlineCount--;

        sessionEvent.getSession().getServletContext().setAttribute("online",newInteger(onlineCount));

    }

}

(2)在web.xml文件中配置OnlineListener监听器,相关代码如下:

<listener>

     <listener-class>com.ljheee.listener.OnlineListener</listener-class>

</listener>

(3)创建JSP页面“online.jsp”,测试OnlineListener监听器,代码如下:

<%@ page language="java"pageEncoding="GBK"%>

<html>

   <head>  

           <title>使用监听器监听在线人数的例子</title>

   </head>

   <body>

   <center>

<h2>当前的在线人数:<%=(Integer)application.getAttribute("online")%></h2>

</center>

   </body>

</html>

完整JSP操作数据库,注册、登录,过滤器,监听器案例http://download.csdn.net/detail/ljheee/9491978

1 0
原创粉丝点击