在struts2中使用拦截器(Interceptor)控制登录和权限

在jsp servlet中我们通常使用Servlet Filter控制用户是否登入, 是否有权限转到某个页面。在struts2中我们应该会想到他的拦截器(Interceptor), Interceptor在struts2中起着非常重要的作用。 很多struts2中的功能都是使用Interceptor实现的。

需求:简单的登入界面,让用户输入用户名、密码、记住密码(remember me)。 如果用户选中remember me的话, 下次就不需要再登入了(使用cookie实现, 用需要点击logout取消remeber me功能)。 如果用户起始输入的地址不是登入页面的话,在用户登入之后需要转到用户输入的起始地址。

我们先看看LoginInterceptor.java
Java代码
  1. package com.javaeye.dengyin2000.wallet.interceptor;   
  2.   
  3. import java.util.Map;   
  4.   
  5. import javax.servlet.http.Cookie;   
  6. import javax.servlet.http.HttpServletRequest;   
  7.   
  8. import org.apache.commons.lang.StringUtils;   
  9. import org.apache.struts2.StrutsStatics;   
  10.   
  11. import com.javaeye.dengyin2000.wallet.dao.UserDAO;   
  12. import com.javaeye.dengyin2000.wallet.dao.UserNotFoundException;   
  13. import com.javaeye.dengyin2000.wallet.domains.User;   
  14. import com.opensymphony.xwork2.ActionContext;   
  15. import com.opensymphony.xwork2.ActionInvocation;   
  16. import com.opensymphony.xwork2.interceptor.AbstractInterceptor;   
  17.   
  18. public class LoginInterceptor extends AbstractInterceptor {   
  19.     public static final String USER_SESSION_KEY="wallet.session.user";   
  20.     public static final String COOKIE_REMEMBERME_KEY="wallet.cookie.rememberme";   
  21.     public static final String GOING_TO_URL_KEY="GOING_TO";   
  22.        
  23.     private UserDAO userDao;   
  24.   
  25.     @Override  
  26.     public String intercept(ActionInvocation invocation) throws Exception {   
  27.            
  28.         ActionContext actionContext = invocation.getInvocationContext();   
  29.         HttpServletRequest request= (HttpServletRequest) actionContext.get(StrutsStatics.HTTP_REQUEST);   
  30.            
  31.         Map session = actionContext.getSession();   
  32.         if (session != null && session.get(USER_SESSION_KEY) != null){   
  33.             return invocation.invoke();   
  34.         }   
  35.            
  36.         Cookie[] cookies = request.getCookies();   
  37.         if (cookies!=null) {   
  38.             for (Cookie cookie : cookies) {   
  39.                 if (COOKIE_REMEMBERME_KEY.equals(cookie.getName())) {   
  40.                     String value = cookie.getValue();   
  41.                     if (StringUtils.isNotBlank(value)) {   
  42.                         String[] split = value.split("==");   
  43.                         String userName = split[0];   
  44.                         String password = split[1];   
  45.                         try {   
  46.                             User user = userDao   
  47.                                     .attemptLogin(userName, password);   
  48.                             session.put(USER_SESSION_KEY, user);   
  49.                         } catch (UserNotFoundException e) {   
  50.                             setGoingToURL(session, invocation);   
  51.                             return "login";   
  52.                         }   
  53.                     } else {   
  54.                         setGoingToURL(session, invocation);   
  55.                         return "login";   
  56.                     }   
  57.                     return invocation.invoke();   
  58.                 }   
  59.             }   
  60.         }   
  61.         setGoingToURL(session, invocation);   
  62.         return "login";   
  63.     }   
  64.   
  65.     private void setGoingToURL(Map session, ActionInvocation invocation){   
  66.         String url = "";   
  67.         String namespace = invocation.getProxy().getNamespace();   
  68.         if (StringUtils.isNotBlank(namespace) && !namespace.equals("/")){   
  69.             url = url + namespace;   
  70.         }   
  71.         String actionName = invocation.getProxy().getActionName();   
  72.         if (StringUtils.isNotBlank(actionName)){   
  73.             url = url + "/" + actionName + ".action";   
  74.         }   
  75.         session.put(GOING_TO_URL_KEY, url);   
  76.     }   
  77.        
  78.     public UserDAO getUserDao() {   
  79.         return userDao;   
  80.     }   
  81.   
  82.     public void setUserDao(UserDAO userDao) {   
  83.         this.userDao = userDao;   
  84.     }   
  85.   
  86. }  
package com.javaeye.dengyin2000.wallet.interceptor;

import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.StrutsStatics;

import com.javaeye.dengyin2000.wallet.dao.UserDAO;
import com.javaeye.dengyin2000.wallet.dao.UserNotFoundException;
import com.javaeye.dengyin2000.wallet.domains.User;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

public class LoginInterceptor extends AbstractInterceptor {
	public static final String USER_SESSION_KEY="wallet.session.user";
	public static final String COOKIE_REMEMBERME_KEY="wallet.cookie.rememberme";
	public static final String GOING_TO_URL_KEY="GOING_TO";
	
	private UserDAO userDao;

	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		
		ActionContext actionContext = invocation.getInvocationContext();
		HttpServletRequest request= (HttpServletRequest) actionContext.get(StrutsStatics.HTTP_REQUEST);
		
		Map session = actionContext.getSession();
		if (session != null && session.get(USER_SESSION_KEY) != null){
			return invocation.invoke();
		}
		
		Cookie[] cookies = request.getCookies();
		if (cookies!=null) {
			for (Cookie cookie : cookies) {
				if (COOKIE_REMEMBERME_KEY.equals(cookie.getName())) {
					String value = cookie.getValue();
					if (StringUtils.isNotBlank(value)) {
						String[] split = value.split("==");
						String userName = split[0];
						String password = split[1];
						try {
							User user = userDao
									.attemptLogin(userName, password);
							session.put(USER_SESSION_KEY, user);
						} catch (UserNotFoundException e) {
							setGoingToURL(session, invocation);
							return "login";
						}
					} else {
						setGoingToURL(session, invocation);
						return "login";
					}
					return invocation.invoke();
				}
			}
		}
		setGoingToURL(session, invocation);
		return "login";
	}

	private void setGoingToURL(Map session, ActionInvocation invocation){
		String url = "";
		String namespace = invocation.getProxy().getNamespace();
		if (StringUtils.isNotBlank(namespace) && !namespace.equals("/")){
			url = url + namespace;
		}
		String actionName = invocation.getProxy().getActionName();
		if (StringUtils.isNotBlank(actionName)){
			url = url + "/" + actionName + ".action";
		}
		session.put(GOING_TO_URL_KEY, url);
	}
	
	public UserDAO getUserDao() {
		return userDao;
	}

	public void setUserDao(UserDAO userDao) {
		this.userDao = userDao;
	}

}


首先判断session中有没有用户信息, 如果有的话继续, 如果没有的话,检查cookie中有没有rememberme的值,如果有的话,用==分割, 取得用户名密码进行登入。如果没有这个用户的话,记录下request的action地址然后转到登入页面。如果验证有这个用户,则继续下面的interceptor。 如果cookie中没有信息的话,则记录request的action地址然后转到登入页面。 以上就是LoginInterceptor的全部代码。

下面我们看看struts.xml

Java代码
  1. "1.0" encoding="UTF-8"?>   
  2.   
  3.     "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"  
  4.     "http://struts.apache.org/dtds/struts-2.0.dtd">   
  5.   
  6.   
  7.     <package name="default" extends="struts-default">   
  8.            
  9.             "loginInterceptor" class="loginInterceptor">   
  10.             "loginDefaultStack">   
  11.                 "loginInterceptor">   
  12.                 "defaultStack">   
  13.                
  14.            
  15.         <default-interceptor-ref name="loginDefaultStack">default-interceptor-ref>   
  16.            
  17.             "login" type="redirect">/login.jsp   
  18.                 
  19.         "index" class="indexAction">   
  20.             /index.jsp   
  21.            
  22.         "logout" class="logoutAction">   
  23.            
  24.         "login" class="loginAction" method="login">   
  25.             "redirect">${goingToURL}   
  26.             "input">/login.jsp   
  27.             "defaultStack">   
  28.            
  29.            
  30.         "register" class="registerAction">   
  31.             "redirect">/login.jsp   
  32.             "input">/register.jsp   
  33.             "defaultStack">   
  34.            
  35.     package>   
  36.   





	
		
			
			
				
				
			
		
		
		
			/login.jsp
				
		
			/index.jsp
		
		
		
		
			${goingToURL}
			/login.jsp
			
		
		
		
			/login.jsp
			/register.jsp
			
		
	


我们是使用的默认的interceptor stack是loginInterceptor, 如果你需要让不登入的用户也能访问的话,你需要配置你的action使用defaultStack。 我们这里的login, register使用的就是defaultStack。 这里要注意的是success的result是我们用LoginInterceptor设过来的值。 这样我们就能够转到用户输入的起始页面。 下面我们再来看看login.jsp 和 loginAction

Java代码
  1. <%@taglib prefix="s" uri="/struts-tags" %>   
  2. <%@ page language="java" contentType="text/html; charset=UTF-8"  
  3.     pageEncoding="UTF-8"%>   
  4.   
  5.   
  6.     "Content-Type" content="text/html; charset=UTF-8">   
  7.     Wallet-Login   
  8.   
  9.   
  10. Login

        
  11.   
  12.   
  13. "login" method="post" validate="false" theme="xhtml">   
  14. "loginName" label="Username">
      
  15. "password" label="Password">
      
  16. "Remember Me" name="rememberMe">   
  17. "%{'Login'}">    
  18.   
  19. "register.jsp">Register   
  20.   
  21.   
<%@taglib prefix="s" uri="/struts-tags" %>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>


	
	Wallet-Login


Login



Register


Java代码
  1. package com.javaeye.dengyin2000.wallet.actions;   
  2.   
  3. import java.util.Map;   
  4.   
  5. import javax.servlet.http.Cookie;   
  6. import javax.servlet.http.HttpServletRequest;   
  7. import javax.servlet.http.HttpServletResponse;   
  8.   
  9. import org.apache.commons.lang.StringUtils;   
  10. import org.apache.struts2.interceptor.CookiesAware;   
  11. import org.apache.struts2.interceptor.ServletRequestAware;   
  12. import org.apache.struts2.interceptor.ServletResponseAware;   
  13. import org.apache.struts2.interceptor.SessionAware;   
  14.   
  15. import com.javaeye.dengyin2000.wallet.dao.UserDAO;   
  16. import com.javaeye.dengyin2000.wallet.dao.UserNotFoundException;   
  17. import com.javaeye.dengyin2000.wallet.domains.User;   
  18. import com.javaeye.dengyin2000.wallet.interceptor.LoginInterceptor;   
  19. import com.opensymphony.xwork2.ActionSupport;   
  20.   
  21. public class LoginAction extends ActionSupport implements ServletResponseAware, ServletRequestAware, SessionAware, CookiesAware{   
  22.   
  23.     private UserDAO userDao;   
  24.     private String loginName;   
  25.     private String password;   
  26.     private boolean rememberMe;   
  27.     private HttpServletResponse response;   
  28.     private HttpServletRequest request;   
  29.     private Map session;   
  30.     private Map cookies;   
  31.     private String goingToURL;   
  32.     public String getGoingToURL() {   
  33.         return goingToURL;   
  34.     }   
  35.     public void setGoingToURL(String goingToURL) {   
  36.         this.goingToURL = goingToURL;   
  37.     }   
  38.     public boolean isRememberMe() {   
  39.         return rememberMe;   
  40.     }   
  41.     public void setRememberMe(boolean rememberMe) {   
  42.         this.rememberMe = rememberMe;   
  43.     }   
  44.     public String getLoginName() {   
  45.         return loginName;   
  46.     }   
  47.     public void setLoginName(String loginName) {   
  48.         this.loginName = loginName;   
  49.     }   
  50.     public String getPassword() {   
  51.         return password;   
  52.     }   
  53.     public void setPassword(String password) {   
  54.         this.password = password;   
  55.     }   
  56.        
  57.        
  58.     public String login()throws Exception{   
  59.         try {   
  60.             User user = userDao.attemptLogin(loginName, password);   
  61.             if (rememberMe){   
  62.                 Cookie cookie = new Cookie(LoginInterceptor.COOKIE_REMEMBERME_KEY, user.getLoginName() + "==" + user.getPassword());   
  63.                 cookie.setMaxAge(60 * 60 * 24 * 14);   
  64.                 response.addCookie(cookie);   
  65.             }   
  66.             session.put(LoginInterceptor.USER_SESSION_KEY, user);   
  67.             String goingToURL = (String) session.get(LoginInterceptor.GOING_TO_URL_KEY);   
  68.             if (StringUtils.isNotBlank(goingToURL)){   
  69.                 setGoingToURL(goingToURL);   
  70.                 session.remove(LoginInterceptor.GOING_TO_URL_KEY);   
  71.             }else{   
  72.                 setGoingToURL("index.action");   
  73.             }   
  74.             return SUCCESS;   
  75.         } catch (UserNotFoundException e) {   
  76.             addActionMessage("user name or password is not corrected.");   
  77.             return INPUT;   
  78.         }   
  79.     }   
  80.     public UserDAO getUserDao() {   
  81.         return userDao;   
  82.     }   
  83.     public void setUserDao(UserDAO userDao) {   
  84.         this.userDao = userDao;   
  85.     }   
  86.     public void setServletResponse(HttpServletResponse response) {   
  87.         this.response = response;   
  88.     }   
  89.     public void setServletRequest(HttpServletRequest request) {   
  90.         this.request = request;   
  91.     }   
  92.     public void setSession(Map session) {   
  93.         this.session = session;   
  94.     }   
  95.     public void setCookiesMap(Map cookies) {   
  96.         this.cookies = cookies;   
  97.     }   
  98. }  
package com.javaeye.dengyin2000.wallet.actions;

import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.interceptor.CookiesAware;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.apache.struts2.interceptor.SessionAware;

import com.javaeye.dengyin2000.wallet.dao.UserDAO;
import com.javaeye.dengyin2000.wallet.dao.UserNotFoundException;
import com.javaeye.dengyin2000.wallet.domains.User;
import com.javaeye.dengyin2000.wallet.interceptor.LoginInterceptor;
import com.opensymphony.xwork2.ActionSupport;

public class LoginAction extends ActionSupport implements ServletResponseAware, ServletRequestAware, SessionAware, CookiesAware{

	private UserDAO userDao;
	private String loginName;
	private String password;
	private boolean rememberMe;
	private HttpServletResponse response;
	private HttpServletRequest request;
	private Map session;
	private Map cookies;
	private String goingToURL;
	public String getGoingToURL() {
		return goingToURL;
	}
	public void setGoingToURL(String goingToURL) {
		this.goingToURL = goingToURL;
	}
	public boolean isRememberMe() {
		return rememberMe;
	}
	public void setRememberMe(boolean rememberMe) {
		this.rememberMe = rememberMe;
	}
	public String getLoginName() {
		return loginName;
	}
	public void setLoginName(String loginName) {
		this.loginName = loginName;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	
	
	public String login()throws Exception{
		try {
			User user = userDao.attemptLogin(loginName, password);
			if (rememberMe){
				Cookie cookie = new Cookie(LoginInterceptor.COOKIE_REMEMBERME_KEY, user.getLoginName() + "==" + user.getPassword());
				cookie.setMaxAge(60 * 60 * 24 * 14);
				response.addCookie(cookie);
			}
			session.put(LoginInterceptor.USER_SESSION_KEY, user);
			String goingToURL = (String) session.get(LoginInterceptor.GOING_TO_URL_KEY);
			if (StringUtils.isNotBlank(goingToURL)){
				setGoingToURL(goingToURL);
				session.remove(LoginInterceptor.GOING_TO_URL_KEY);
			}else{
				setGoingToURL("index.action");
			}
			return SUCCESS;
		} catch (UserNotFoundException e) {
			addActionMessage("user name or password is not corrected.");
			return INPUT;
		}
	}
	public UserDAO getUserDao() {
		return userDao;
	}
	public void setUserDao(UserDAO userDao) {
		this.userDao = userDao;
	}
	public void setServletResponse(HttpServletResponse response) {
		this.response = response;
	}
	public void setServletRequest(HttpServletRequest request) {
		this.request = request;
	}
	public void setSession(Map session) {
		this.session = session;
	}
	public void setCookiesMap(Map cookies) {
		this.cookies = cookies;
	}
}


差不多就是这么多代码了。 最后看看logoutAction

Java代码
  1. package com.javaeye.dengyin2000.wallet.actions;   
  2.   
  3. import javax.servlet.http.Cookie;   
  4. import javax.servlet.http.HttpServletRequest;   
  5. import javax.servlet.http.HttpServletResponse;   
  6. import javax.servlet.http.HttpSession;   
  7.   
  8. import org.apache.struts2.interceptor.ServletRequestAware;   
  9. import org.apache.struts2.interceptor.ServletResponseAware;   
  10.   
  11. import com.javaeye.dengyin2000.wallet.interceptor.LoginInterceptor;   
  12. import com.opensymphony.xwork2.ActionSupport;   
  13.   
  14. public class LogoutAction extends ActionSupport implements ServletRequestAware , ServletResponseAware{   
  15.   
  16.     private HttpServletRequest request;   
  17.     private HttpServletResponse response;   
  18.   
  19.     public String execute() throws Exception{   
  20.         HttpSession session = request.getSession(false);   
  21.         if (session!=null)   
  22.             session.removeAttribute(LoginInterceptor.USER_SESSION_KEY);   
  23.            
  24.         Cookie[] cookies = request.getCookies();   
  25.         if (cookies!=null) {   
  26.             for (Cookie cookie : cookies) {   
  27.                 if (LoginInterceptor.COOKIE_REMEMBERME_KEY.equals(cookie   
  28.                         .getName())) {   
  29.                     cookie.setValue("");   
  30.                     cookie.setMaxAge(0);   
  31.                     response.addCookie(cookie);   
  32.                     return "login";   
  33.                 }   
  34.             }   
  35.         }   
  36.         return "login";   
  37.     }   
  38.   
  39.     public void setServletRequest(HttpServletRequest request) {   
  40.         this.request = request;   
  41.     }   
  42.   
  43.     public void setServletResponse(HttpServletResponse response) {   
  44.         this.response = response;   
  45.     }   
  46.   
  47. }  
package com.javaeye.dengyin2000.wallet.actions;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;

import com.javaeye.dengyin2000.wallet.interceptor.LoginInterceptor;
import com.opensymphony.xwork2.ActionSupport;

public class LogoutAction extends ActionSupport implements ServletRequestAware , ServletResponseAware{

