首页 > 代码库 > struts2 自定义拦截,防止非法操作

struts2 自定义拦截,防止非法操作

<package name="defaults" extends="struts-default">            <interceptors>            <interceptor name="login"                class="com.zqgame.interceptor.CheckLoginInterceptor" />            <interceptor-stack name="myinterceptor">                <interceptor-ref name="login">                    <param name="excludeMethods">validateLogin</param>                </interceptor-ref>                <interceptor-ref name="defaultStack" />             </interceptor-stack>        </interceptors>        <!-- 设置所有Action自动调用的拦截器堆栈 -->        <default-interceptor-ref name="myinterceptor"></default-interceptor-ref>        <global-results>            <result name="error">/err/exception.jsp</result>            <result name="message">/err/message.jsp</result>        </global-results>                <global-exception-mappings>            <exception-mapping exception="java.lang.NullPointerException" result="error" />            <exception-mapping exception="java.lang.Exception" result="error" />        </global-exception-mappings>    </package>

 

action配置里面继承defaults:

<package name="login" namespace="/login" extends="defaults">        <action name="login_*" class="loginAction" method="{1}">                </action>    </package>

 

拦截器类实现:

public class CheckLoginInterceptor extends MethodFilterInterceptor {        private Logger log = LoggerFactory.getLogger(CheckLoginInterceptor.class);    private static final long serialVersionUID = 1L;    @Override    protected String doIntercept(ActionInvocation actionInvocation) throws Exception {        // 确认Session中是否存在LOGIN        Map<String,Object> session = actionInvocation.getInvocationContext().getSession();        String login = (String) session.get(SysKey.Login_Key);        if (login != null && login.length() > 0) {            // login不为null,登录session有效。            return actionInvocation.invoke();        } else {            // 否则非法操作,返回LOGIN            log.debug("no login, forward login page!");            return PageCode.Login;        }    } }