Java中的拦截器、过滤器、监听器

来源:互联网 发布:阿里云服务器在哪里 编辑:程序博客网 时间:2024/05/02 00:38

一:拦截器 :是在面向切面编程的就是在你的service或者一个方法,前调用一个方法,或者在方法后调用一个方法比如动态代理就是拦截器的简单实现,

                           在你调用方 法前打印出字符串(或者做其它业务逻辑的操作),也可以在你调用方法后打印出字符串,甚至在你抛出异常的时候做业务逻辑的操作。 

       1.Struts2拦截器是在访问某个Action或Action的某个方法,字段之前或之后实施拦截,并且Struts2拦截器是可插拔的,拦截器是AOP的一种实现。
       2.拦截器栈(Interceptor Stack)Struts2拦截器栈就是将拦截器按一定的顺序联结成一条链。在访问被拦截的方法或字段时,Struts2拦截器链中的拦截器就会按其
          之前定义的顺序被调用。

[java] view plain copy
 print?
  1. package com.lzw.struts.Interceptor;  
  2.   
  3. import com.opensymphony.xwork2.ActionInvocation;  
  4. import com.opensymphony.xwork2.interceptor.MethodFilterInterceptor;  
  5.   
  6. public class MyInterceptor extends MethodFilterInterceptor {  
  7.   
  8.     private static final long serialVersionUID = -6410044851077844880L;  
  9.       
  10.     /** 
  11.      * 在struts.xml <param name="lzw">struts</param>  
  12.      */  
  13.     private String lzw;  
  14.       
  15.     public String getLzw() {  
  16.         return lzw;  
  17.     }  
  18.   
  19.     public void setLzw(String lzw) {  
  20.         this.lzw = lzw;  
  21.     }  
  22.   
  23.     @Override  
  24.     public void destroy() {  
  25.         System.out.println("destroy!");  
  26.     }  
  27.   
  28.     @Override  
  29.     public void init() {  
  30.         System.out.println("init!");  
  31.     }  
  32.   
  33.     @Override  
  34.     protected String doIntercept(ActionInvocation invocation) throws Exception {  
  35.         System.out.println("MyInterceptor-start");  
  36.         System.out.println(lzw);  
  37.         String result = invocation.invoke();  
  38.         System.out.println("MyInterceptor-end");  
  39.         return result;  
  40.     }  
  41. }  
[java] view plain copy
 print?
  1. package com.lzw.struts.Interceptor;  
  2.   
  3. import com.opensymphony.xwork2.ActionInvocation;  
  4. import com.opensymphony.xwork2.interceptor.MethodFilterInterceptor;  
  5.   
  6. public class FirstInterceptor extends MethodFilterInterceptor {  
  7.   
  8.     private static final long serialVersionUID = 1L;  
  9.       
  10.     @Override  
  11.     protected String doIntercept(ActionInvocation invocation) throws Exception {  
  12.         System.out.println("FirstInterceptor-Start");  
  13.         String result = invocation.invoke();  
  14.         System.out.println("FirstInterceptor-End");  
  15.         return result;  
  16.     }  
  17. }  
struts.xml
[java] view plain copy
 print?
  1. <?xml version="1.0" encoding="UTF-8" ?>  
  2.   
  3. <!DOCTYPE struts PUBLIC  
  4.     "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"  
  5.     "http://struts.apache.org/dtds/struts-2.3.dtd">  
  6.   
  7. <struts>  
  8.     <!--开发模式开关,本地可以设为true帮助调试问题,部署到服务器上设为false-->  
  9.     <constant name="struts.devMode" value="false"/>  
  10.     <!--务必配上该属性,否则会导致AOP注入异常-->   
  11.     <constant name="struts.objectFactory.spring.autoWire.alwaysRespect" value="true"/>  
  12.     <constant name="struts.i18n.encoding" value="UTF-8" />  
  13.     <constant name="struts.multipart.maxSize" value="1000000000"/>  
  14.     <package name="strutsLzw" extends="struts-default" namespace="/">  
  15.         <interceptors>  
  16.             <interceptor name="lzwInterceptorA" class="com.lzw.struts.Interceptor.MyInterceptor">  
  17.                 <param name="lzw">struts</param>  
  18.             </interceptor>  
  19.             <interceptor name="lzwInterceptorB" class="com.lzw.struts.Interceptor.FirstInterceptor">  
  20.             </interceptor>  
  21.             <!-- 定义自己的拦截器栈 -->  
  22.             <interceptor-stack name="myStack">  
  23.                 <interceptor-ref name="lzwInterceptorA"></interceptor-ref>  
  24.                 <interceptor-ref name="lzwInterceptorB"></interceptor-ref>  
  25.                 <interceptor-ref name="defaultStack"></interceptor-ref>  
  26.             </interceptor-stack>  
  27.         </interceptors>  
  28.         <!-- 全局的每个action都会拦截 -->  
  29.         <default-interceptor-ref name="myStack"></default-interceptor-ref>  
  30.           
  31.         <!-- 增加method="lzwTest" 执行LoginAction的lzwTest方法 否则执行execute方法 -->  
  32.         <action name="login" class="com.lzw.struts.action.LoginAction" method="lzwTest">  
  33.             <result name="success">/result.jsp</result>  
  34.             <result name="failer">/error.jsp</result>  
  35.             <result name="input">/error.jsp</result>  
  36.         </action>  
  37.     </package>  
  38. </struts>  
或者:
[java] view plain copy
 print?
  1. <?xml version="1.0" encoding="UTF-8" ?>  
  2.   
  3. <!DOCTYPE struts PUBLIC  
  4.     "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"  
  5.     "http://struts.apache.org/dtds/struts-2.3.dtd">  
  6.   
  7. <struts>  
  8.     <package name="strutsLzw" extends="struts-default">  
  9.         <interceptors>  
  10.             <interceptor name="lzwInterceptor" class="com.lzw.struts.Interceptor.MyInterceptor">  
  11.                 <param name="lzw">struts</param>  
  12.             </interceptor>  
  13.         </interceptors>  
  14.         <!-- 增加method="lzwTest" 执行LoginAction的lzwTest方法 否则执行execute方法 -->  
  15.         <action name="login" class="com.lzw.struts.action.LoginAction" method="lzwTest">  
  16.             <result name="success">/result.jsp</result>  
  17.             <result name="failer">/error.jsp</result>  
  18.             <result name="input">/error.jsp</result>  
  19.             <interceptor-ref name="lzwInterceptor"></interceptor-ref>  
  20.             <!--增加defaultStack 否则 验证拦截器不执行,也就是  validate 方法不执行-->  
  21.             <interceptor-ref name="defaultStack"></interceptor-ref>  
  22.         </action>  
  23.     </package>  
  24. </struts>  
