java無狀態登入實現方式之ThreadLocal+Cookie

來源:互聯網
上載者:User

標籤:copy   tac   uri   ica   ace   logger   ++   replace   sub   

註:本文提到的無狀態指的是無需session完畢認證、取使用者封裝資訊。

無狀態的優點:

  1。多應用單點登入:在多應用的時候僅僅需在登入server登入後。各子應用無需再次登入。

  2。多server叢集:無需製作會話共用的緩衝就可以實現。

此方案的缺點:

  1,依賴於cookie,儘管如今主流瀏覽器都支援cookie。

  2。單點登入須要各子應用屬於同一主網域名稱下(跨主網域名稱無法實現)。

實現原理:

  登入時封裝使用者資訊,並將使用者資訊通過序列化加密寫到使用者cookie。當使用者下次請求應用server時,過濾器將使用者資訊取到反解密還原序列化後放入ThreadLocal中,利用ThreadLocal的安全執行緒特性,之後操作取到使用者資訊。


使用者封裝資訊類

package com.xxx.commons.framework.bean;import java.io.Serializable;public class Principal implements Serializable {private static final long serialVersionUID = -1373760761780840081L;private Long id;private String username;private Integer userType;private Long pharmacyId;private Long saleManId;private Long ydId;private String name;public Principal(Long id, String username,Integer userType,Long pharmacyId,Long saleManId,Long ydId,String name) {this.id = id;this.username = username;this.userType = userType;this.pharmacyId = pharmacyId;this.saleManId = saleManId;this.ydId = ydId;this.setName(name);}public Long getId() {return id;}public void setId(Long id) {this.id = id;}public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}@Overridepublic String toString() {return username;}public Integer getUserType() {return userType;}public void setUserType(Integer userType) {this.userType = userType;}/** * @return pharmacyId *        */public Long getPharmacyId() {return pharmacyId;}/**  * @param pharmacyId   *        */public void setPharmacyId(Long pharmacyId) {this.pharmacyId = pharmacyId;}/** * @return saleManId *        */public Long getSaleManId() {return saleManId;}/**  * @param saleManId   *        */public void setSaleManId(Long saleManId) {this.saleManId = saleManId;}/** * @return ydId *        */public Long getYdId() {return ydId;}/**  * @param ydId   *        */public void setYdId(Long ydId) {this.ydId = ydId;}/** * get name * @return the name *        */public String getName() {return name;}/**  * set name * @param name   *        */public void setName(String name) {this.name = name;}}


使用者資訊工具類

/**    * Copyright RH Corporation 2014 著作權全部   * Created 2014年12月18日 下午1:24:27  * @version V1.0    */package com.xxx.commons.framework.utils;import com.xxx.commons.framework.bean.Principal;/**  * 加入類描寫敘述 * @authorElongDeo * @version1.0 * Created2014年12月18日 下午1:24:27 */public class UserUtil {public static final ThreadLocal<Principal> principal = new ThreadLocal<Principal>(); public static Principal getUserPrincipal(){Principal principal = UserUtil.principal.get();return principal;}public static String getUserName(){String userName = "";Principal principal = getUserPrincipal();if(principal!=null){userName = principal.getUsername();}return userName;}public static String getName(){String name = "";Principal principal = getUserPrincipal();if(principal!=null){name = principal.getName();}return name;}public static Long getUserId(){Long userId = null;Principal principal = getUserPrincipal();if(principal!=null){userId = principal.getId();}return userId;}public static Integer getUserType(){Integer userType = null;Principal principal = getUserPrincipal();if(principal!=null){userType = principal.getUserType();}return userType;}public static Long getPharmacyId(){Long pharmacyId = null;Principal principal = getUserPrincipal();if(principal!=null){pharmacyId = principal.getPharmacyId();}return pharmacyId;}public static Long getSaleManId(){Long saleManId = null;Principal principal = getUserPrincipal();if(principal!=null){saleManId = principal.getSaleManId();}return saleManId;}public static Long getYdId(){Long ydId = null;Principal principal = getUserPrincipal();if(principal!=null){ydId = principal.getYdId();}return ydId;}public static Long getBuyerId(){Long buyerId = null;Integer userType = getUserType();if(userType != null && userType > Constants.USER_ADMIN_TYPE){if(userType.equals(Constants.USER_PHARMARY_TYPE)){buyerId = getPharmacyId();}else{buyerId = getYdId();}}return buyerId;}public static String getCartYn(){String cartYn = "no";Integer userType = getUserType();if(userType > Constants.USER_ADMIN_TYPE){cartYn = "yes";}return cartYn;}}

cookies工具類(用來封裝/解析使用者資訊)

