kittu
kittu

Reputation: 7018

use of initialization parameters in java servlet

What is the use of init parameters in servlet? I know that the name itself implies that initializes some thing, but what is my question?

Any other advantages of using init parameters in servlet web.xml?

I tried searching on web but couldn't find the exact usage of it.

Upvotes: 2

Views: 833

Answers (2)

Gren
Gren

Reputation: 1854

The usage is to provide fixed paremeter values for servlets when they are initialized.
web.xml

<servlet>
    <servlet-name>MySMSServlet</servlet-name>
    <description>Send a sms</description>
    <servlet-class>com.x.y.SendSMS</servlet-class>
    <init-param>
        <param-name>cellnumber</param-name>
        <param-value>5555-0000</param-value>
        <description>SMS target</description>
    </init-param>
    <init-param>
        <param-name>text</param-name>
        <param-value>server start</param-value>
        <description>SMS text</description>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

Servlet class

import javax.servlet.http.HttpServlet;

public class SendSMS extends HttpServlet {
    private static final long serialVersionUID = 100L;

    @Override
    public void init() {
        String cellNumber = getServletConfig().getInitParameter("cellnumber");
        String text = getServletConfig().getInitParameter("text");

        new SMSProvider().sendSMS(cellNumber, text);
    }
}

Upvotes: 1

Joop Eggen
Joop Eggen

Reputation: 109613

I had a servlet filter that had to bypass the normal authorisation flow when a special URL parameter was given. Instead of hard-coding that parameter in java, declaring it in web.xml has the advantage of being able to change it from time to time.

In general the same holds for all settings, that are best suited being declarative: timeouts, max accepted image size, buffer size. The "almost eternal" constants.

In one case a servlet could be kept entirely generic, but the key name was business application (=human client) specific:

x.y.general.servlets.MyGenericServlet -> neutral library code
x.y.clients.abc                       -> ABC specific code

web.xml:

<servlet>
    <servlet-name>My Servlet</servlet-name>
    <servlet-class>x.y.general.servlets.MyGenericServlet</servlet-class>
    <init-param> 
        <description>For ABC</description> 
        <param-name>keyName</param-name> 
        <param-value>ABC_ID</param-value> 
    </init-param> 
</servlet>

Upvotes: 2

Related Questions