本文實(shí)例講述了Java中的攔截器、過(guò)濾器、監(jiān)聽(tīng)器用法。分享給大家供大家參考,具體如下:
一、攔截器 :是在面向切面編程的就是在你的service或者一個(gè)方法,前調(diào)用一個(gè)方法,或者在方法后調(diào)用一個(gè)方法比如動(dòng)態(tài)代理就是攔截器的簡(jiǎn)單實(shí)現(xiàn),在你調(diào)用方 法前打印出字符串(或者做其它業(yè)務(wù)邏輯的操作),也可以在你調(diào)用方法后打印出字符串,甚至在你拋出異常的時(shí)候做業(yè)務(wù)邏輯的操作。
1.Struts2攔截器是在訪問(wèn)某個(gè)Action或Action的某個(gè)方法,字段之前或之后實(shí)施攔截,并且Struts2攔截器是可插拔的,攔截器是AOP的一種實(shí)現(xiàn)。
2.攔截器棧(Interceptor Stack)Struts2攔截器棧就是將攔截器按一定的順序聯(lián)結(jié)成一條鏈。在訪問(wèn)被攔截的方法或字段時(shí),Struts2攔截器鏈中的攔截器就會(huì)按其之前定義的順序被調(diào)用。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
package com.lzw.struts.Interceptor; import com.opensymphony.xwork2.ActionInvocation; import com.opensymphony.xwork2.interceptor.MethodFilterInterceptor; public class MyInterceptor extends MethodFilterInterceptor { private static final long serialVersionUID = -6410044851077844880L; /** * 在struts.xml <param name="lzw">struts</param> */ private String lzw; public String getLzw() { return lzw; } public void setLzw(String lzw) { this .lzw = lzw; } @Override public void destroy() { System.out.println( "destroy!" ); } @Override public void init() { System.out.println( "init!" ); } @Override protected String doIntercept(ActionInvocation invocation) throws Exception { System.out.println( "MyInterceptor-start" ); System.out.println(lzw); String result = invocation.invoke(); System.out.println( "MyInterceptor-end" ); return result; } } |
1
2
3
4
5
6
7
8
9
10
11
12
13
|
package com.lzw.struts.Interceptor; import com.opensymphony.xwork2.ActionInvocation; import com.opensymphony.xwork2.interceptor.MethodFilterInterceptor; public class FirstInterceptor extends MethodFilterInterceptor { private static final long serialVersionUID = 1L; @Override protected String doIntercept(ActionInvocation invocation) throws Exception { System.out.println( "FirstInterceptor-Start" ); String result = invocation.invoke(); System.out.println( "FirstInterceptor-End" ); return result; } } |
struts.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
|
<? xml version = "1.0" encoding = "UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" "http://struts.apache.org/dtds/struts-2.3.dtd"> < struts > <!--開(kāi)發(fā)模式開(kāi)關(guān),本地可以設(shè)為true幫助調(diào)試問(wèn)題,部署到服務(wù)器上設(shè)為false--> < constant name = "struts.devMode" value = "false" /> <!--務(wù)必配上該屬性,否則會(huì)導(dǎo)致AOP注入異常--> < constant name = "struts.objectFactory.spring.autoWire.alwaysRespect" value = "true" /> < constant name = "struts.i18n.encoding" value = "UTF-8" /> < constant name = "struts.multipart.maxSize" value = "1000000000" /> < package name = "strutsLzw" extends = "struts-default" namespace = "/" > < interceptors > < interceptor name = "lzwInterceptorA" class = "com.lzw.struts.Interceptor.MyInterceptor" > < param name = "lzw" >struts</ param > </ interceptor > < interceptor name = "lzwInterceptorB" class = "com.lzw.struts.Interceptor.FirstInterceptor" > </ interceptor > <!-- 定義自己的攔截器棧 --> < interceptor-stack name = "myStack" > < interceptor-ref name = "lzwInterceptorA" ></ interceptor-ref > < interceptor-ref name = "lzwInterceptorB" ></ interceptor-ref > < interceptor-ref name = "defaultStack" ></ interceptor-ref > </ interceptor-stack > </ interceptors > <!-- 全局的每個(gè)action都會(huì)攔截 --> < default-interceptor-ref name = "myStack" ></ default-interceptor-ref > <!-- 增加method="lzwTest" 執(zhí)行LoginAction的lzwTest方法 否則執(zhí)行execute方法 --> < action name = "login" class = "com.lzw.struts.action.LoginAction" method = "lzwTest" > < result name = "success" >/result.jsp</ result > < result name = "failer" >/error.jsp</ result > < result name = "input" >/error.jsp</ result > </ action > </ package > </ struts > |
或者:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
<? xml version = "1.0" encoding = "UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" "http://struts.apache.org/dtds/struts-2.3.dtd"> < struts > < package name = "strutsLzw" extends = "struts-default" > < interceptors > < interceptor name = "lzwInterceptor" class = "com.lzw.struts.Interceptor.MyInterceptor" > < param name = "lzw" >struts</ param > </ interceptor > </ interceptors > <!-- 增加method="lzwTest" 執(zhí)行LoginAction的lzwTest方法 否則執(zhí)行execute方法 --> < action name = "login" class = "com.lzw.struts.action.LoginAction" method = "lzwTest" > < result name = "success" >/result.jsp</ result > < result name = "failer" >/error.jsp</ result > < result name = "input" >/error.jsp</ result > < interceptor-ref name = "lzwInterceptor" ></ interceptor-ref > <!--增加defaultStack 否則 驗(yàn)證攔截器不執(zhí)行,也就是 validate 方法不執(zhí)行--> < interceptor-ref name = "defaultStack" ></ interceptor-ref > </ action > </ package > </ struts > |
web.xml中加入:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
< filter > < filter-name >struts2</ filter-name > <!-- 已經(jīng)過(guò)時(shí)了<filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class> --> < filter-class >org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</ filter-class > < init-param > < param-name >actionPackages</ param-name > < param-value >com.lzw.struts.action</ param-value > </ init-param > </ filter > < filter-mapping > < filter-name >struts2</ filter-name > < url-pattern >/*</ url-pattern > </ filter-mapping > |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
|
package com.lzw.struts.action; import com.opensymphony.xwork2.ActionSupport; public class LoginAction extends ActionSupport{ private static final long serialVersionUID = 1L; private String username; private String password; public String getUsername() { return username; } public void setUsername(String username) { this .username = username; } public String getPassword() { return password; } public void setPassword(String password) { this .password = password; } @Override public String execute() throws Exception { System.out.println( "=====execute=====" ); if ( "hello" .equals( this .getUsername().trim()) && "world" .equals( this .getPassword().trim())) { return "success" ; } else { this .addFieldError( "username" , "username or password error" ); return "failer" ; } } @Override public void validate() { System.out.println( "=====validate=====" ); if ( null == this .getUsername() || "" .equals( this .getUsername().trim())) { this .addFieldError( "username" , "username required" ); } if ( null == this .getPassword() || "" .equals( this .getPassword().trim())) { this .addFieldError( "password" , "password required" ); } } public String lzwTest() { System.out.println( "======Test====" ); return SUCCESS; } } |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
<%@ page language= "java" import = "java.util.*" pageEncoding= "ISO-8859-1" %> <% String path = request.getContextPath(); String basePath = request.getScheme()+ "://" +request.getServerName()+ ":" +request.getServerPort()+path+ "/" ; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" > <html> <head> <base href= "<%=basePath%>" rel= "external nofollow" > <title>My JSP 'login.jsp' starting page</title> <meta http-equiv= "pragma" content= "no-cache" > <meta http-equiv= "cache-control" content= "no-cache" > <meta http-equiv= "expires" content= "0" > <meta http-equiv= "keywords" content= "keyword1,keyword2,keyword3" > <meta http-equiv= "description" content= "This is my page" > <!-- <link rel= "stylesheet" type= "text/css" href= "styles.css" rel= "external nofollow" > --> </head> <body> <form action= "login.action" method= "post" > username:<input type= "text" name= "username" ><br> password:<input type= "password" name= "password" ><br> <input type= "submit" value= "submit" > </form> </body> </html> |
控制臺(tái)結(jié)果:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
init! 2013 - 10 - 31 13 : 51 : 15 org.apache.coyote.AbstractProtocol start 信息: Starting ProtocolHandler [ "http-apr-8080" ] 2013 - 10 - 31 13 : 51 : 15 org.apache.coyote.AbstractProtocol start 信息: Starting ProtocolHandler [ "ajp-apr-8009" ] 2013 - 10 - 31 13 : 51 : 15 org.apache.catalina.startup.Catalina start 信息: Server startup in 1699 ms MyInterceptor-start struts FirstInterceptor-Start =====validate===== ======Test==== FirstInterceptor-End MyInterceptor-end |
二、過(guò)濾器:是在java web中,你傳入的request,response提前過(guò)濾掉一些信息,或者提前設(shè)置一些參數(shù),然后再傳入servlet或者struts的 action進(jìn)行業(yè)務(wù)邏輯,比如過(guò)濾掉非法url(不是login.do的地址請(qǐng)求,如果用戶沒(méi)有登陸都過(guò)濾掉),或者在傳入servlet或者struts的action前統(tǒng)一設(shè)置字符集,或者去除掉一些非法字符。主要為了減輕服務(wù)器負(fù)載,減少壓力
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
|
package com.lzw.filter.demo; 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; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; public class UserAccessFilter implements Filter{ @Override public void destroy() { System.out.println( "destroy!" ); } @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest)req; HttpServletResponse response = (HttpServletResponse)res; HttpSession session = request.getSession(); if (session.getAttribute( "user" )== null && request.getRequestURI().indexOf( "login.jsp" )==- 1 ){ response.sendRedirect( "login.jsp" ); return ; } chain.doFilter(req, res); } @Override public void init(FilterConfig config) throws ServletException { //ApplicationFilterConfig[name=UserFilter, filterClass=com.lzw.filter.demo.UserAccessFilter] System.out.println(config.toString()); } } |
web.xml 中加入:
1
2
3
4
5
6
7
8
|
< filter > < filter-name >UserFilter</ filter-name > < filter-class >com.lzw.filter.demo.UserAccessFilter</ filter-class > </ filter > < filter-mapping > < filter-name >UserFilter</ filter-name > < url-pattern >/jsp/*</ url-pattern > </ filter-mapping > |
1、攔截器是基于java的反射機(jī)制的,而過(guò)濾器是基于函數(shù)回調(diào)
2、過(guò)濾器依賴與servlet容器,而攔截器不依賴與servlet容器
3、攔截器只能對(duì)action請(qǐng)求起作用,而過(guò)濾器則可以對(duì)幾乎所有的請(qǐng)求起作用
4、攔截器可以訪問(wèn)action上下文、值棧里的對(duì)象,而過(guò)濾器不能
5、在action的生命周期中,攔截器可以多次被調(diào)用,而過(guò)濾器只能在容器初始化時(shí)被調(diào)用一次
在action的生命周期中,攔截器可以多次被調(diào)用,而過(guò)濾器只能在容器初始化時(shí)被調(diào)用一次
執(zhí)行順序 :過(guò)濾前 - 攔截前 - Action處理 - 攔截后 - 過(guò)濾后。
個(gè)人認(rèn)為過(guò)濾是一個(gè)橫向的過(guò)程,首先把客戶端提交的內(nèi)容進(jìn)行過(guò)濾(例如未登錄用戶不能訪問(wèn)內(nèi)部頁(yè)面的處理);
過(guò)濾通過(guò)后,攔截器將檢查用戶提交數(shù)據(jù)的驗(yàn)證,做一些前期的數(shù)據(jù)處理,接著把處理后的數(shù)據(jù)發(fā)給對(duì)應(yīng)的Action;
Action處理完成返回后,攔截器還可以做其他過(guò)程,再向上返回到過(guò)濾器的后續(xù)操作。
三、監(jiān)聽(tīng)器:Servlet的監(jiān)聽(tīng)器Listener,它是實(shí)現(xiàn)了javax.servlet.ServletContextListener接口的服務(wù)器端程序,它也是隨web應(yīng)用的啟動(dòng)而啟動(dòng),只初始化一次,隨web應(yīng)用的停止而銷毀。
主要作用是:做一些初始化的內(nèi)容添加工作、設(shè)置一些基本的內(nèi)容、比如一些參數(shù)或者是一些固定的對(duì)象等等。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
package com.lzw.filter.demo; import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; public class InitDataListener implements ServletContextListener { private static ServletContext servletContext; public static ServletContext getServletContext() { return servletContext; } @Override public void contextInitialized(ServletContextEvent contextEvent) { servletContext = contextEvent.getServletContext(); //final ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(servletContext); System.out.println( "服務(wù)器啟動(dòng)完畢!" ); System.out.println(servletContext); } @Override public void contextDestroyed(ServletContextEvent sce) {} } |
web.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
<?xml version= "1.0" encoding= "UTF-8" ?> <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" > <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file> default .html</welcome-file> <welcome-file> default .htm</welcome-file> <welcome-file> default .jsp</welcome-file> </welcome-file-list> <listener> <listener- class >com.lzw.filter.demo.InitDataListener</listener- class > </listener> </web-app> |
控制臺(tái)結(jié)果:
1
2
3
4
5
6
7
8
9
10
11
|
信息: Starting service Catalina 2013 - 10 - 31 15 : 13 : 55 org.apache.catalina.core.StandardEngine startInternal 信息: Starting Servlet Engine: Apache Tomcat/ 7.0 . 42 服務(wù)器啟動(dòng)完畢! org.apache.catalina.core.ApplicationContextFacade @7966340c 2013 - 10 - 31 15 : 13 : 56 org.apache.coyote.AbstractProtocol start 信息: Starting ProtocolHandler [ "http-apr-8080" ] 2013 - 10 - 31 15 : 13 : 56 org.apache.coyote.AbstractProtocol start 信息: Starting ProtocolHandler [ "ajp-apr-8009" ] 2013 - 10 - 31 15 : 13 : 56 org.apache.catalina.startup.Catalina start 信息: Server startup in 402 ms |
希望本文所述對(duì)大家java程序設(shè)計(jì)有所幫助。