拦截器对session验证的实现

来源:互联网 发布:小超市收款软件 编辑:程序博客网 时间:2024/06/07 08:35

自定义一个拦截器

package com.Hanb.fly.interceptor;import java.util.Map;import com.Hanb.fly.model.User;import com.opensymphony.xwork2.Action;import com.opensymphony.xwork2.ActionInvocation;import com.opensymphony.xwork2.interceptor.Interceptor;public class AuthorInterceptor implements Interceptor {@Overridepublic void destroy() {// TODO Auto-generated method stub}@Overridepublic void init() {// TODO Auto-generated method stub}@Overridepublic String intercept(ActionInvocation actionInvocation) throws Exception {// TODO Auto-generated method stubMap session=actionInvocation.getInvocationContext().getSession();User user=(User)session.get("user");if(user==null){System.out.println("拦截器起作用1");return Action.INPUT;}else{System.out.println("拦截器起作用2");    return actionInvocation.invoke();}}}

在struts中配置拦截器

<?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><package name="inter" extends="struts-default"><interceptors>    <interceptor name="authenticationInterceptor" class="com.Hanb.fly.interceptor.AuthorInterceptor" />    <interceptor-stack name="myStack">      <interceptor-ref name="authenticationInterceptor" />      <interceptor-ref name="defaultStack" />    </interceptor-stack>  </interceptors>    <action name="login" class="com.Hanb.fly.action.LoginAction" method="check">    <result>/index1.jsp</result>    <result name="input">/index2.jsp</result></action>    <action name="show" class="com.Hanb.fly.action.LoginAction" method="show">    <result>/index1.jsp</result>    <result name="input">/error.jsp</result>    <interceptor-ref name="myStack"></interceptor-ref></action>  </package></struts>
index.jsp为登录页面,登录成功,在session中设置user,并跳转到index1.jsp

若失败,跳转到index2.jsp。

当请求show.action时,若session中没有设置user,即没有登录,拦截器将返回input,页面跳转入error.jsp。若session中设置user了,拦截器将请求放给show.action。