The Envers documentation has an answer for this if you use Seam.
public class ExampleListener implements RevisionListener {
public void newRevision(Object revisionEntity) {
ExampleRevEntity exampleRevEntity = (ExampleRevEntity) revisionEntity;
Identity identity = (Identity) Component.getInstance("org.jboss.seam.security.identity");
exampleRevEntity.setUsername(identity.getUsername());
}
}
So, I suppose your question would be how to retrieve the currently logged in user at that point if you don't use Seam? I'm sure there are several ways to do it, we do it like this.
- Write a ServletFilter
- In the filter get the principal from the session (or the security context if you use a security framework like Spring Security)
- Store it in the log4j MDC
Code example from filter
protected void beforeRequest(final HttpServletRequest request, final String message) {
final Principal principal = request.getUserPrincipal();
final String username = principal != null ? principal.getName() : null;
if (username != null) {
MDC.put(USER, username);
}
}
protected void afterRequest(final HttpServletRequest request, final String message) {
MDC.remove(USER);
}
Later you can get the user from anywhere in your code because the MDC has a static get(String)
method.