Struts2 拦截器的使用,验证是否已经登陆。
第一步:编写拦截器类,继承AbstructInterceptor 重新Intercept()。
1.调用下一个拦截器或action之前做了什么。
2.调用下一个拦截器或者action。
3.调用拦截器或action之后做了什么。
代码:
[java] view plain copy public class LoginInterceptor extends AbstractInterceptor{ @Override public String intercept(ActionInvocation invocation) throws Exception { String result = ""; System.out.println("before invoke"); //因为要把这个拦截器设置成默认拦截器,所以如果是登陆的action则跳过。 if(MyAction.class==invocation.getAction().getClass()){ return invocation.invoke(); } //取session中的username,如果等于null则没有登陆,返回input跳转到登陆页面 if(ServletActionContext.getRequest().getSession().getAttribute("username")==null){ return "input"; } result = invocation.invoke(); System.out.println("after invoke"); return result; }第二步:在struts.xml中定义拦截器。
[html] view plain copy <interceptors> <interceptor name="loginInterceptor" class="com.interceptor.LoginInterceptor"></interceptor> <interceptor-stack name="myStack"> <interceptor-ref name="loginInterceptor"></interceptor-ref> <interceptor-ref name="defaultStack"></interceptor-ref> </interceptor-stack> </interceptors>设置成默认的拦截器
[html] view plain copy <default-interceptor-ref name="myStack"></default-interceptor-ref>如果不需要设置成默认拦截器,则在具体的action中配置
[html] view plain copy <action name="login" class="com.action.LoginAction"> <interceptor-ref name="myStack"></interceptor-ref> ......登陆提交到的action里的login()
[java] view plain copy public String login() throws Exception { String target = ""; if(username.equals("hsp")&&password.equals("hsp")){ target = "success"; this.getSession().setAttribute("username", username); } else{ target = "input"; } return target; }login.jsp代码
[html] view plain copy <body> <h2>登录</h2> <form action="myAction!login.action" method="post"> username:<input type="text" name="username"/><br/> password:<input type="password" name="password"/><br/> <input type="submit" value="login"><br/> </form> </body>struts.xml代码
[html] view plain copy <action name="myAction" class="com.action.MyAction"> <result name="success" type="redirectAction">welcom</result> </action> <action name="welcom"> <result>welcom.jsp</result> </action>当用户正确登陆后跳转到welcom.action。复制url再把浏览器关闭。重新打开浏览器,请求复制的url。拦截器会起作用,让页面跳转的登陆页面。
