struts2攔截器裏如何知道你請求的是那個方法
使用:invocation.getInvocationContext().getName(); //輸出Priv_queryPriv,這正是我訪問的Action中的方法。
1.struts.xml中這麼定義的
- <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這麼寫
- /**
- * 權限信息控制
- * @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攔截器
- /**
- * 權限攔截器Interceptor
- * @author mengxianjun
- * @date 2011-4-8 下午03:07:24
- *
- */
- @SuppressWarnings("serial")
- @Component( "PrivInterceptor" )
- @Scope("prototype")
- public class PrivInterceptor extends MethodFilterInterceptor{
- @Resource(name = "EmployeeService")
- private EmployeeService empSafeService;//工號安全Service
- @Resource(name="EmployeeRoleService")
- private EmployeeRoleService empRoleService;
- /* (non-Javadoc)
- * @see com.opensymphony.xwork2.interceptor.MethodFilterInterceptor#doIntercept(com.opensymphony.xwork2.ActionInvocation)
- * @author mengxianjun
- * @date 2011-4-8 下午03:07:24
- */
- @SuppressWarnings("unchecked")
- @Override
- protected String doIntercept(ActionInvocation invocation) throws Exception {
- System.out.println("============"+invocation.getInvocationContext().getName());
- System.out.println("============"+invocation.getInvocationContext().getLocale());
- System.out.println("============"+invocation.getInvocationContext().getParameters());
- System.out.println("執行到攔截器裏。。。。");
- ActionContext act = invocation.getInvocationContext();
- //獲得session
- Map session = invocation.getInvocationContext().getSession();
- TEmployeeInfo sessionInfo = (TEmployeeInfo) session.get("user");
- String employee_id="";
- /**
- * 一、是否登錄
- */
- try
- {
- employee_id = sessionInfo.getEmployeeId();
- }
- catch( NullPointerException e )
- {
- act.put("message", "Session過期,請重新登錄!");
- return "loginPage";
- }
- /*=========================================================單點登錄判斷============================================*/
- HashMap<String, String> map = (HashMap<String, String>) ServletActionContext.getServletContext().getAttribute("userList");
- String sessionID_User = map.get( employee_id ); //登錄用戶session的ID
- String sessionID_Now = ServletActionContext.getRequest().getSession().getId(); //當前session的ID
- if( ! sessionID_User.trim().equals(sessionID_Now) )
- {
- act.put("message", "此賬號已登錄!");
- return "privError";
- }
- /*=========================================================單點登錄判斷============================================*/
- /**
- * 二、登錄成功後,根據URL進行權限判斷
- */
- if( !"".equals(employee_id.trim()) && null!=employee_id )
- {
- /**
- * 2.1判斷工號登錄後,業務密碼是否爲123456,是跳轉到商戶安全設置,修改業務密碼
- */
- /*TEmployeeSafe empSafe = empSafeService.queryEmployeSafe(employee_id);
- if( null!=empSafe )
- {
- String MD5password = KeyedDigestMD5.getKeyedDigest("123456","").toUpperCase();//獲得123456的MD5值
- String employeePass = empSafe.getEmployeePass();//獲得登錄密碼
- String employeePass2 = empSafe.getEmployeePass2();//獲得工號業務密碼
- if( MD5password.equals(employeePass) || MD5password.equals(employeePass2) )
- {
- act.put("message", "歡迎使用本系統,您的登錄密碼、業務密碼過於簡單,請修改!");
- return "updateEmpPassword";
- }
- }*/
- /**
- * 2.2截取請求URL
- */
- HttpServletRequest request = ServletActionContext.getRequest();
- String currentURL = request.getRequestURI();
- String targetURL = "";
- if( -1 != currentURL.indexOf("?") )//普通<form>標籤是?分隔傳來的參數
- {
- String paramURL = currentURL.substring(currentURL.indexOf("?",0), currentURL.length());//參數URL
- int targetLength = currentURL.length() - paramURL.length();//去掉請求參數Length
- targetURL = currentURL.substring(currentURL.indexOf("/",1), targetLength);
- System.out.println("去掉請求參數路徑URL:"+targetURL);
- }
- else if( -1 != currentURL.indexOf(";") )//struts2標籤<s:form>標籤是;分隔傳來的參數
- {
- String paramURL = currentURL.substring(currentURL.indexOf(";",0), currentURL.length());//參數URL
- int targetLength = currentURL.length() - paramURL.length();//去掉請求參數Length
- targetURL = currentURL.substring(currentURL.indexOf("/",1), targetLength);
- System.out.println("去掉請求參數路徑URL:"+targetURL);
- }
- else
- {
- targetURL = currentURL.substring(currentURL.indexOf("/",1), currentURL.length());
- System.out.println("請求路徑URL:"+targetURL);
- }
- /**
- * 2.3必須保證當前用戶:1.工號必須開啓2.角色已分配 3.角色已啓用 4.角色有權限集合
- */
- if("12".equals(sessionInfo.getState()))
- {
- act.put("message", "工號已鎖定!");
- return "privError";
- }
- else if("15".equals(sessionInfo.getState()))
- {
- act.put("message", "工號已註銷!");
- return "privError";
- }
- else if( sessionInfo.getRoleState()==null || "".equals(sessionInfo.getRoleState()) )
- {
- act.put("message", "未分配角色!");
- return "privError";
- }
- else if( !"10".equals(sessionInfo.getRoleState()) )
- {
- act.put("message", "該角色未啓用!");
- return "privError";
- }
- else
- {
- try
- {
- /*1.得到中間表TRolePriv集合*/
- TRolePriv rp = new TRolePriv();
- rp.setRoleNum(sessionInfo.getRoleNum());
- List<TRolePriv> rolePrivList = empRoleService.queryRolePriv(rp);
- /*2.根據中間表TRolePriv,生成TEmployeePriv集合*/
- List<TEmployeePriv> privList = new ArrayList<TEmployeePriv>();
- for( TRolePriv trp : rolePrivList )
- {
- TEmployeePriv myPriv = empRoleService.queryPrivById(trp.getPrivNum());
- if(myPriv!=null&&myPriv.getPrivUrl()!=null&&!"".equals(myPriv.getPrivUrl())){
- privList.add(myPriv);//去掉一級菜單添加進privList,privUrl爲空是一級菜單
- }
- }
- /*3.權限privUrl與targetURL比較*/
- if( privList.size()>0 )
- {
- int privState = 0;
- for( TEmployeePriv p : privList )
- {
- /**
- * 對比去掉請求參數後的URL是否一致,即/Login_login
- */
- String privUrl = p.getPrivUrl();//TEmployeePriv中privUrl,可能帶參數,可能不帶參數
- if(-1!=privUrl.indexOf("?",0)){
- String paramPrivURL = privUrl.substring(privUrl.indexOf("?",0), privUrl.length());//參數URL
- int targetPrivLength = privUrl.length() - paramPrivURL.length();//去掉請求參數Length
- privUrl = privUrl.substring(privUrl.indexOf("/",0), targetPrivLength);//TEmployeePriv中privUrl去掉參數
- }
- if( privUrl.equals(targetURL) )
- {
- privState = 1;
- }
- }
- if( 1 == privState )
- {
- return invocation.invoke();
- }
- else
- {
- System.out.println("-------得到Priv權限集合,但是無訪問權限---------");
- act.put("message", "您沒有權限 , 拒絕訪問!");
- return "privError";
- }
- }
- else
- {
- act.put("message", "您沒有相應權限 , 拒絕訪問!");
- return "privError";
- }
- }
- catch( NullPointerException e )
- {
- act.put("message", "您沒有權限 , 拒絕訪問!");
- return "privError";
- }
- }
- }
- else
- {
- act.put("message", "Session過期,請重新登錄!");
- return "loginPage";
- }
- }
- }