从REST / EJB服务记录用户信息和更新操作

我需要从其余资源中记录所有更新操作,并将其存储到数据库日志表中。

想法是存储信息,例如:

  • 登录用户
  • 有关更新/保存的实体的操作说明
  • 更新的字段和参考键

我的应用程序与Java EE8兼容,它使用REST / EJB和CDI。

起初,我想到了在EJB端处理所有这些问题,但是公开的服务不需要在方法签名上已使用户登录,因此添加它会产生强制。.

是否有任何发送用户信息的方法,通常可以通过webrequest(我们使用会话令牌模型身份验证)检索并通过EJB注入?

ancen1978 回答:从REST / EJB服务记录用户信息和更新操作

如果正确设置了会话管理,则可以通过以下方式注入会话上下文:

@Resource
SessionContext sessionContext;

然后:

sessionContext.getCallerPrincipal().getName()

是您的登录用户。

,

如前所述,SessionContext.getCallerPrincipal()。getName()不起作用,因为身份验证机制不提供它。

经过一番尝试,我发现了这一点

在EJB方面

@RequestScoped
public class UserInfo {

    private String userId;

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        if (this.userId != null) throw new UncheckedException("cannot infer userid twice");
        this.userId = userId;
    }
}

在REST方面

@Inject
UserInfo userInfo;

void userAuthenticated(...) {

    String userId = ... // get userid from access token through **WebRequest** object

    userInfo.setUserId(userId);

}

旁注

老实说,我宁愿在 UserInfo 构造函数上注入 userid ,但由于 WebRequest 对象不属于EJB,所以我不允许这样做上下文

替代方式

使用响应过滤器将所有日志记录过程移至REST端。

示例代码:

@Provider
public class LoggingFilter implements ContainerResponseFilter {


    @Context
    HttpServletRequest webRequest;

    @Context
    ResourceInfo resinfo;

    @Inject
    LoggingService loggingService;


    @Override
    public void filter(ContainerRequestContext containerRequestContext,ContainerResponseContext containerResponseContext) {

        final Method resourceMethod = resinfo.getResourceMethod();

        if (resourceMethod.isAnnotationPresent(Loggable.class) && containerResponseContext.getStatusInfo().getFamily() == Response.Status.Family.SUCCESSFUL) {

            // get all method's info and log to database ...

        }
    }
本文链接:https://www.f2er.com/3110805.html

大家都在问