---
title: "struts2拦截器 获得请求方法名+获得请求参数 "
author: "guobin6125"
date: "2012-08-13T21:57:57Z"
tags: []
categories: ["Web前端"]
slug: "struts2"
draft: false
lastmod: "2012-08-13T21:57:57Z"
id: 1630879
url: "https://guobin6125.iteye.com/blog/1630879"
---

SSI框架为基础开发的，hulian平台

struts2拦截器里如何知道你请求的是那个方法  
使用:**invocation.getInvocationContext().getName();** //输出Priv\_queryPriv,这正是我访问的Action中的方法。

 

1.struts.xml中这么定义的

Xml代码 [![复制代码](http://guobin6125.iteye.com/images/icon_copy.gif)](http://guobin6125.iteye.com/admin/blogs/ "复制代码") [![收藏代码](http://guobin6125.iteye.com/images/icon_star.png)![](http://guobin6125.iteye.com/images/spinner.gif)]()

01. **&lt;struts&gt;**
02. &lt;!-- character filter --&gt;
03. **&lt;constant** name="struts.i18n.encoding" value="utf-8" **/&gt;**
04. **&lt;constant** name="struts.multipart.saveDir" value="/tmp" **/&gt;**
05. **&lt;constant** name="struts.multipart.maxSize" value="1000000000" **/&gt;**
06. &lt;!-- CONFIG Global Exception --&gt;
07. **&lt;package** name="basePriv" extends="struts-default"**&gt;**
08. **&lt;interceptors&gt;**
09. **&lt;interceptor** name="myPrivInterceptor" class="PrivInterceptor"**/&gt;**
10. **&lt;interceptor-stack** name="b2cplatPrivInterceptor"**&gt;**
11. **&lt;interceptor-ref** name="myPrivInterceptor"**&gt;**
12. **&lt;param** name="includeMethods"**&gt;&lt;/param&gt;**
13. **&lt;param** name="excludeMethods"**&gt;**
14. loginMain,loginTop,loginSwitch,loginRight,login,leftMenuShow,
15. queryCityList,queryInOrOutAreaList,queryDistricts
16. **&lt;/param&gt;**
17. **&lt;/interceptor-ref&gt;**
18. **&lt;interceptor-ref** name="defaultStack"**/&gt;**
19. **&lt;/interceptor-stack&gt;**
20. **&lt;/interceptors&gt;**
21. **&lt;default-interceptor-ref** name="b2cplatPrivInterceptor"**/&gt;**
22. **&lt;global-results&gt;**
23. **&lt;result** name="privError"**&gt;**/errorPrivPage.jsp**&lt;/result&gt;**
24. **&lt;result** name="updateEmpPassword"**&gt;**/jsp/phone/xxxx.jsp**&lt;/result&gt;**
25. **&lt;result** name="loginPage" type="redirect"**&gt;**/jsp/phone/login/trunToLogin.jsp**&lt;/result&gt;**
26. **&lt;/global-results&gt;**
27. **&lt;global-exception-mappings&gt;**
28. **&lt;exception-mapping** result="error" exception="java.lang.Exception"**&gt;**/errorPage.jsp
29. **&lt;/exception-mapping&gt;**
30. **&lt;/global-exception-mappings&gt;**
31. **&lt;/package&gt;**
32. **&lt;package** name="managerPlatform" extends="basePriv" namespace="/"**&gt;**
33. **&lt;action** name="\*\_\*" class="{1}Action" method="{2}"**&gt;**
34. **&lt;result** name="success"**&gt;**${successPath}**&lt;/result&gt;**
35. **&lt;result** name="error"**&gt;**${errorPath}**&lt;/result&gt;**
36. **&lt;result** name="input"**&gt;**${inputPath}**&lt;/result&gt;**
37. **&lt;result** name="redirectAction" type="redirectAction"**&gt;**${redirectActionPath}**&lt;/result&gt;**
38. **&lt;result** name="doChain" type="chain"**&gt;**${chainPath}**&lt;/result&gt;**
39. **&lt;result** name="redirect" type="redirect"**&gt;**${redirectPath}**&lt;/result&gt;**
40. **&lt;result** name="print" type="stream"**&gt;**
41. **&lt;param** name="contentType"**&gt;**application/vnd.ms-excel**&lt;/param&gt;**
42. **&lt;param** name="inputName"**&gt;**inputStream**&lt;/param&gt;**
43. **&lt;param** name="contentDisposition"**&gt;**filename="${printFileName}"**&lt;/param&gt;**
44. **&lt;param** name="bufferSize"**&gt;**1024**&lt;/param&gt;**
45. **&lt;/result&gt;**
46. **&lt;/action&gt;**
47. **&lt;/package&gt;**
48. **&lt;/struts&gt;**

```
<struts>
	<!-- character filter -->
	<constant name="struts.i18n.encoding" value="utf-8" />
	<constant name="struts.multipart.saveDir" value="/tmp" />
	<constant name="struts.multipart.maxSize" value="1000000000" />
	<!-- CONFIG Global Exception -->
	
	<package name="basePriv" extends="struts-default">
		<interceptors>
			<interceptor name="myPrivInterceptor" class="PrivInterceptor"/>
			<interceptor-stack name="b2cplatPrivInterceptor">
				<interceptor-ref name="myPrivInterceptor">
					<param name="includeMethods"></param>
					<param name="excludeMethods">
						loginMain,loginTop,loginSwitch,loginRight,login,leftMenuShow,
						queryCityList,queryInOrOutAreaList,queryDistricts
					</param>
				</interceptor-ref>
				<interceptor-ref name="defaultStack"/>
			</interceptor-stack>
		</interceptors>
		
		<default-interceptor-ref name="b2cplatPrivInterceptor"/>
		
		<global-results>
			<result name="privError">/errorPrivPage.jsp</result>
			<result name="updateEmpPassword">/jsp/phone/xxxx.jsp</result>
			<result name="loginPage" type="redirect">/jsp/phone/login/trunToLogin.jsp</result>
		</global-results>
		
		<global-exception-mappings>
			<exception-mapping result="error" exception="java.lang.Exception">/errorPage.jsp
			</exception-mapping>
		</global-exception-mappings>
	</package>
	
	
<package name="managerPlatform" extends="basePriv" namespace="/">
	<action name="*_*" class="{1}Action" method="{2}">
		<result name="success">${successPath}</result>
		<result name="error">${errorPath}</result>
		<result name="input">${inputPath}</result>
		<result name="redirectAction" type="redirectAction">${redirectActionPath}</result>
		<result name="doChain" type="chain">${chainPath}</result>
		<result name="redirect" type="redirect">${redirectPath}</result>
		<result name="print" type="stream">
			<param name="contentType">application/vnd.ms-excel</param>
			<param name="inputName">inputStream</param>
			<param name="contentDisposition">filename="${printFileName}"</param>
			<param name="bufferSize">1024</param>
		</result>
	</action>
</package>
		
</struts>
```

 2.Action这么写

Java代码 [![复制代码](http://guobin6125.iteye.com/images/icon_copy.gif)](http://guobin6125.iteye.com/admin/blogs/ "复制代码") [![收藏代码](http://guobin6125.iteye.com/images/icon_star.png)![](http://guobin6125.iteye.com/images/spinner.gif)]()

01. /\**
02. * 权限信息控制
03. * @author  ken
04. * @date 2011-9-13 下午15:00:46
05. \*/
06. @Scope("prototype")
07. @Controller("PrivAction")
08. **public** **class** PrivAction **extends** BaseAction{
09. **private** **static** **final** **long** serialVersionUID = 1L;
10. **static** **final** Logger log = Logger.getLogger(PrivAction.**class**);
11. @Autowired
12. **private** PrivService privService;
13. /* 权限模型 \*/
14. **private** TEmployeePriv employeePriv;
15. /\**
16. * 权限查询
17. * @return
18. \*/
19. **public** String queryPriv(){
20. **if**(employeePriv==**null**){
21. employeePriv = **new** TEmployeePriv();
22. successPath = "/jsp/phone/priv/priv/privList.jsp";
23. **return** SUCCESS;
24. }
25. **try** {
26. entitys = **this**.privService.queryAllPriv(employeePriv);
27. } **catch** (Exception e) {
28. log.error("",e);
29. }
30. successPath = "/jsp/phone/priv/priv/privList.jsp?flag=true";
31. **return** SUCCESS;
32. }
33. }

```
/**
 * 权限信息控制
 * @author  ken
 * @date 2011-9-13 下午15:00:46
 */
@Scope("prototype")
@Controller("PrivAction")
public class PrivAction extends BaseAction{

	private static final long serialVersionUID = 1L;
	static final Logger log = Logger.getLogger(PrivAction.class);
	
	@Autowired
	private PrivService privService;
	
	/* 权限模型 */
	private TEmployeePriv employeePriv;
	
	/**
	 * 权限查询
	 * @return
	 */
	public String queryPriv(){
		if(employeePriv==null){
			employeePriv = new TEmployeePriv();
			successPath = "/jsp/phone/priv/priv/privList.jsp";
			return SUCCESS;
		}
		try {
			entitys = this.privService.queryAllPriv(employeePriv);
		} catch (Exception e) {
			log.error("",e);
		}
		
		successPath = "/jsp/phone/priv/priv/privList.jsp?flag=true";
		return SUCCESS;
	}
}
```

 3.struts2拦截器

Java代码 [![复制代码](http://guobin6125.iteye.com/images/icon_copy.gif)](http://guobin6125.iteye.com/admin/blogs/ "复制代码") [![收藏代码](http://guobin6125.iteye.com/images/icon_star.png)![](http://guobin6125.iteye.com/images/spinner.gif)]()

001. /\**
002. * 权限拦截器Interceptor
003. * @author mengxianjun
004. * @date 2011-4-8 下午03:07:24
005. \*
006. \*/
007. @SuppressWarnings("serial")
008. @Component( "PrivInterceptor" )
009. @Scope("prototype")
010. **public** **class** PrivInterceptor **extends** MethodFilterInterceptor{
011. @Resource(name = "EmployeeService")
012. **private** EmployeeService empSafeService;//工号安全Service
013. @Resource(name="EmployeeRoleService")
014. **private** EmployeeRoleService empRoleService;
015. /* (non-Javadoc)
016. * @see com.opensymphony.xwork2.interceptor.MethodFilterInterceptor#doIntercept(com.opensymphony.xwork2.ActionInvocation)
017. * @author mengxianjun
018. * @date 2011-4-8 下午03:07:24
019. \*/
020. @SuppressWarnings("unchecked")
021. @Override
022. **protected** String doIntercept(ActionInvocation invocation) **throws** Exception {
023. System.out.println("============"+invocation.getInvocationContext().getName());
024. System.out.println("============"+invocation.getInvocationContext().getLocale());
025. System.out.println("============"+invocation.getInvocationContext().getParameters());
026. System.out.println("执行到拦截器里。。。。");
027. ActionContext act = invocation.getInvocationContext();
028. //获得session
029. Map session = invocation.getInvocationContext().getSession();
030. TEmployeeInfo sessionInfo = (TEmployeeInfo) session.get("user");
031. String employee\_id="";
032. /\**
033. * 一、是否登录
034. \*/
035. **try**
036. {
037. employee\_id = sessionInfo.getEmployeeId();
038. }
039. **catch**( NullPointerException e )
040. {
041. act.put("message", "Session过期，请重新登录！");
042. **return** "loginPage";
043. }
044. /\*=========================================================单点登录判断============================================\*/
045. HashMap&lt;String, String&gt; map = (HashMap&lt;String, String&gt;)  ServletActionContext.getServletContext().getAttribute("userList");
046. String sessionID\_User = map.get( employee\_id ); //登录用户session的ID
047. String sessionID\_Now = ServletActionContext.getRequest().getSession().getId(); //当前session的ID
048. **if**( ! sessionID\_User.trim().equals(sessionID\_Now) )
049. {
050. act.put("message", "此账号已登录！");
051. **return** "privError";
052. }
053. /\*=========================================================单点登录判断============================================\*/
054. /\**
055. * 二、登录成功后，根据URL进行权限判断
056. \*/
057. **if**( !"".equals(employee\_id.trim()) && **null**!=employee\_id )
058. {
059. /\**
060. * 2.1判断工号登录后，业务密码是否为123456，是跳转到商户安全设置，修改业务密码
061. \*/
062. /\*TEmployeeSafe empSafe = empSafeService.queryEmployeSafe(employee\_id);
063. if( null!=empSafe )
064. {
065. String MD5password = KeyedDigestMD5.getKeyedDigest("123456","").toUpperCase();//获得123456的MD5值
066. String employeePass = empSafe.getEmployeePass();//获得登录密码
067. String employeePass2 = empSafe.getEmployeePass2();//获得工号业务密码
068. if( MD5password.equals(employeePass) || MD5password.equals(employeePass2) )
069. {
070. act.put("message", "欢迎使用本系统，您的登录密码、业务密码过于简单，请修改！");
071. return "updateEmpPassword";
072. }
073. }\*/
074. /\**
075. * 2.2截取请求URL
076. \*/
077. HttpServletRequest request = ServletActionContext.getRequest();
078. String currentURL = request.getRequestURI();
079. String targetURL = "";
080. **if**( -1 != currentURL.indexOf("?") )//普通&lt;form&gt;标签是?分隔传来的参数
081. {
082. String paramURL = currentURL.substring(currentURL.indexOf("?",0), currentURL.length());//参数URL
083. **int** targetLength = currentURL.length() - paramURL.length();//去掉请求参数Length
084. targetURL = currentURL.substring(currentURL.indexOf("/",1), targetLength);
085. System.out.println("去掉请求参数路径URL:"+targetURL);
086. }
087. **else** **if**( -1 != currentURL.indexOf(";") )//struts2标签&lt;s:form&gt;标签是;分隔传来的参数
088. {
089. String paramURL = currentURL.substring(currentURL.indexOf(";",0), currentURL.length());//参数URL
090. **int** targetLength = currentURL.length() - paramURL.length();//去掉请求参数Length
091. targetURL = currentURL.substring(currentURL.indexOf("/",1), targetLength);
092. System.out.println("去掉请求参数路径URL:"+targetURL);
093. }
094. **else**
095. {
096. targetURL = currentURL.substring(currentURL.indexOf("/",1), currentURL.length());
097. System.out.println("请求路径URL:"+targetURL);
098. }
099. /\**
100. * 2.3必须保证当前用户：1.工号必须开启2.角色已分配  3.角色已启用   4.角色有权限集合
101. \*/
102. **if**("12".equals(sessionInfo.getState()))
103. {
104. act.put("message", "工号已锁定！");
105. **return** "privError";
106. }
107. **else** **if**("15".equals(sessionInfo.getState()))
108. {
109. act.put("message", "工号已注销！");
110. **return** "privError";
111. }
112. **else** **if**( sessionInfo.getRoleState()==**null** || "".equals(sessionInfo.getRoleState()) )
113. {
114. act.put("message", "未分配角色！");
115. **return** "privError";
116. }
117. **else** **if**( !"10".equals(sessionInfo.getRoleState()) )
118. {
119. act.put("message", "该角色未启用！");
120. **return** "privError";
121. }
122. **else**
123. {
124. **try**
125. {
126. /\*1.得到中间表TRolePriv集合\*/
127. TRolePriv rp = **new** TRolePriv();
128. rp.setRoleNum(sessionInfo.getRoleNum());
129. List&lt;TRolePriv&gt; rolePrivList = empRoleService.queryRolePriv(rp);
130. /\*2.根据中间表TRolePriv,生成TEmployeePriv集合\*/
131. List&lt;TEmployeePriv&gt; privList = **new** ArrayList&lt;TEmployeePriv&gt;();
132. **for**( TRolePriv trp : rolePrivList )
133. {
134. TEmployeePriv myPriv = empRoleService.queryPrivById(trp.getPrivNum());
135. **if**(myPriv!=**null**&&myPriv.getPrivUrl()!=**null**&&!"".equals(myPriv.getPrivUrl())){
136. privList.add(myPriv);//去掉一级菜单添加进privList，privUrl为空是一级菜单
137. }
138. }
139. /\*3.权限privUrl与targetURL比较\*/
140. **if**( privList.size()&gt;0 )
141. {
142. **int** privState = 0;
143. **for**( TEmployeePriv p : privList )
144. {
145. /\**
146. * 对比去掉请求参数后的URL是否一致，即/Login\_login
147. \*/
148. String privUrl = p.getPrivUrl();//TEmployeePriv中privUrl,可能带参数,可能不带参数
149. **if**(-1!=privUrl.indexOf("?",0)){
150. String paramPrivURL = privUrl.substring(privUrl.indexOf("?",0), privUrl.length());//参数URL
151. **int** targetPrivLength = privUrl.length() - paramPrivURL.length();//去掉请求参数Length
152. privUrl = privUrl.substring(privUrl.indexOf("/",0), targetPrivLength);//TEmployeePriv中privUrl去掉参数
153. }
154. **if**( privUrl.equals(targetURL) )
155. {
156. privState = 1;
157. }
158. }
159. **if**( 1 == privState )
160. {
161. **return** invocation.invoke();
162. }
163. **else**
164. {
165. System.out.println("-------得到Priv权限集合，但是无访问权限---------");
166. act.put("message", "您没有权限  , 拒绝访问！");
167. **return** "privError";
168. }
169. }
170. **else**
171. {
172. act.put("message", "您没有相应权限 , 拒绝访问！");
173. **return** "privError";
174. }
175. }
176. **catch**( NullPointerException e )
177. {
178. act.put("message", "您没有权限 , 拒绝访问！");
179. **return** "privError";
180. }
181. }
182. }
183. **else**
184. {
185. act.put("message", "Session过期，请重新登录！");
186. **return** "loginPage";
187. }
188. }
189. }