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

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.        
  8.     <package name="basePriv" extends="struts-default">  
  9.         <interceptors>  
  10.             <interceptor name="myPrivInterceptor" class="PrivInterceptor"/>  
  11.             <interceptor-stack name="b2cplatPrivInterceptor">  
  12.                 <interceptor-ref name="myPrivInterceptor">  
  13.                     <param name="includeMethods"></param>  
  14.                     <param name="excludeMethods">  
  15.                         loginMain,loginTop,loginSwitch,loginRight,login,leftMenuShow,   
  16.                         queryCityList,queryInOrOutAreaList,queryDistricts   
  17.                     </param>  
  18.                 </interceptor-ref>  
  19.                 <interceptor-ref name="defaultStack"/>  
  20.             </interceptor-stack>  
  21.         </interceptors>  
  22.            
  23.         <default-interceptor-ref name="b2cplatPrivInterceptor"/>  
  24.            
  25.         <global-results>  
  26.             <result name="privError">/errorPrivPage.jsp</result>  
  27.             <result name="updateEmpPassword">/jsp/phone/xxxx.jsp</result>  
  28.             <result name="loginPage" type="redirect">/jsp/phone/login/trunToLogin.jsp</result>  
  29.         </global-results>  
  30.            
  31.         <global-exception-mappings>  
  32.             <exception-mapping result="error" exception="java.lang.Exception">/errorPage.jsp   
  33.             </exception-mapping>  
  34.         </global-exception-mappings>  
  35.     </package>  
  36.        
  37.        
  38. <package name="managerPlatform" extends="basePriv" namespace="/">  
  39.     <action name="*_*" class="{1}Action" method="{2}">  
  40.         <result name="success">${successPath}</result>  
  41.         <result name="error">${errorPath}</result>  
  42.         <result name="input">${inputPath}</result>  
  43.         <result name="redirectAction" type="redirectAction">${redirectActionPath}</result>  
  44.         <result name="doChain" type="chain">${chainPath}</result>  
  45.         <result name="redirect" type="redirect">${redirectPath}</result>  
  46.         <result name="print" type="stream">  
  47.             <param name="contentType">application/vnd.ms-excel</param>  
  48.             <param name="inputName">inputStream</param>  
  49.             <param name="contentDisposition">filename="${printFileName}"</param>  
  50.             <param name="bufferSize">1024</param>  
  51.         </result>  
  52.     </action>  
  53. </package>  
  54.            
  55. </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.   
  10.     private static final long serialVersionUID = 1L;   
  11.     static final Logger log = Logger.getLogger(PrivAction.class);   
  12.        
  13.     @Autowired  
  14.     private PrivService privService;   
  15.        
  16.     /* 权限模型 */  
  17.     private TEmployeePriv employeePriv;   
  18.        
  19.     /**  
  20.      * 权限查询  
  21.      * @return  
  22.      */  
  23.     public String queryPriv(){   
  24.         if(employeePriv==null){   
  25.             employeePriv = new TEmployeePriv();   
  26.             successPath = "/jsp/phone/priv/priv/privList.jsp";   
  27.             return SUCCESS;   
  28.         }   
  29.         try {   
  30.             entitys = this.privService.queryAllPriv(employeePriv);   
  31.         } catch (Exception e) {   
  32.             log.error("",e);   
  33.         }   
  34.            
  35.         successPath = "/jsp/phone/priv/priv/privList.jsp?flag=true";   
  36.         return SUCCESS;   
  37.     }   
  38. }  
