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:

<context-param>

  <param-name>upload.path</param-name>

  <param-value>/home/jboss/data</param-value>

</context-param>

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

@ApplicationScoped

public class Utils {

	@Inject

	private ServletContext context;

}

Then you can read your context params easily as follows:

context.getInitParameter("upload.path");

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

@Inject

private HttpServletRequest httpRequest;
Found the article helpful? if so please follow us on Socials