SSH网上商城--Struts2拦截器的应用

来源:互联网 发布:时时彩网站源码 编辑:程序博客网 时间:2024/05/18 01:47

   在网上商城项目后台管理中,没有登录权限的用户是不能进行相关访问的,在此应用Struts2拦截器实现对Action访问的拦截。


   编写拦截器的两个步骤:

        1.编写一个类去实现Interceptor接口,或者继承Interceptor的子类。
        2.配置拦截器  

  

   拦截器代码:

package cn.itcast.shop.interceptor;import org.apache.struts2.ServletActionContext;import cn.itcast.shop.adminuser.vo.AdminUser;import com.opensymphony.xwork2.ActionInvocation;import com.opensymphony.xwork2.ActionSupport;import com.opensymphony.xwork2.interceptor.MethodFilterInterceptor;/** * 后台权限校验的拦截器 * 作用:对没有登录的用户是不能进行访问的 * @author DXJ * *///可以使用其他的拦截器MethodFilterInterceptor,可以对Action中的某些方法进行拦截public class PrivilegeInterceptor extends MethodFilterInterceptor{@Override//执行拦截的方法protected String doIntercept(ActionInvocation actionInvocation) throws Exception {//判断session中是否保存后台用户的信息AdminUser adminUser = (AdminUser) ServletActionContext.getRequest().getSession().getAttribute("existAdminUser");if (adminUser == null) {//没有登录进行访问ActionSupport support = (ActionSupport) actionInvocation.getAction();support.addActionError("您还没有登录!没有权限访问!");return "loginFail";} else {//已经登录过,直接放行return actionInvocation.invoke();}}}
    

   去Struts2中配置拦截器

<!-- 配置自定义拦截器 --><interceptors><interceptor name="privilegeInterceptor" class="cn.itcast.shop.interceptor.PrivilegeInterceptor"/>        </interceptors>
   

   然后在后台管理的相关内容中应用拦截器(后台登录肯定不能使用该拦截器)

<!-- 配置后台一级管理的Action --><action name="adminCategory_*" class="adminCategoryAction" method="{1}"><result name="findAll">/admin/category/list.jsp</result><result name="saveSuccess" type="redirectAction">adminCategory_findAll.action</result><result name="deleteSuccess" type="redirectAction">adminCategory_findAll.action</result><result name="editSuccess">/admin/category/edit.jsp</result><result name="updateSuccess" type="redirectAction">adminCategory_findAll.action</result><interceptor-ref name="privilegeInterceptor"/>     <interceptor-ref name="defaultStack"/>   //这是默认的</action>等等
   

   其中下边两个属性可以设置哪些方法可以拦截哪些不能拦截

   

   设置好拦截器后,对没有登录权限的用户来说,显示效果如下!即便是直接登录相关页面也无法进行操作!必须登录后才能正常操作!



0 0
原创粉丝点击