Get current logged on user under current process

Source: Internet
Author: User

This is also a tool class

Scenario: For example, we need to use the current login information in the Controller or service or DAO layer. What we have done before is definitely taken out of the session. then where to pass. This is very troublesome. At this time we need to build a tool class. The goal is to get information about the current lander anywhere.

We're going to use an object here . ThreadLocal this class is equivalent to a map, but the key of this class is the current process. So, one such class can only put one object. Here to pay attention.

Why use a class like this? Because of the nature of this class, each process is completely isolated, to avoid high concurrency in the case of some errors (I do not know what error, anyway is to prevent high concurrency, this pit back to fill!!!) todo~~)

1.requestholder.java
 PackageCom.mmall.common;ImportCom.mmall.model.SysUser;Importjavax.servlet.http.HttpServletRequest; Public classRequestholder {Private Static FinalThreadlocal<sysuser> Userholder =NewThreadlocal<sysuser>(); Private Static FinalThreadlocalNewThreadlocal();  Public Static voidAdd (Sysuser sysuser) {userholder.set (sysuser); }     Public Static voidAdd (HttpServletRequest request) {Requestholder.set (request); }     Public StaticSysuser Getcurrentuser () {returnUserholder.get (); }     Public Statichttpservletrequest getcurrentrequest () {returnRequestholder.get (); }     Public Static voidRemove () {userholder.remove ();    Requestholder.remove (); }}
View Code

Note: Here new two such classes, one put the current object, one put the current request, and then customize the Add method, there is a remove method, because after each request, you want to remove the data inside the threadlocal

2. Then write a filter. Intercept all requests. No login directly to return to the login page, login to get the current object from the session, and then add in

Loginfilter.java

 PackageCom.mmall.filter;ImportCom.mmall.common.RequestHolder;ImportCom.mmall.model.SysUser;Importlombok.extern.slf4j.Slf4j;Importjavax.servlet.*;Importjavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse;Importjava.io.IOException;/*** Created by knocking the code out of the Kaka * on 2018/3/28 23:49.*/@Slf4j Public classLoginfilterImplementsFilter {@Override Public voidInit (Filterconfig filterconfig)throwsservletexception {} @Override Public voidDoFilter (ServletRequest servletrequest, Servletresponse servletresponse, Filterchain filterchain)throwsIOException, servletexception {httpservletrequest req=(httpservletrequest) ServletRequest; HttpServletResponse resp=(HttpServletResponse) servletresponse; Sysuser Sysuser= (Sysuser) req.getsession (). getattribute ("user")); if(Sysuser = =NULL) {String path= "/signin.jsp";            Resp.sendredirect (path); return;        } requestholder.add (Sysuser);        Requestholder.add (req);        Filterchain.dofilter (ServletRequest, servletresponse); return; } @Override Public voiddestroy () {}}
View Code

3. Purge the current data for each request end how to know every time the current request is over please read my blog

Httpinterceptor.java
 PackageCom.mmall.common;ImportCom.mmall.util.JsonMapper;Importlombok.extern.slf4j.Slf4j;ImportOrg.springframework.web.servlet.ModelAndView;ImportOrg.springframework.web.servlet.handler.HandlerInterceptorAdapter;Importjavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse;ImportJava.util.Map; @Slf4j Public classHttpinterceptorextendsHandlerinterceptoradapter {Private Static FinalString start_time = "Requeststarttime"; @Override Public BooleanPrehandle (HttpServletRequest request, httpservletresponse response, Object handler)throwsException {String URL=Request.getrequesturi (). toString (); Map Parametermap=Request.getparametermap (); Log.info ("Request start. url:{}, params:{} ", URL, jsonmapper.obj2string (parametermap)); LongStart =System.currenttimemillis ();        Request.setattribute (Start_time, START); return true; } @Override Public voidPosthandle (HttpServletRequest request, httpservletresponse response, Object handler, Modelandview Modelandview)throwsException {String URL=Request.getrequesturi (). toString (); LongStart =(Long) Request.getattribute (start_time); LongEnd =System.currenttimemillis (); Log.info ("Request finished. url:{}, cost:{} ", url, End-start); } @Override Public voidAftercompletion (HttpServletRequest request, httpservletresponse response, Object handler, Exception ex)throwsException {String URL=Request.getrequesturi (). toString (); LongStart =(Long) Request.getattribute (start_time); LongEnd =System.currenttimemillis (); Log.info ("Request completed. url:{}, cost:{} ", url, End-start);    Removethreadlocalinfo (); }     Public voidRemovethreadlocalinfo () {requestholder.remove ();; }}
View Code

4. Configuring filters in Web. xml

<filter>        <filter-name>loginFilter</filter-name>        <filter-class> com.mmall.filter.loginfilter</filter-class></filter><filter-mapping>        < filter-name>loginfilter</filter-name>        <url-pattern>/sys/*</url-pattern>        <url-pattern>/admin/*</url-pattern></filter-mapping>

Get current logged on user under current process

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.