Init parameters in servlets

The following two tabs change content below.
Prasad Kharkar is a java enthusiast and always keen to explore and learn java technologies. He is SCJP,OCPWCD, OCEJPAD and aspires to be java architect.

Latest posts by Prasad Kharkar (see all)

Hello, In this article we are going to learn about init parameters in servlets and how to use them in java web applications.

What is the need?

Sometimes we may have a requirement that a value keeps changing time to time and so we do not want to hard code it into a servlet. If it is done, we will have to change the value and again recompile the servlet.

How can it be achieved?

Servlet specification provides a way to provide init parameters to the servlet when it is initialized. i.e. its  init()  method completes. These init parameters are available in the servlet. Parameters can be accessed using public String getInitParameter(String name)  method.

Step 1: Create a dynamic web project.

Create a new dynamic web project.

Step 2: Create Servlet and configure in web.xml

We will create a new Servlet called AdminServlet which will use the parameter admin.

This is configured in  web.xml

Notice the configuration

This specifies initialization parameters specifically for Admin Servlet because they are contained in servlet tag in web.xml . These are ServletConfig parameters and available only for specific servlet.

Now we want some parameters to be available for whole web application and not only for a specific servlet, to fulfill this, need to specify context init parameters. We can configure them directly under  <web-app>  tag in web.xml  as follows.

 Step 3: Run the application.

Deploy your application under tomcat server and start it. Hit the url

You will see the values of both servlet config init parameters and context init parameters printed on the page.





Share Button

2 comments for “Init parameters in servlets

  1. michael stern
    December 6, 2017 at 6:18 am

    How do you create a servlet that print 10 random numbers to advice a participant to join in a lottery game?

    • December 19, 2017 at 9:37 am

      could you please post the problem you are facing in your code?

Leave a Reply

Your email address will not be published. Required fields are marked *