Struts2+Spring+Hibernate step by step 11 ssh拦截验证用户登录到集成

注意:该系列文章从教师王健写了一部分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;
		}
		
	}

}


第二步:将此拦截器配置到struts.xml中。例如以下:

<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整合系列教程到此完结。

源码下载:

step by step ssh 10

版权声明:本文博客原创文章。博客,未经同意,不得转载。

原文地址:https://www.cnblogs.com/mfrbuaa/p/4667716.html