Struts2 自定义拦截器

1、实现原理:com.ioensymphony.xwork2.interceptor.interceptor 接口

2、案例需求:模拟登陆进入 index.jsp ,否则返回 login.jsp

3、页面 index.jsp

			<body>
				这个主页只有登录才能看到
			</body>
4、页面 login.jsp

			<body>
				${message }
				<form  action="">
					用户名:<input  type="text"  name ="username" /><br />
					密    码:<input  type="text"  name ="password" /><br />
				</form>
			</body>
5、struts.xml 中

			<struts>
				<package name="interceptor"  namespace="/interceptor"  extends="struts-default">
					<action name="visitIndex" class="cn.itcast.action.VisitAction"  method="execute">
						<result   name="success">/index.jsp</result>
						<result   name="login">/login.jsp</result>
					</action>
				</package>
			</struts>
6、在 VisitAction 中

			public  class  VisitAction {
				public  String  execute(){
					return  SUCCESS;
				}
			}
7、自定义拦截器 cn.itheima.interceptor.PermissionInterceptor     implements  Interceptor

			public class  PermissionInterceptor  implements  Interceptor{
				// 判断用户是否登录
				public  String  intercept(ActionInvocation  invocation)  throws  Exception{
					HttpSession   session = ServletActionContext.getRequest().getSession();
					Object  obj = session.getAttribute("user");
					if( obj == null){
						// 如果没登录
						return  "login";

					}else{
						// 如果登陆了
						return  invocation.invoke();	// 放行,调用Action方法,这里就是调 VisitAction 的方法
					}
				}

				public  void  destroy(){

				}

				public  void  init(){

				}
			}
8、使用拦截器,在 struts.xml

			<package name="interceptor"  namespace="/interceptor"  extends="struts-default">
				<interceptors>
					<interceptor  name="permissionInterceptor"   class="cn.itheima.interceptor.PermissionInterceptor"></interceptor>
				</interceptors>
				<action name="visitIndex" class="cn.itcast.action.VisitAction"  method="execute">
					<interceptor-ref  name="defaultStack"></interceptor-ref>#写上框架的拦截器,防止失效,一定放在最前面
					<interceptor-ref  name="permissionInterceptor"></interceptor-ref>#写了自定义的拦截器,框架默认的拦截器就失效了
					<result   name="success">/index.jsp</result>
					<result   name="login">/login.jsp</result>
				</action>
			</package>
9、模拟用户登录

在 1.jsp 中
	<% session.setAttribute("user", "") %>
10、在 login.jsp 页面点击登录,能够进入 index.jsp ,如果8中不模拟登录,就进入不了 index.jsp 页面。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值