web.xml中加入:
[java] view plain copy
 print?
  1. <filter>  
  2.      <filter-name>struts2</filter-name>  
  3.      <!-- 已经过时了<filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>  -->  
  4.      <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>  
  5.      <init-param>  
  6.         <param-name>actionPackages</param-name>  
  7.         <param-value>com.lzw.struts.action</param-value>  
  8.      </init-param>  
  9.  </filter>  
  10.  <filter-mapping>  
  11.       <filter-name>struts2</filter-name>  
  12.       <url-pattern>/*</url-pattern>  
  13.  </filter-mapping>  
[java] view plain copy
 print?
  1. package com.lzw.struts.action;  
  2.   
  3. import com.opensymphony.xwork2.ActionSupport;  
  4.   
  5. public class LoginAction extends ActionSupport{  
  6.   
  7.     private static final long serialVersionUID = 1L;  
  8.       
  9.     private String username;  
  10.     private String password;  
  11.       
  12.     public String getUsername() {  
  13.         return username;  
  14.     }  
  15.     public void setUsername(String username) {  
  16.         this.username = username;  
  17.     }  
  18.     public String getPassword() {  
  19.         return password;  
  20.     }  
  21.     public void setPassword(String password) {  
  22.         this.password = password;  
  23.     }  
  24.       
  25.     @Override  
  26.     public String execute() throws Exception {  
  27.         System.out.println("=====execute=====");  
  28.         if ("hello".equals(this.getUsername().trim()) && "world".equals(this.getPassword().trim())) {  
  29.             return "success";  
  30.         } else {  
  31.             this.addFieldError("username""username or password error");  
  32.             return "failer";  
  33.         }  
  34.     }  
  35.       
  36.     @Override  
  37.     public void validate() {  
  38.         System.out.println("=====validate=====");  
  39.         if (null == this.getUsername() || "".equals(this.getUsername().trim())) {  
  40.             this.addFieldError("username""username required");  
  41.         }  
  42.         if (null == this.getPassword() || "".equals(this.getPassword().trim())) {  
  43.             this.addFieldError("password""password required");  
  44.         }  
  45.     }  
  46.       
  47.     public String lzwTest() {  
  48.         System.out.println("======Test====");  
  49.         return SUCCESS;  
  50.     }  
  51.       
  52. }  

[java] view plain copy
 print?
  1. <%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>  
  2. <%  
  3. String path = request.getContextPath();  
  4. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
  5. %>  
  6.   
  7. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  8. <html>  
  9.   <head>  
  10.     <base href="<%=basePath%>">  
  11.       
  12.     <title>My JSP 'login.jsp' starting page</title>  
  13.       
  14.     <meta http-equiv="pragma" content="no-cache">  
  15.     <meta http-equiv="cache-control" content="no-cache">  
  16.     <meta http-equiv="expires" content="0">      
  17.     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">  
  18.     <meta http-equiv="description" content="This is my page">  
  19.     <!--  
  20.     <link rel="stylesheet" type="text/css" href="styles.css">  
  21.     -->  
  22.   
  23.   </head>   
  24.   <body>   
  25.       <form action="login.action" method="post">    
  26.           username:<input type="text" name="username"><br>  
  27.           password:<input type="password" name="password"><br>  
  28.       <input type="submit" value="submit">   
  29.       </form>   
  30.   </body>  
  31. </html>  

控制台结果:
[java] view plain copy
 print?
  1. init!  
  2. 2013-10-31 13:51:15 org.apache.coyote.AbstractProtocol start  
  3. 信息: Starting ProtocolHandler ["http-apr-8080"]  
  4. 2013-10-31 13:51:15 org.apache.coyote.AbstractProtocol start  
  5. 信息: Starting ProtocolHandler ["ajp-apr-8009"]  
  6. 2013-10-31 13:51:15 org.apache.catalina.startup.Catalina start  
  7. 信息: Server startup in 1699 ms  
  8. MyInterceptor-start  
  9. struts  
  10. FirstInterceptor-Start  
  11. =====validate=====  
  12. ======Test====  
  13. FirstInterceptor-End  
  14. MyInterceptor-end  
二: 过滤器:是在java web中,你传入的request,response提前过滤掉一些信息,或者提前设置一些参数,
然后再传入servlet或者struts的 action进行业务逻辑,比如过滤掉非法url(不是login.do的地址请求,如果用户没有登陆都过滤掉),
或者在传入servlet或者struts的action前统一设置字符集,或者去除掉一些非法字符。主要为了减轻服务器负载,减少压力
[java] view plain copy
 print?
  1. package com.lzw.filter.demo;  
  2.   
  3. import java.io.IOException;  
  4.   
  5. import javax.servlet.Filter;  
  6. import javax.servlet.FilterChain;  
  7. import javax.servlet.FilterConfig;  
  8. import javax.servlet.ServletException;  
  9. import javax.servlet.ServletRequest;  
  10. import javax.servlet.ServletResponse;  
  11. import javax.servlet.http.HttpServletRequest;  
  12. import javax.servlet.http.HttpServletResponse;  
  13. import javax.servlet.http.HttpSession;  
  14.   
  15. public class UserAccessFilter implements Filter{  
  16.   
  17.     @Override  
  18.     public void destroy() {  
  19.         System.out.println("destroy!");  
  20.     }  
  21.   
  22.     @Override  
  23.     public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)   
  24.             throws IOException, ServletException {    
  25.         HttpServletRequest request = (HttpServletRequest)req;   
  26.         HttpServletResponse response = (HttpServletResponse)res;  
  27.         HttpSession session = request.getSession();  
  28.         if(session.getAttribute("user")== null && request.getRequestURI().indexOf("login.jsp")==-1 ){   
  29.             response.sendRedirect("login.jsp");   
  30.             return ;   
  31.         }   
  32.         chain.doFilter(req, res);   
  33.     }  
  34.   
  35.     @Override  
  36.     public void init(FilterConfig config) throws ServletException {  
  37.         //ApplicationFilterConfig[name=UserFilter, filterClass=com.lzw.filter.demo.UserAccessFilter]  
  38.         System.out.println(config.toString());  
  39.     }  
  40.   
  41. }  

web.xml 中加入:
[java] view plain copy
 print?
  1. <filter>   
  2.         <filter-name>UserFilter</filter-name>   
  3.         <filter-class>com.lzw.filter.demo.UserAccessFilter</filter-class>   
  4.     </filter>   
  5.     <filter-mapping>   
  6.         <filter-name>UserFilter</filter-name>   
  7.         <url-pattern>/jsp/*</url-pattern>   
  8.     </filter-mapping>   

1、拦截器是基于java的反射机制的,而过滤器是基于函数回调 
2、过滤器依赖与servlet容器,而拦截器不依赖与servlet容器 
3、拦截器只能对action请求起作用,而过滤器则可以对几乎所有的请求起作用 
4、拦截器可以访问action上下文、值栈里的对象,而过滤器不能 
5、在action的生命周期中,拦截器可以多次被调用,而过滤器只能在容器初始化时被调用一次 

在action的生命周期中,拦截器可以多次被调用,而过滤器只能在容器初始化时被调用一次
执行顺序 :过滤前 - 拦截前 - Action处理 - 拦截后 - 过滤后。
个人认为过滤是一个横向的过程,首先把客户端提交的内容进行过滤(例如未登录用户不能访问内部页面的处理);
过滤通过后,拦截器将检查用户提交数据的验证,做一些前期的数据处理,接着把处理后的数据发给对应的Action;
Action处理完成返回后,拦截器还可以做其他过程,再向上返回到过滤器的后续操作。


三:监听器:Servlet的监听器Listener,它是实现了javax.servlet.ServletContextListener
           接口的服务器端程序,它也是随web应用的启动而启动,只初始化一次,随web应用的停止而销毁。
                 主要作用是:做一些初始化的内容添加工作、设置一些基本的内容、比如一些参数或者是一些固定的对象等等。
[java] view plain copy
 print?
  1. package com.lzw.filter.demo;  
  2.   
  3. import javax.servlet.ServletContext;  
  4. import javax.servlet.ServletContextEvent;  
  5. import javax.servlet.ServletContextListener;  
  6.   
  7. public class InitDataListener implements ServletContextListener {  
  8.       
  9.     private static ServletContext servletContext;  
  10.       
  11.     public static ServletContext getServletContext() {  
  12.         return servletContext;  
  13.     }  
  14.   
  15.     @Override  
  16.     public void contextInitialized(ServletContextEvent contextEvent) {  
  17.         servletContext = contextEvent.getServletContext();  
  18.         //final ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(servletContext);  
  19.         System.out.println("服务器启动完毕!");  
  20.         System.out.println(servletContext);  
  21.     }  
  22.       
  23.     @Override  
  24.     public void contextDestroyed(ServletContextEvent sce) {}  
  25.   
  26. }  
web.xml 
[java] view plain copy
 print?
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">  
  3.   <welcome-file-list>  
  4.     <welcome-file>index.html</welcome-file>  
  5.     <welcome-file>index.htm</welcome-file>  
  6.     <welcome-file>index.jsp</welcome-file>  
  7.     <welcome-file>default.html</welcome-file>  
  8.     <welcome-file>default.htm</welcome-file>  
  9.     <welcome-file>default.jsp</welcome-file>  
  10.   </welcome-file-list>  
  11.     
  12.    <listener>  
  13.         <listener-class>com.lzw.filter.demo.InitDataListener</listener-class>  
  14.    </listener>  
  15. </web-app>  

控制台结果:
[java] view plain copy
 print?
  1. 信息: Starting service Catalina  
  2. 2013-10-31 15:13:55 org.apache.catalina.core.StandardEngine startInternal  
  3. 信息: Starting Servlet Engine: Apache Tomcat/7.0.42  
  4. 服务器启动完毕!  
  5. org.apache.catalina.core.ApplicationContextFacade@7966340c  
  6. 2013-10-31 15:13:56 org.apache.coyote.AbstractProtocol start  
  7. 信息: Starting ProtocolHandler ["http-apr-8080"]  
  8. 2013-10-31 15:13:56 org.apache.coyote.AbstractProtocol start  
  9. 信息: Starting ProtocolHandler ["ajp-apr-8009"]  
  10. 2013-10-31 15:13:56 org.apache.catalina.startup.Catalina start  
  11. 信息: Server startup in 402 ms  

0 0
原创粉丝点击