How to create Object in the class implementing Han

2019-08-22 18:05发布

I am having situation like: in the preHandle() method of the class implementing HandlerInterceptor, i am having sessionId getting in the incoming HttpServletRequest object request. now using this session id i am fetching userInfo from the DB. the same info i have to use somewhere else like service layer to process the request.

It would be very helpful if anyone of you help me out to achieve it. Thanks in advance.

1条回答
老娘就宠你
2楼-- · 2019-08-22 18:37

You can use a ThreadLocal to store a reference to a user that will only be accessible to the current thread of execution.

https://docs.oracle.com/javase/7/docs/api/java/lang/ThreadLocal.html

You can wrap this in a context class so that in your service you can access the current user via the static call: User user = UserContextUtils.getUser();

UserContextUtils:

public class UserContextUtils {

    private static final ThreadLocal<User> CONTEXT = new ThreadLocal<>();

    public static void setUser(User user) {
        CONTEXT.set(user);
    }

    public static User getUser() {
        return CONTEXT.get();
    }

    public static void clear() {
        CONTEXT.remove();
    }
}

The Interceptor:

public class MyHandlerInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, 
              HttpServletResponse response, Object handler)
            throws Exception {

        User user = null;// get user from the database.
        UserContextUtils.setUser(user);

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, 
             HttpServletResponse response, Object handler,
            Exception ex) {

        // as some web servers re-use threads, you must ensure that the 
        // context is cleared on completion either here or elsewhere.

        UserContextUtils.clear();
    }

    @Override
    public void postHandle(HttpServletRequest request, 
             HttpServletResponse response, Object handler,
            ModelAndView modelAndView) throws Exception {

    }
}
查看更多
登录 后发表回答