	private HttpServletRequest request;
	private HttpServletResponse response;

	public String execute() throws Exception{
		HttpSession session = request.getSession(false);
		if (session!=null)
			session.removeAttribute(LoginInterceptor.USER_SESSION_KEY);
		
		Cookie[] cookies = request.getCookies();
		if (cookies!=null) {
			for (Cookie cookie : cookies) {
				if (LoginInterceptor.COOKIE_REMEMBERME_KEY.equals(cookie
						.getName())) {
					cookie.setValue("");
					cookie.setMaxAge(0);
					response.addCookie(cookie);
					return "login";
				}
			}
		}
		return "login";
	}

	public void setServletRequest(HttpServletRequest request) {
		this.request = request;
	}

	public void setServletResponse(HttpServletResponse response) {
		this.response = response;
	}

}


这里需要注意的是需要把cookie也清理下。

applicationContext-struts.xml
Java代码
  1. "1.0" encoding="UTF-8"?>   
  2.     "-//SPRING//DTD BEAN//EN"    
  3.     "http://www.springframework.org/dtd/spring-beans.dtd">   
  4.        
  5.   
  6.        
  7.        
  8.      "indexAction" class="com.javaeye.dengyin2000.wallet.actions.IndexAction" singleton="false">   
  9.      "loginAction" class="com.javaeye.dengyin2000.wallet.actions.LoginAction" singleton="false">   
  10.         "userDao" ref="userDao" />   
  11.         
  12.         
  13.      "logoutAction" class="com.javaeye.dengyin2000.wallet.actions.LogoutAction" singleton="false">   
  14.         
  15.      "registerAction" class="com.javaeye.dengyin2000.wallet.actions.RegisterAction" singleton="false">   
  16.         
  17.         
  18.      "loginInterceptor" class="com.javaeye.dengyin2000.wallet.interceptor.LoginInterceptor">   
  19.         "userDao" ref="userDao" />   
  20.         
  21.         
  22.      "userDao" class="com.javaeye.dengyin2000.wallet.dao.UserDAOImpl">   
  23.         
  24.   


	

	
    
     
     
     	
     
     
     
     
     
     
     
     
     	
     
     
     
     



参考:http://www.vitarara.org/cms/struts_2_cookbook/creating_a_login_interceptor

你可能感兴趣的:(interceptor,struts,session,login,string,cookies,struts,2.0)