/**
 * 权限信息控制
 * @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.   
  8. @SuppressWarnings("serial")   
  9. @Component"PrivInterceptor" )   
  10. @Scope("prototype")   
  11. public class PrivInterceptor extends MethodFilterInterceptor{   
  12.        
  13.     @Resource(name = "EmployeeService")   
  14.     private EmployeeService empSafeService;//工号安全Service   
  15.        
  16.     @Resource(name="EmployeeRoleService")   
  17.     private EmployeeRoleService empRoleService;   
  18.        
  19.     /* (non-Javadoc)  
  20.      * @see com.opensymphony.xwork2.interceptor.MethodFilterInterceptor#doIntercept(com.opensymphony.xwork2.ActionInvocation)  
  21.      * @author mengxianjun  
  22.      * @date 2011-4-8 下午03:07:24  
  23.      */  
  24.        
  25.     @SuppressWarnings("unchecked")   
  26.     @Override  
  27.     protected String doIntercept(ActionInvocation invocation) throws Exception {   
  28.   
  29.         System.out.println("============"+invocation.getInvocationContext().getName());   
  30.         System.out.println("============"+invocation.getInvocationContext().getLocale());   
  31.         System.out.println("============"+invocation.getInvocationContext().getParameters());   
  32.            
  33.            
  34.         System.out.println("执行到拦截器里。。。。");   
  35.            
  36.         ActionContext act = invocation.getInvocationContext();   
  37.            
  38.         //获得session   
  39.         Map session = invocation.getInvocationContext().getSession();   
  40.            
  41.         TEmployeeInfo sessionInfo = (TEmployeeInfo) session.get("user");   
  42.            
  43.         String employee_id="";   
  44.            
  45.         /**  
  46.          * 一、是否登录  
  47.          */  
  48.         try  
  49.         {   
  50.             employee_id = sessionInfo.getEmployeeId();   
  51.         }   
  52.         catch( NullPointerException e )   
  53.         {   
  54.             act.put("message""Session过期,请重新登录!");   
  55.             return "loginPage";   
  56.         }   
  57.            
  58. /*=========================================================单点登录判断============================================*/  
  59.         HashMap<String, String> map = (HashMap<String, String>)  ServletActionContext.getServletContext().getAttribute("userList");   
  60.         String sessionID_User = map.get( employee_id ); //登录用户session的ID   
  61.         String sessionID_Now = ServletActionContext.getRequest().getSession().getId(); //当前session的ID   
  62.            
  63.         if( ! sessionID_User.trim().equals(sessionID_Now) )   
  64.         {   
  65.             act.put("message""此账号已登录!");   
  66.             return "privError";   
  67.         }   
  68. /*=========================================================单点登录判断============================================*/  
  69.            
  70.         /**  
  71.          * 二、登录成功后,根据URL进行权限判断  
  72.          */  
  73.         if( !"".equals(employee_id.trim()) && null!=employee_id )   
  74.         {   
  75.             /**  
  76.              * 2.1判断工号登录后,业务密码是否为123456,是跳转到商户安全设置,修改业务密码  
  77.              */  
  78.             /*TEmployeeSafe empSafe = empSafeService.queryEmployeSafe(employee_id);  
  79.             if( null!=empSafe )  
  80.             {  
  81.                 String MD5password = KeyedDigestMD5.getKeyedDigest("123456","").toUpperCase();//获得123456的MD5值  
  82.                 String employeePass = empSafe.getEmployeePass();//获得登录密码  
  83.                 String employeePass2 = empSafe.getEmployeePass2();//获得工号业务密码  
  84.                 if( MD5password.equals(employeePass) || MD5password.equals(employeePass2) )  
  85.                 {  
  86.                     act.put("message", "欢迎使用本系统,您的登录密码、业务密码过于简单,请修改!");  
  87.                     return "updateEmpPassword";  
  88.                 }  
  89.             }*/  
  90.                
  91.                
  92.             /**  
  93.              * 2.2截取请求URL  
  94.              */  
  95.             HttpServletRequest request = ServletActionContext.getRequest();   
  96.                
  97.             String currentURL = request.getRequestURI();   
  98.             String targetURL = "";   
  99.                
  100.             if( -1 != currentURL.indexOf("?") )//普通<form>标签是?分隔传来的参数   
  101.             {   
  102.                 String paramURL = currentURL.substring(currentURL.indexOf("?",0), currentURL.length());//参数URL   
  103.                    
  104.                 int targetLength = currentURL.length() - paramURL.length();//去掉请求参数Length   
  105.                    
  106.                 targetURL = currentURL.substring(currentURL.indexOf("/",1), targetLength);   
  107.                 System.out.println("去掉请求参数路径URL:"+targetURL);   
  108.             }   
  109.             else if( -1 != currentURL.indexOf(";") )//struts2标签<s:form>标签是;分隔传来的参数   
  110.             {   
  111.                 String paramURL = currentURL.substring(currentURL.indexOf(";",0), currentURL.length());//参数URL   
  112.                    
  113.                 int targetLength = currentURL.length() - paramURL.length();//去掉请求参数Length   
  114.                    
  115.                 targetURL = currentURL.substring(currentURL.indexOf("/",1), targetLength);   
  116.                 System.out.println("去掉请求参数路径URL:"+targetURL);   
  117.             }   
  118.             else  
  119.             {   
  120.                 targetURL = currentURL.substring(currentURL.indexOf("/",1), currentURL.length());   
  121.                 System.out.println("请求路径URL:"+targetURL);   
  122.             }   
  123.                
  124.                
  125.             /**  
  126.              * 2.3必须保证当前用户:1.工号必须开启2.角色已分配  3.角色已启用   4.角色有权限集合  
  127.              */  
  128.             if("12".equals(sessionInfo.getState()))   
  129.             {   
  130.                 act.put("message""工号已锁定!");   
  131.                 return "privError";   
  132.             }   
  133.             else if("15".equals(sessionInfo.getState()))   
  134.             {   
  135.                 act.put("message""工号已注销!");   
  136.                 return "privError";   
  137.             }   
  138.             else if( sessionInfo.getRoleState()==null || "".equals(sessionInfo.getRoleState()) )   
  139.             {   
  140.                 act.put("message""未分配角色!");   
  141.                 return "privError";   
  142.             }   
  143.             else if( !"10".equals(sessionInfo.getRoleState()) )   
  144.             {   
  145.                 act.put("message""该角色未启用!");   
  146.                 return "privError";   
  147.             }   
  148.             else  
  149.             {   
  150.                 try  
  151.                 {   
  152.                     /*1.得到中间表TRolePriv集合*/  
  153.                     TRolePriv rp = new TRolePriv();   
  154.                     rp.setRoleNum(sessionInfo.getRoleNum());   
  155.                     List<TRolePriv> rolePrivList = empRoleService.queryRolePriv(rp);   
  156.                        
  157.                     /*2.根据中间表TRolePriv,生成TEmployeePriv集合*/  
  158.                     List<TEmployeePriv> privList = new ArrayList<TEmployeePriv>();   
  159.                     for( TRolePriv trp : rolePrivList )   
  160.                     {   
  161.                         TEmployeePriv myPriv = empRoleService.queryPrivById(trp.getPrivNum());   
  162.                         if(myPriv!=null&&myPriv.getPrivUrl()!=null&&!"".equals(myPriv.getPrivUrl())){   
  163.                             privList.add(myPriv);//去掉一级菜单添加进privList,privUrl为空是一级菜单   
  164.                         }   
  165.                     }   
  166.                        
  167.                     /*3.权限privUrl与targetURL比较*/  
  168.                     if( privList.size()>0 )   
  169.                     {   
  170.                         int privState = 0;   
  171.                            
  172.                         for( TEmployeePriv p : privList )   
  173.                         {   
  174.                             /**  
  175.                              * 对比去掉请求参数后的URL是否一致,即/Login_login  
  176.                              */  
  177.                             String privUrl = p.getPrivUrl();//TEmployeePriv中privUrl,可能带参数,可能不带参数   
  178.                                
  179.                             if(-1!=privUrl.indexOf("?",0)){   
  180.                                 String paramPrivURL = privUrl.substring(privUrl.indexOf("?",0), privUrl.length());//参数URL   
  181.                                 int targetPrivLength = privUrl.length() - paramPrivURL.length();//去掉请求参数Length   
  182.                                 privUrl = privUrl.substring(privUrl.indexOf("/",0), targetPrivLength);//TEmployeePriv中privUrl去掉参数   
  183.                             }   
  184.                                
  185.                             if( privUrl.equals(targetURL) )   
  186.                             {   
  187.                                 privState = 1;   
  188.                             }   
  189.                         }   
  190.                         if1 == privState )   
  191.                         {   
  192.                             return invocation.invoke();   
  193.                         }   
  194.                         else  
  195.                         {   
  196.                             System.out.println("-------得到Priv权限集合,但是无访问权限---------");   
  197.                             act.put("message""您没有权限  , 拒绝访问!");   
  198.                             return "privError";   
  199.                         }   
  200.                     }   
  201.                     else  
  202.                     {   
  203.                         act.put("message""您没有相应权限 , 拒绝访问!");   
  204.                         return "privError";   
  205.                     }   
  206.                 }   
  207.                 catch( NullPointerException e )   
  208.                 {   
  209.                     act.put("message""您没有权限 , 拒绝访问!");   
  210.                     return "privError";   
  211.                 }   
  212.             }   
  213.         }   
  214.         else  
  215.         {   
  216.             act.put("message""Session过期,请重新登录!");   
  217.             return "loginPage";   
  218.         }   
  219.     }   
  220. }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值