第十八章 自定义拦截器

struts.xml配置拦截器:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
    <constant name="struts.enable.DynamicMethodInvocation" value="false"/>
    <constant name="struts.action.extension" value="do,action"/>
    <constant name="struts.multipart.maxSize" value="10701096"/>
    
	<package name="employee" namespace="/control/employee" extends="struts-default">
		<interceptors>  //拦截器配置
			<interceptor name="permission" class="cn.itcast.interceptor.PermissionInterceptor"/>
			<interceptor-stack name="permissionStack">
				<interceptor-ref name="defaultStack"/> //必须写在前面
				<interceptor-ref name="permission" />
			</interceptor-stack>
		</interceptors>
		<global-results>
			<result name="success">/WEB-INF/page/message.jsp</result>
		</global-results>
		<action name="list_*" class="cn.itcast.action.HelloWorldAction" method="{1}">
			<interceptor-ref name="permissionStack" />  //使用拦截器
		</action>
	</package>
</struts>



拦截器文件:

package cn.itcast.interceptor;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;

public class PermissionInterceptor implements Interceptor {

	public void destroy() {
	}

	public void init() {
	}

	public String intercept(ActionInvocation invocation) throws Exception {
		Object user = ActionContext.getContext().getSession().get("user");
		if(user!=null) return invocation.invoke(); //如果user不为null,代表用户已经登录,允许执行action中的方法
		ActionContext.getContext().put("message", "你没有权限执行该操作");
		return "success";
	}

}


当session中有user时,登陆则可以执行action

当session中没有user时,跳过action,message显示为"你没有权限执行该操作"

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值