/** * CookieUtils.java Copyright ? 2008-2013 lefeng.com Inc. All Rights Reserved. */package com.xxx.commons.framework.utils;import java.util.HashMap;import java.util.Map;import javax.servlet.http.Cookie;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.apache.commons.codec.binary.Base64;import com.xxx.commons.framework.bean.Principal;import com.xxx.commons.items.PropertiesFileLoader;/** * <pre> * <P>Author : ElongDeo</P>  * <P>Date : 2014-3-10 </P> * <P>Cookie操作輔助類</P> * </pre> */public class CookieUtils {public static String DOMAIN = ".xxx.com";public static final String COOKIE_TOKEN_LOGIN = "xxx_token";public static final String COOKIE_USER_INFO = "xxx_user";static {PropertiesFileLoader instance = PropertiesFileLoader.getInstance();DOMAIN = instance.getProerties("config/user.properties","domain");}/** * 設定cookie * @param response * @param name  cookie名字 * @param value cookie值 * @param maxAge cookie生命週期  以秒為單位 */public static void addCookie(HttpServletResponse response,String name,String value,int maxAge, String domain){    Cookie cookie = new Cookie(name,value);    cookie.setDomain(domain);    cookie.setPath("/");    if(maxAge>0)  cookie.setMaxAge(maxAge);    response.addCookie(cookie);}/** * 依據名字擷取cookie * @param request * @param name cookie名字 * @return */public static Cookie getCookieByName(HttpServletRequest request,String name){    Map<String,Cookie> cookieMap = readCookieMap(request);    if(cookieMap.containsKey(name)){        Cookie cookie = (Cookie)cookieMap.get(name);        return cookie;    }else{        return null;    }   }/** * 將cookie封裝到Map裡面 * @param request * @return */public static Map<String,Cookie> readCookieMap(HttpServletRequest request){      Map<String,Cookie> cookieMap = new HashMap<String,Cookie>();    Cookie[] cookies = request.getCookies();    if(null!=cookies){        for(Cookie cookie : cookies){            cookieMap.put(cookie.getName(), cookie);        }    }    return cookieMap;}public static Principal getPrincipal(HttpServletRequest request) {Cookie cookie = getCookieByName(request, COOKIE_USER_INFO);if (cookie != null && !"".equals(cookie.getValue())) {try {return (Principal) SerializeUtils.deserialize(Base64.decodeBase64(cookie.getValue()));} catch (Exception e) {e.printStackTrace();}}return null;}public static void setPrincipal(HttpServletResponse response, Principal principal) {try {addCookie(response, COOKIE_USER_INFO, Base64.encodeBase64String(SerializeUtils.serialize(principal)), 0, DOMAIN);} catch (Exception e) {e.printStackTrace();}}public static void removePrincipal(HttpServletResponse response) {try {addCookie(response, COOKIE_USER_INFO, null, 0, DOMAIN);} catch (Exception e) {e.printStackTrace();}}}


登入寫入cookie程式碼片段

Principal principal = new Principal(userId,  login, userType, pharmacyId, saleManId, ydId, name);//假設正確,那麼寫cookie而且正確跳轉try {CookieUtils.setPrincipal(response, principal);redirect = StringUtils.isEmpty(request.getParameter("redirect"))?

LOGIN_REDIRECT_URL:request.getParameter("redirect");// 須要處理首頁PrintUtils.printToMobile(response, new ResultObject<Object>(1, redirect), "json");return;} catch (Exception e) {e.printStackTrace();}


過濾器擷取使用者資訊並放入ThreadLocal

/** *  */package com.xxx.commons.framework.filters;import java.io.IOException;import java.util.HashSet;import java.util.Set;import javax.servlet.Filter;import javax.servlet.FilterChain;import javax.servlet.FilterConfig;import javax.servlet.ServletException;import javax.servlet.ServletRequest;import javax.servlet.ServletResponse;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.apache.log4j.Logger;import com.xxx.commons.framework.utils.CookieUtils;import com.xxx.commons.framework.utils.StringUtils;import com.xxx.commons.framework.utils.UserUtil;/** * Servlet Filter implementation class AuthenticationFilter */public class PrincipalFilter implements Filter {Logger logger = Logger.getLogger(PrincipalFilter.class);private static String notLoginUrl = null;// 被忽略的全部URL.private static Set<String> mobjIgnoredUrls = new HashSet<String>();/** * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain) */public void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) throws IOException, ServletException {UserUtil.principal.set(CookieUtils.getPrincipal((HttpServletRequest)request));if(notLoginUrl != null && UserUtil.principal.get() == null && !isIgnoreUrl((HttpServletRequest)request)){((HttpServletResponse)response).sendRedirect(notLoginUrl);return;}chain.doFilter(request, response);}/** * 加入描寫敘述  * @author ElongDeo 2015年6月26日 * @param filterConfig * @throws ServletException */@Overridepublic void init(FilterConfig filterConfig) throws ServletException {notLoginUrl = filterConfig.getInitParameter("notLoginUrl");// 封裝要被忽略的URLString urlText = filterConfig.getInitParameter("ignoredUrls");if(urlText != null){urlText = urlText.replaceAll("\r\n", "").replaceAll("\t", "").trim();String[] urls = urlText.split(",");for (int i = 0; i < urls.length; i++) {mobjIgnoredUrls.add(urls[i]);}}}/** * <pre> * 驗證是否要被忽略的URL. * </pre> *  * @param pobjRequest *            the pobjRequest * @return true, if is ignore url * @author guotianchi 2011-4-20 */private boolean isIgnoreUrl(HttpServletRequest pobjRequest) {String objRequestUri = pobjRequest.getRequestURI();if (StringUtils.isNotEmpty(objRequestUri)) {int index = objRequestUri.lastIndexOf(‘/‘);if (index >= 0&& index < (objRequestUri.length() - 1)&& mobjIgnoredUrls.contains(objRequestUri.substring(index + 1, objRequestUri.length()))) {return true;}}return false;}/** * 加入描寫敘述  * @author ElongDeo 2015年6月26日 */@Overridepublic void destroy() {}}

應用serverweb.xml配置

    <filter><filter-name>PrincipalFilter</filter-name><filter-class>com.xxx.commons.framework.filters.PrincipalFilter</filter-class><init-param><param-name>notLoginUrl</param-name><param-value>/common/logout.htm</param-value></init-param><init-param><param-name>ignoredUrls</param-name><param-value>logout.htm</param-value></init-param></filter>    <filter-mapping><filter-name>PrincipalFilter</filter-name><url-pattern>/*</url-pattern></filter-mapping>


java無狀態登入實現方式之ThreadLocal+Cookie

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.