ThreadLocal + Cookie for java stateless login implementation

Source: Internet
Author: User

ThreadLocal + Cookie for java stateless login implementation

Note:The stateless State mentioned in this Article refers to the absence of session authentication and user encapsulation information.

Benefits of stateless:

1. Single Sign-on for multiple applications: After logging on to the server for multiple applications, each sub-application does not need to log on again.

2. multi-server cluster: No need to create a cache for session sharing.

Disadvantages of this solution:

1. Relying on cookies, although mainstream browsers currently support cookies.

2. Single-point logon requires that each sub-application belongs to the same primary domain name (cross-primary domain name cannot be implemented ).

Implementation principle:

User information is encapsulated during logon, and user information is serialized and encrypted to the user cookie. When the user requests the application server the next time, the filter obtains the user information, decrypts the user information, and stores it in ThreadLocal. The ThreadLocal thread security feature is used to obtain the user information.

 

User encapsulation Information

 

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;}}

 

 

User information tool

 

/*** Copyright RH Corporation 2014 Copyright ownership * Created December 18, 2014 1:24:27 * @ version V1.0 */package com. xxx. commons. framework. utils; import com. xxx. commons. framework. bean. principal;/*** add class description * @ authorElongDeo * @ version1.0 * Created December 18, 2014 1:24:27 */public class UserUtil {public static final ThreadLocal
 
  
Principal = new ThreadLocal
  
   
(); 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 (used to encapsulate/parse user information)

 

 

/** * 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;/** * 
* 

Author: ElongDeo

*

Date: 2014-3-10

*

Cookie operation helper

**/Public class CookieUtils {public static String DOMAIN = .xxx.com; public static final String token = xxx_token; public static final String COOKIE_USER_INFO = xxx_user; static {PropertiesFileLoader instance = PropertiesFileLoader. getInstance (); DOMAIN = instance. getProerties (config/user. properties, domain );} /***** set cookie * @ param response * @ param name cookie name * @ param value cookie value * @ param maxAge cookie lifecycle in seconds */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);}/*** obtain cookie by name * @ param request * @ param name cookie name * @ return */public static Cookie getCookieByName (HttpServletRequest request, String name) {Map CookieMap = readCookieMap (request); if (cookieMap. containsKey (name) {Cookie cookie = (Cookie) cookieMap. get (name); return cookie;} else {return null;}/*** encapsulate the cookie in the Map * @ param request * @ return */public static Map ReadCookieMap (HttpServletRequest request) {Map CookieMap = new HashMap (); 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 ();}}}

 

 

Login write cookie code snippet

 

Principal principal = new Principal (userId, login, userType, pharmacyId, saleManId, ydId, name); // If yes, write the cookie and jump to try {CookieUtils correctly. setPrincipal (response, principal); redirect = StringUtils. isEmpty (request. getParameter (redirect ))? LOGIN_REDIRECT_URL: request. getParameter (redirect); // you need to process the homepage PrintUtils. printToMobile (response, new ResultObject(1, redirect), json); return;} catch (Exception e) {e. printStackTrace ();}

Filter to get user information and put it into 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; // all ignored URLs. private static Set
 
  
MobjIgnoredUrls = new HashSet
  
   
();/*** @ 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);}/*** add Description * @ author ElongDeo June 26, 2015 * @ param filterConfig * @ throws ServletException */@ Overridepublic void init (FilterConfig filterConfig) throws ServletException {notLoginUrl = filterConfig. getInitParameter (notLoginUrl); // wrap the URL string urlText = f to be ignored IlterConfig. getInitParameter (ignoredUrls); if (urlText! = Null) {urlText = urlText. replaceAll (,). replaceAll (,). trim (); String [] urls = urlText. split (,); for (int I = 0; I <urls. length; I ++) {mobjIgnoredUrls. add (urls [I]) ;}}/ ***
   
* Verify the URL to be ignored .*
** @ 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 ;}/ *** add Description * @ author ElongDeo June 26, 2015 */@ Override public void destroy (){}}

Web. xml configuration of the Application Server

 

 

    
 
  
   PrincipalFilter
  
  
   com.xxx.commons.framework.filters.PrincipalFilter
  
  
   
    notLoginUrl
   
   
    /common/logout.htm
   
  
  
   
    ignoredUrls
   
   
    logout.htm
   
  
     
 
  
   PrincipalFilter
  
  
   /*
  
 



 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.