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;

Recommended Articles

Maximize Your CDI Applications with Jakarta EE 11 and beans.xml

Enhance your CDI applications using Jakarta EE 11's beans.xml for improved compatibility and functionality. #CDI #JakartaEE11 #WildFly #Java #Middleware #CloudNative

Using CDI Beans in JBoss - WildFly Modules | Enterprise Java Tutorials

Learn how to use CDI beans and AS resources in JBoss WildFly modules, deploying a demo bean with @ApplicationScoped and javax.annotation.Resource.

Enhance Your Enterprise Java Applications with Contexts and Dependency Injection (CDI) - JSR 299

JSR 299 CDI simplifies Java EE development, bridging the gap between enterprise and web tiers. Learn how to leverage CDI for transactional support in your applications.

Upgrading Java EE 6 to CDI: A Step-by-Step Guide with Eclipse and Maven

Learn how to migrate your Java EE 6 EJB-based application to a CDI-based application using Eclipse and the Maven plugin. Get started with this comprehensive tutorial.