java RestFull获取当前用户操作线程
我需要在一个restful Web服务中获取JPAjava RestFull获取当前用户操作线程,java,rest,jpa,eclipselink,entitylisteners,Java,Rest,Jpa,Eclipselink,Entitylisteners,我需要在一个restful Web服务中获取JPAEntityListener中的当前用户。这是我的代码: 服务网站: @POST @Produces({"application/json"}) @Consumes({"application/json"}) public Response create(@HeaderParam("Authorization") String tokenAuth, AreaTran areaT) { Response res; U
EntityListener
中的当前用户。这是我的代码:
服务网站:
@POST
@Produces({"application/json"})
@Consumes({"application/json"})
public Response create(@HeaderParam("Authorization") String tokenAuth,
AreaTran areaT) {
Response res;
User user = null;
try {
user = testUser(tokenAuth);
Area area = areaCont.create(user, areaT);
res = AppConf.genOk("Area " + area.getNombre() + " creada correctamente");
} catch (Exception e) {
res = le.gen(e, user);
}
return res;
}
在这里,我得到记录的用户user=testUser(tokenAuth)代码>
我的问题是:
public class AuditEntityListener {
@PrePersist
public void prePersist(AuditableEntity e) {
e.setCreatedDate(new Date());
//how get the current user for this transaction HERE!!!!!
}
@PreUpdate
public void preUpdate(AuditableEntity e) {
e.setLastModifiedDate(new Date());
}
}
有没有办法获得请求流的用户?这是解决方案:
1) 在这个类中存储当前事务的数据
public class RequestContext {
private static ThreadLocal<Map<Object, Object>> attributes = new ThreadLocal<>();
public static void initialize() {
attributes.set(new HashMap());
}
public static void cleanup() {
attributes.set(null);
}
public static <T> T getAttribute(Object key) {
return (T) attributes.get().get(key);
}
public static void setAttribute(Object key, Object value) {
attributes.get().put(key, value);
}
3) 在任何地方都可以使用它
public class AuditEntityListener {
@PrePersist
public void prePersist(AuditableEntity e) {
e.setCreatedDate(new Date());
//In my case
e.setCreatedBy((User) RequestContext.getAttribute("user"));
}
@PreUpdate
public void preUpdate(AuditableEntity e) {
e.setLastModifiedDate(new Date());
}
}
public class AuditEntityListener {
@PrePersist
public void prePersist(AuditableEntity e) {
e.setCreatedDate(new Date());
//In my case
e.setCreatedBy((User) RequestContext.getAttribute("user"));
}
@PreUpdate
public void preUpdate(AuditableEntity e) {
e.setLastModifiedDate(new Date());
}