servlet

Get/Set init Parameters in Servlet

In this example we are going to see how to get/set init parameters in a Servelt. Using init parameters you can specify several important aspects of your servlets that are going to be handled during requests service.

In short, to get/set init Parameters in Servlet you should:

  • Create public void init() function on your servlet.
  • Call getServletConfig().getInitParameterNames()
  • Use put(initParamName, initParamValue) to put parameters in your init parameter map.
  • In your doGet method use initParamsMap.entrySet().iterator() to get an Iterator an iterate through init parameters.

 
Let’s see the code snippets that follow:

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package com.javacodegeeks.snippets.enterprise;
 
import java.io.IOException;
import java.io.PrintWriter;
 
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
public class GetSetInitParametersInServlet extends HttpServlet {
 
    private static final long serialVersionUID = -2128122335811219481L;
 
    private String paramName;
    private String paramValue;
 
    public void init() throws ServletException {
        paramName = "myparam";
        paramValue = getServletConfig().getInitParameter(paramName);
    }
 
    public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException {
 
        PrintWriter out = res.getWriter();
        res.setContentType("text/plain");
 
        out.write(paramName);
        out.write(" = ");
        out.write(paramValue);
 
        out.close();
    }
 
}

web.xml

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<?xml version="1.0" encoding="UTF-8"?>
 
  version="2.5">
 
    <display-name>JCG Snippets Web Project</display-name>
 
    <servlet>
        <servlet-name>JCG Snippets Application</servlet-name>
        <servlet-class>com.javacodegeeks.snippets.enterprise.GetSetInitParametersInServlet</servlet-class>
        <init-param>
            <param-name>myparam</param-name>
            <param-value>myvalue</param-value>
        </init-param>
    </servlet>
 
    <servlet-mapping>
        <servlet-name>JCG Snippets Application</servlet-name>
        <url-pattern>/jcgservlet</url-pattern>
    </servlet-mapping>
 
</web-app>

URL:

http://myhost:8080/jcgsnippets/jcgservlet

Output:

myparam = myvalue

This was an example on how to get/set init Parameters in Servlet.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button