SSH—Struts2拦截器的应用(防止未登录用户进行操作)

来源:互联网 发布:点数图交易软件 编辑:程序博客网 时间:2024/04/30 14:48

前言

    类似于京东、淘宝这些平台,如果单纯的去浏览页面上的一些商品显示,一点问题都没有,但是当你点击商品的订单详情或者想查看一下自己的购物车,那么就会出现通过登录进去的界面,这个就是今天要说的这个拦截器的功能。

内容

需求

    通过拦截器防止用户随意对界面或者个人账户进行随意的增删改查。

解决方式

1、定义一个拦截器类(类里面通过判断是否有用户存在session里面,如果没有就拦截要访问的页面)

2、struts2配置文件中配置拦截器

3、 在要拦截的action中使用拦截器接口

原理图

 

Demo部分

  • java类

/* * 说明:后台权限校验的拦截器(对没有登录的用户,是不可访问的) * 作者:周丽同 */public class PrivilegeInterceptor extends MethodFilterInterceptor{@Override//执行拦截的方法protected String doIntercept(ActionInvocation actionInvocation) throws Exception {// TODO Auto-generated method stub//判断session中是否保存了后台用户的信息AdminUser existAdminUser = (AdminUser) ServletActionContext.getRequest().getSession().getAttribute("existAdminUser");if(existAdminUser == null){//没有登录就进行访问了ActionSupport actionSupport = (ActionSupport) actionInvocation.getAction();actionSupport.addActionError("亲,您还没有登录,没有权限访问!");return "loginFail";}else{//已经登录过了return actionInvocation.invoke();}}}

  • Struts.xml配置

<!-- 定义拦截器 --><interceptors><interceptor name="PrivilegeInterceptor" class="cn.itcasst.shop.interceptor.PrivilegeInterceptor"></interceptor></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><interceptor-ref name="defaultStack"></interceptor-ref></action>

小结

    以上是本菜鸟对struts拦截器的一些片面的理解,希望在路过大神可以对本菜鸟指点一二。


感谢您的宝贵时间······

0 1