hyljava

Struts2登录拦截器

UserLoginInterceptor 拦截器类(千万不要写成abstract类,开始我就写成这样了就是加载不上去)

package com.hyl.inter;

import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;
import com.hyl.action.UserInfoAction;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;

public class UserLoginInterceptor implements Interceptor {
 public void destroy() {
  System.out.println("我是登录拦截器销毁");
 }

 public void init() {
  System.out.println("我是登录验证拦截器初始化");
 }

 public String intercept(ActionInvocation invocation) throws Exception {
  System.out.println("我正在进行登录拦截功能");
  String result = "";
  // 判断当前要调用的Action实例(对象) 是否是 登录验证的Action
  if (invocation.getAction() instanceof UserInfoAction) {
   
   result = invocation.invoke();
  } else {
   //当前要调用的不是登录的Action
   //从session中取值,判断是否是空(登录)
   //登录的Action中将登录用户信息存储到session中,key值是当前的sessionID
   HttpServletRequest request = ServletActionContext.getRequest();
   Map session = invocation.getInvocationContext().getSession();
   if (session.get(request.getSession().getId()) != null) {
    result = invocation.invoke();
   } else {
    //session中如果不存在就跳到登录页面
    return "error";
   }
  }
  return result;
 }
}

Struts配置文件内容

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
 <package name="userInfo" namespace="/userInfo"  extends="struts-default">
  <interceptors>
   <interceptor name="userInter" class="com.hyl.inter.UserLoginInterceptor"></interceptor>
   <interceptor-stack name="myStack">
<!--加载Struts默认拦截器-->
   <interceptor-ref name="defaultStack"></interceptor-ref>
   <interceptor-ref name="userInter"></interceptor-ref>
   </interceptor-stack>
  </interceptors>
  
  <default-interceptor-ref name="myStack"></default-interceptor-ref>

  <action name="*userInfoMan" class="com.hyl.action.UserInfoAction" method="{1}">
   <result name="success1" type="redirect">/menu.jsp</result>
   <result name="error" type="redirect">/user_login.jsp</result>
  </action>

 </package>

</struts>   


 

posted on 2012-08-10 18:58 何云隆 阅读(3357) 评论(1)  编辑  收藏 所属分类: Struts2

评论

# re: Struts2登录拦截器 2012-10-15 11:13 6

6  回复  更多评论   


只有注册用户登录后才能发表评论。


网站导航: