Java : Applying hibernate filters to DAOs

This page last changed on Dec 05, 2008 by Kees de Kooter

Goal

To obtain user information from the http session and use it for building hibernate filters in the DAOs. Now the user object is passed around to all finders for filtering in HQL queries. There must be a more aspect oriented way to achive this.

First piece of the puzzle

Use the ThreadLocal pattern to store a reference to the user. This can be implemented in a servlet filter or for Spring MVC apps in an interceptor.

public class AuthenticationFilter implements Filter {

    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {

        Resource user = (Resource)httpRequest.getSession().getAttribute(SessionVariable.USER);

        // Add user to application wide RequestContext
        RequestContext.setUser(user);

        chain.doFilter(request, response);
    }
}

public class RequestContext {

    private static final ThreadLocal<Resource> currentRequest = new ThreadLocal<Resource>();

    //
    public static Resource getUser() {
        return currentRequest.get();
    }

    public static void setUser(Resource user) {
        currentRequest.set(user);
    }
}

Now the user can be obtained by calling RequestContext.getUser().

Next step: adding filters