How to get user info directly at JPA level in rest api

最后都变了- 提交于 2019-12-13 03:57:17

问题


I am using REST api with JPA, and getting the user information in the header section . For audit purpose need to save the user detail with each request. How to directly get the user info at JPA level (@Prepersist and @PreUpdate hooks) from rest header.

I don't want to pass the details though service layer Is there any generic way to do it ?

Note-I am not using spring.

Thanks in advance.


回答1:


I had the similar problem with spring framework. Following idea may help you.

  1. Create AppContext using ThreadLocal

    public class AppContext {
    
    private static final ThreadLocal<User> currentUser = new ThreadLocal<>();
    
    public static void setCurrentUser(String tenant) {
        currentUser.set(tenant);
    }
    
    public static String getCurrentUser() {
        return currentUser.get();
    }
    
    public static void clear() {
        currentUser.remove();
    }
    

    }

  2. Use filter or similar to get user from http header and set to the AppContext

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
    
         // Your code to extract user info from header
         // Build user object and set to the AppContext
         AppContext.setCurrentUser(user);
    
        //doFilter
        chain.doFilter(httpRequest, response);
    }
    
  3. Use AppContext on the repository. It should available on request scope.

      @PrePersist
      public void onPrePersist() {
        if(AppContext.getCurrentUser() != null){
            this.user = AppContext.getCurrentUser();
         }
    }
    

    }



来源:https://stackoverflow.com/questions/53096385/how-to-get-user-info-directly-at-jpa-level-in-rest-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!