Resource Injection in Servlet Filter

You can inject EJB or resources into servlet filters, in the same way as injecting into servlet classes. Things that can be injected include EJB 3 stateless and stateful session beans, EJB 2.1 Home, DataSource, ORB, UserTransaction, javamail session, JMS ConnectionFactory, JMS Queue, JMS Topic, etc. For example,
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import javax.ejb.EJB;
import javax.annotation.Resource;
import javax.sql.DataSource;

public class MyServletFilter implements Filter {
@EJB(beanName="HelloBean")
private HelloRemote helloBean;

@Resource(mappedName="jdbc/__default")
private DataSource ds;

private FilterConfig filterConfig;

public void doFilter(ServletRequest request,
ServletResponse response,
FilterChain chain)
throws IOException, ServletException {
PrintWriter pw = response.getWriter();
helloBean.hello();

try {
chain.doFilter(request, response);
} catch(RuntimeException e) {
throw e;
} catch(Exception e) {
throw new ServletException(e);
}
}
public void destroy() {
}

public void init(FilterConfig filterConfig) {
this.filterConfig = filterConfig;
}
}

Followers

Pageviews Last 7 Days