注:该系列文章部分内容来自王健老师编写ssh整合开发教程
引言:
之前没有引入拦截器之前,我们使用Filter过滤器验证用户是否登录,在使用struts2之后,完全可以使用拦截器,验证用户是否已经登录,如果没有登录,则显示登录页面,要求其先登录。
第一步:书写一个方法拦截器如下:
说明:因为在当前程序中,只有一个Action类,即OneAction.java,而其中的excute方法又是登录方法,所以对于execute方法不能拦截,而对于其他方法则必须拦截,所以使用方法拦截器,代码如下:
package com.xuzheng.filter; import com.opensymphony.xwork2.Action; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionInvocation; import com.opensymphony.xwork2.interceptor.MethodFilterInterceptor; @SuppressWarnings("serial") public class ValidateLogin extends MethodFilterInterceptor{ @Override protected String doIntercept(ActionInvocation invo) throws Exception { //验证用户是否已经登录 if(ActionContext.getContext().getSession().get("user")!=null){ System.out.println("用户已经登录......"); return invo.invoke(); }else{ System.out.println("你还没有登录......"); return Action.LOGIN; } } }
<interceptors> <!-- 1、编写自己的拦截器 --> <interceptor name="validateLogin1" class="com.xuzheng.filter.ValidateLogin"> <param name="excludeMethods">execute</param> </interceptor> <!-- 2、配置一个拦截器栈 --> <interceptor-stack name="validateLogin"> <interceptor-ref name="defaultStack"></interceptor-ref> <interceptor-ref name="validateLogin1"></interceptor-ref> </interceptor-stack> </interceptors> <!-- 3、配置默认拦截器 --> <default-interceptor-ref name="validateLogin"></default-interceptor-ref> <!-- 4、配置全局结果转向 --> <global-results> <result name="login">/index.jsp</result> </global-results>
第三步:发布项目,如果在地址栏中直接输入如下:
http://127.0.0.1:8080/ssh/one!update.action 则会跳转至登录页面
图-1
至此,ssh整合系列教程到此完结。
源代码下载:
Struts2+Spring+Hibernate step by step 11 ssh整合之拦截器验证用户是否登录,布布扣,bubuko.com