ITeye博客

struts2拦截器 获得请求方法名+获得请求参数

guobin6125 · 2012-08-13 21:57 · Web前端 · Markdown

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

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

 

1.struts.xml中这么定义的

Xml代码 复制代码 收藏代码

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

  1. /**
  2. * 权限信息控制
  3. * @author  ken
  4. * @date 2011-9-13 下午15:00:46
  5. */
  6. @Scope("prototype")
  7. @Controller("PrivAction")
  8. public class PrivAction extends BaseAction{
  9. 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代码 复制代码 收藏代码

  1. /**
  2. * 权限拦截器Interceptor
  3. * @author mengxianjun
  4. * @date 2011-4-8 下午03:07:24
  5. *
  6. */
  7. @SuppressWarnings("serial")
  8. @Component( "PrivInterceptor" )
  9. @Scope("prototype")
  10. public class PrivInterceptor extends MethodFilterInterceptor{
  11. @Resource(name = "EmployeeService")
  12. private EmployeeService empSafeService;//工号安全Service
  13. @Resource(name="EmployeeRoleService")
  14. private EmployeeRoleService empRoleService;
  15. /* (non-Javadoc)
  16. * @see com.opensymphony.xwork2.interceptor.MethodFilterInterceptor#doIntercept(com.opensymphony.xwork2.ActionInvocation)
  17. * @author mengxianjun
  18. * @date 2011-4-8 下午03:07:24
  19. */
  20. @SuppressWarnings("unchecked")
  21. @Override
  22. protected String doIntercept(ActionInvocation invocation) throws Exception {
  23. System.out.println("============"+invocation.getInvocationContext().getName());
  24. System.out.println("============"+invocation.getInvocationContext().getLocale());
  25. System.out.println("============"+invocation.getInvocationContext().getParameters());
  26. System.out.println("执行到拦截器里。。。。");
  27. ActionContext act = invocation.getInvocationContext();
  28. //获得session
  29. Map session = invocation.getInvocationContext().getSession();
  30. TEmployeeInfo sessionInfo = (TEmployeeInfo) session.get("user");
  31. String employee_id="";
  32. /**
  33. * 一、是否登录
  34. */
  35. try
  36. {
  37. employee_id = sessionInfo.getEmployeeId();
  38. }
  39. catch( NullPointerException e )
  40. {
  41. act.put("message", "Session过期,请重新登录!");
  42. return "loginPage";
  43. }
  44. /*=========================================================单点登录判断============================================*/
  45. HashMap<String, String> map = (HashMap<String, String>)  ServletActionContext.getServletContext().getAttribute("userList");
  46. String sessionID_User = map.get( employee_id ); //登录用户session的ID
  47. String sessionID_Now = ServletActionContext.getRequest().getSession().getId(); //当前session的ID
  48. if( ! sessionID_User.trim().equals(sessionID_Now) )
  49. {
  50. act.put("message", "此账号已登录!");
  51. return "privError";
  52. }
  53. /*=========================================================单点登录判断============================================*/
  54. /**
  55. * 二、登录成功后,根据URL进行权限判断
  56. */
  57. if( !"".equals(employee_id.trim()) && null!=employee_id )
  58. {
  59. /**
  60. * 2.1判断工号登录后,业务密码是否为123456,是跳转到商户安全设置,修改业务密码
  61. */
  62. /*TEmployeeSafe empSafe = empSafeService.queryEmployeSafe(employee_id);
  63. if( null!=empSafe )
  64. {
  65. String MD5password = KeyedDigestMD5.getKeyedDigest("123456","").toUpperCase();//获得123456的MD5值
  66. String employeePass = empSafe.getEmployeePass();//获得登录密码
  67. String employeePass2 = empSafe.getEmployeePass2();//获得工号业务密码
  68. if( MD5password.equals(employeePass) || MD5password.equals(employeePass2) )
  69. {
  70. act.put("message", "欢迎使用本系统,您的登录密码、业务密码过于简单,请修改!");
  71. return "updateEmpPassword";
  72. }
  73. }*/
  74. /**
  75. * 2.2截取请求URL
  76. */
  77. HttpServletRequest request = ServletActionContext.getRequest();
  78. String currentURL = request.getRequestURI();
  79. String targetURL = "";
  80. if( -1 != currentURL.indexOf("?") )//普通<form>标签是?分隔传来的参数
  81. {
  82. String paramURL = currentURL.substring(currentURL.indexOf("?",0), currentURL.length());//参数URL
  83. int targetLength = currentURL.length() - paramURL.length();//去掉请求参数Length
  84. targetURL = currentURL.substring(currentURL.indexOf("/",1), targetLength);
  85. System.out.println("去掉请求参数路径URL:"+targetURL);
  86. }
  87. else if( -1 != currentURL.indexOf(";") )//struts2标签<s:form>标签是;分隔传来的参数
  88. {
  89. String paramURL = currentURL.substring(currentURL.indexOf(";",0), currentURL.length());//参数URL
  90. int targetLength = currentURL.length() - paramURL.length();//去掉请求参数Length
  91. targetURL = currentURL.substring(currentURL.indexOf("/",1), targetLength);
  92. System.out.println("去掉请求参数路径URL:"+targetURL);
  93. }
  94. else
  95. {
  96. targetURL = currentURL.substring(currentURL.indexOf("/",1), currentURL.length());
  97. System.out.println("请求路径URL:"+targetURL);
  98. }
  99. /**
  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<TRolePriv> rolePrivList = empRoleService.queryRolePriv(rp);
  130. /*2.根据中间表TRolePriv,生成TEmployeePriv集合*/
  131. List<TEmployeePriv> privList = new ArrayList<TEmployeePriv>();
  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()>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. }

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。