Accessing ServletContext and ServletRequest in CDI Beans

Today I've found one interesting question on StackOverFlow of one user asking to read the web.xml context params from a CDI Bean. Luckily it's not complicated at all to accomplish this task.

In order to be able to read the web.xml context-params from a CDI Bean all you need to do is injecting the ServletContext into your CDI Bean. This is our starting point:





The Servlet Context can be injected safetly into any CDI bean as follows:


public class Utils {


	private ServletContext context;


Then you can read your context params easily as follows:


Much the same way you can inject the HTTPServletRequest and extract the request's parameters or access the HTTPSession:


private HttpServletRequest httpRequest;

Follow us on Twitter