Talking about ServletContext and ServletConfig in Jakarta EE Servlet

ServletContext is an object instantiated by Web Container when we deploy a Jakarta EE web application. It is used to store and retrieve information that we configure for all the Servlets present in the application. And ServletConfig helps us get information defined for a particular Servlet. How is it in detail? In this tutorial, I will discuss with you about ServletContext and ServletConfig in Jakarta EE Servlet.

First, I will create a Jakarta EE Servlet Maven project as an example:

Now, I will create 2 new Servlets:

HelloWorldServlet

and HuongDanJavaServlet:

then declare them in the web.xml file as follows:

The result when running the application, the request to http://localhost:8080/hello is as follows:

And request to http://localhost:8080/huongdanjava as follows:

If you define information for all Servlets in your application using one or more <context-param> tags in the web.xml file as follows:

Then, in both Servlets that I defined above, I can get this configuration information using the ServletContext object, for example as follows:

Or:

The getServletContext() method will return the ServletContext object managed by the Web Container that the application is being deployed to, which is initialized when we deploy the application.

Result:

Or:

And if you define information for a particular Servlet by declaring the <init-param> tag inside the <servlet> tag, this information will not be available to other Servlets of the application and we get these using ServletConfig.

For example, now, I declare the web.xml file as follows:

then with the above code, we will not get context-param information anymore:

And:

You can get the information declared in HelloServlet using ServletConfig as follows:

Result:

Request to http://localhost:8080/huongdanjava, you will see the following result:

There are many other information that you can configure with Jakarta EE Servlet and you can also use ServletContext and ServletConfig to get this information!

Add Comment