如何在Rest API中直接在JPA级别获取用户信息 [英] How to get user info directly at JPA level in rest api
问题描述
我将REST api与JPA一起使用,并在标头部分获取用户信息. 出于审计目的,需要在每个请求中保存用户详细信息. 如何从其余标头直接获取JPA级别的用户信息(@Prepersist和@PreUpdate挂钩).
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 ?
注意-我没有用弹簧.
谢谢.
推荐答案
spring框架也有类似的问题.遵循以下想法可能会对您有所帮助.
I had the similar problem with spring framework. Following idea may help you.
-
使用ThreadLocal创建AppContext
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();
}
}
使用过滤器或类似工具从http标头中获取用户并设置为AppContext
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);
}
在存储库上使用AppContext.它应该在请求范围内可用.
Use AppContext on the repository. It should available on request scope.
@PrePersist
public void onPrePersist() {
if(AppContext.getCurrentUser() != null){
this.user = AppContext.getCurrentUser();
}
}
}
这篇关于如何在Rest API中直接在JPA级别获取用户信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!