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

前言

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

内容

需求

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

解决方式

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拦截器的一些片面的理解,希望在路过大神可以对本菜鸟指点一二。


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

评论 17
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

女汉纸一枚

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值