2

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.

2 Answers 2

2

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>
Sign up to request clarification or add additional context in comments.

Comments

1

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);
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.