本文实例讲述了java自定义拦截器及其用法。分享给大家供大家参考。具体如下:
LoginInterceptor.java文件如下:
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
|
package com.tq365.util; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.apache.struts2.ServletActionContext; import com.opensymphony.xwork2.ActionInvocation; import com.opensymphony.xwork2.interceptor.AbstractInterceptor; import com.tq365.vo.User; /** * 自定义的拦截器(放行登录操作和已经登录用户的操作) * @author archie2010 * */ public class LoginInterceptor extends AbstractInterceptor{ private static final long serialVersionUID = 1406123004582563032L; @Override public String intercept(ActionInvocation invocation) throws Exception { HttpServletRequest request = ServletActionContext.getRequest(); HttpSession session = ServletActionContext.getRequest().getSession(); User user = (User)session.getAttribute( "USER" ); // 请求的url String path = request.getServletPath(); boolean flag = false ; if ( "/loginuser.jspx" .equals(path)){ flag = true ; } else { if (user!= null ){ flag = true ; } } System.out.println(path); return flag ? invocation.invoke() : "error" ; } } |
struts.xml文件如下:
1
2
3
4
5
6
7
8
9
|
< interceptors > <!-- login拦截器 --> < interceptor name = "login" class = "com.tq365.util.LongInterceptor" /> < interceptor-stack name = "myInterceptor" > < interceptor-ref name = "login" /> < interceptor-ref name = "paramsPrepareParamsStack" /> </ interceptor-stack > </ interceptors > < default-interceptor-ref name = "myInterceptor" /> |
希望本文所述对大家的java程序设计有所帮助。