java RestFull在动作线程中获取当前用户

时间:2015-08-21 14:12:46

标签: java rest jpa eclipselink entitylisteners

我需要在一个安静的Web服务中获取JPA 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 个答案:

答案 0 :(得分:0)

这是解决方案:

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);
}

}

2)听取inicialize和清除

    @Provider
    public class RequestContextFilter implements ContainerRequestFilter,ContainerResponseFilter {
        @EJB
        UserCont uCont;

        @Override
        public void filter(ContainerRequestContext requestContext) throws IOException {
                RequestContext.initialize();
                //Here your code for assign data
                //RequestContext.setAttribute("myAtribute", value);
                //In my case
                String tokenAuth = requestContext.getHeaderString("Authorization");
            Long u = null;
            try {
                u = Sessions.get(tokenAuth);
            } catch (Exception e) {
            }
            User user = null;
            if (u != null) {
                user = uCont.find(u);
                RequestContext.setAttribute("user", user);
            }
        }

        @Override
        public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException {
            RequestContext.cleanup();
        }
    }

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());
}

}