权限控制,顾名思义就是对于某些页面或者操作需要满足一定的权限要求才能继续继续进行。比如说:后台管理需要管理员登录,用户密码修改等操作需要用户登录等等。在Struts2中,简单的权限控制可以通过配置拦截器即可。下面我以修改密码进行举例:
(1)定义拦截器CheckInterceptor.java用于验证用户是否登录
package com.zxpm.interceptor;import java.util.Map;import com.opensymphony.xwork2.ActionInvocation;import com.opensymphony.xwork2.interceptor.Interceptor;import com.zxpm.entity.Users;public class CheckInterceptor implements Interceptor { public String intercept(ActionInvocation arg0) throws Exception { Map<String, Object> session = arg0.getInvocationContext().getSession(); Users u = (Users) session.get("user"); if(u != null) return arg0.invoke(); else return "login"; } public void destroy() { // TODO Auto-generated method stub } public void init() { // TODO Auto-generated method stub }}
(2)配置struts.xml文件:
<package name="user" namespace="/user" extends="struts-default"> <interceptors> <!-- 声明拦截器 --> <interceptor name="loginInterceptor" class="com.zxpm.interceptor.CheckInterceptor" /> <interceptor name="errorInterceptor" class="com.zxpm.interceptor.ErrorInterceptor" /> <!-- 配置拦截器栈 --> <interceptor-stack name="myErrorInterceptor"> <interceptor-ref name="defaultStack" /> <interceptor-ref name="errorInterceptor" /> </interceptor-stack> </interceptors> <!-- 覆盖底层的拦截器栈 对包中的所有action都有效 --> <default-interceptor-ref name="myErrorInterceptor" /> <global-results> <result name="errorMsg">/error.jsp</result> </global-results> <global-exception-mappings> <exception-mapping result="errorMsg" exception="java.lang.Exception"></exception-mapping> </global-exception-mappings> <action name="modifyPwd" class="user" method="modifyPassword"> <result type="redirect">/index.jsp</result> <result name="login" type="redirect">/index.jsp</result> <interceptor-ref name="loginInterceptor" /> <interceptor-ref name="defaultStack" /> </action> </package>
注:i)由于这里定义了关于异常的拦截器,因此代码显得稍多,实际上就是申明拦截器,然后在action中添加interceptor-ref即可;ii)我这个小项目因为登录操作在首页,因此直接就重定向到首页去了
本文出自 “zifangsky的个人博客” 博客,请务必保留此出处http://983836259.blog.51cto.com/7311475/1741570
原文:http://983836259.blog.51cto.com/7311475/1741570