Skip to content

Instantly share code, notes, and snippets.

@jpgreenwald
Created July 6, 2013 17:20
Show Gist options
  • Save jpgreenwald/5940573 to your computer and use it in GitHub Desktop.
Save jpgreenwald/5940573 to your computer and use it in GitHub Desktop.
It seems to be impossible to use CDI within a JAX-RS 2.0 ContainerRequestFilter, but it is possible to first use a WebFilter to obtain the service and then pass it along via attributes.
package com.swsandbox.resource;
import com.swsandbox.service.UserService;
import javax.inject.Inject;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;
@WebFilter(urlPatterns = "/*")
public class InjectionServlet implements Filter
{
@Inject
UserService userService;
@Override
public void init(FilterConfig filterConfig) throws ServletException
{
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException
{
request.setAttribute("userService", userService);
chain.doFilter(request, response);
}
@Override
public void destroy()
{
}
}
package com.swsandbox.resource;
import com.swsandbox.service.UserService;
import javax.annotation.Priority;
import javax.ws.rs.Priorities;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.ext.Provider;
import java.io.IOException;
@Priority(Priorities.AUTHENTICATION)
@Provider
public class MyFilter implements ContainerRequestFilter
{
@Override
public void filter(ContainerRequestContext requestContext) throws IOException
{
//Obtain a CDI injected object by name
UserService userService = (UserService) requestContext.getProperty("userService");
}
}
@Alinezhada
Copy link

perfect , well done

@rkoshy
Copy link

rkoshy commented Aug 4, 2020

AWESOME! Thank you -- just what I needed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment