| 
 
TA的每日心情|  | 开心 2021-3-12 23:18
 | 
|---|
 签到天数: 2 天 [LV.1]初来乍到 | 
 
| 
 1,创建自定义验证拦截器类:AuthenticationInterceptor.java
 package ch06.struts2.Interceptor;
 import java.util.Map;
 import com.opensymphony.xwork2.Action;
 import com.opensymphony.xwork2.ActionInvocation;
 import com.opensymphony.xwork2.interceptor.Interceptor;
 public class AuthenticationInterceptor implements Interceptor {
 private static final long serialVersionUID = 1L;
 public static final String USER_SESSION_KEY = "UserSessionKey";
 public void destroy() {
 }
 public void init() {
 }
 public String intercept(ActionInvocation actionInvocation) throws Exception {
 //取得Session
 Map session = actionInvocation.getInvocationContext().getSession();
 //从Session里或得登陆保存进session的User类
 String user = (String)session.get(USER_SESSION_KEY);
 //判断用户名是否为空
 boolean isAuthenticated = (null != user);
 if(!isAuthenticated){//如果为通过验证
 return Action.LOGIN;//返回登陆页面
 }
 return actionInvocation.invoke(); //返回验证通过
 }
 }
 2,在struts.xml配置自定义拦截器
 <!-- 配置自定义拦截器 -->
 <interceptors>
 <interceptor name="Authentication" class="ch06.struts2.Interceptor.AuthenticationInterceptor"></interceptor>
 </interceptors>
 
 <!-- 添加受验证拦截器保护的Action -->
 <action name="Welcome">
 <interceptor-ref name="Authentication"></interceptor-ref>
 <result name="success">welcome.jsp</result>
 </action>
 
 | 
 |