How do I read servlet context initialization parameters?

package org.kodejava.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;

import javax.servlet.Servlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(urlPatterns = "/context-init-param")
public class ContextInitParameter extends HttpServlet implements Servlet {

    public ContextInitParameter() {
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html");
        PrintWriter writer = response.getWriter();

        // Get an instance of ServletContext
        ServletContext context = getServletContext();

        // To read context initialization parameter we can call context.getInitParameter() 
        // and pass the name of initialization parameter to be read. If the named
        // parameter does not exist the returned value will be null.
        //
        // In this example we read an initialization parameter called LOG.PATH
        String logPath = context.getInitParameter("LOG.PATH");
        writer.println("Log Path: " + logPath + "<br/>");

        // Reads all the name of servlet's initialization parameters. If the
        // servlet doesn't have any an empty enumeration will be returned.
        Enumeration<String> enumeration = context.getInitParameterNames();
        while (enumeration.hasMoreElements()) {
            String paramName = enumeration.nextElement();
            String paramValue = context.getInitParameter(paramName);

            writer.println("Context Init Param: [" + paramName + " = " + paramValue +
                    "]<br/>");
        }
    }
}

The context initialization parameter (context-param) look something like this in the web.xml file:

<web-app>
    ...
    <context-param>
        <param-name>locale</param-name>
        <param-value>id_ID</param-value>
    </context-param>
    <context-param>
        <param-name>LOG.PATH</param-name>
        <param-value>F:/Logs</param-value>
    </context-param>
    ...
</web-app>

Maven dependencies

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>4.0.1</version>
</dependency>

Maven Central

How do I read an applet parameters?

package org.kodejava.applet;

import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;

public class AppletParameterExample extends Applet {
    private String name = "";

    public void init() {
        // Here we read a parameter named name from the applet tag definition
        // in our html file.
        name = getParameter("name");
    }

    public void paint(Graphics g) {
        g.setColor(Color.BLUE);
        g.drawString("Hello " + name + ", Welcome to the Applet World.", 0, 0);
    }
}

Now we have the applet code ready. To enable the web browser to execute the applet create the following html page.

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Parameterized Applet</title>
</head>
<body>
<applet code="org.kodejava.applet.AppletParameterExample"
        height="150" width="350">
    <param name="name" value="Mr. Bean"/>
</applet>
</body>
</html>

How do I read request parameter from servlet?

When creating an application with Java servlet most of the time we will work with the request and response object. From the request object we can read the parameter submitted by the user’s browser either through an HTTP GET or POST method.

Basically what you need to know is when you try to get the passed parameter from inside the servlet you can call the request.getParameter(paramName) where the paramName is the name of parameter that you want to read from the servlet request object.

In this example I’ll show you how to read the parameter to process user action in a very simple login servlet. In this example we’ll create a login form, a JSP page that accept user input for a username and password.

<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<html lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Login Page</title>
</head>
<body>
<form id="loginForm" action="${pageContext.request.contextPath}/login" method="post">
    <label for="username">Username</label>
    <input id="username" type="text" name="username"/>
    <label for="password">Password</label>
    <input id="password" type="password" name="password"/>
    <input type="submit" value="Login"/>
</form>
</body>
</html>

In this form you’ll have to input box for a username and password. You also have a submit button for executing the login process. Now we have the form, let’s create the login servlet.

package org.kodejava.servlet;

import javax.servlet.Servlet;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(name = "LoginServlet", urlPatterns = "/login")
public class LoginServlet extends HttpServlet implements Servlet {
    protected void doGet(HttpServletRequest request,
                         HttpServletResponse response) throws IOException {
        doLogin(request, response);
    }

    protected void doPost(HttpServletRequest request,
                          HttpServletResponse response) throws IOException {
        doLogin(request, response);
    }

    protected void doLogin(HttpServletRequest request,
                           HttpServletResponse response) throws IOException {
        // Here we read the parameters from servlet request
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        PrintWriter pw = response.getWriter();
        if (username != null && username.equals("administrator")
                && password != null && password.equals("secret")) {
            // authentication accepted!
            pw.println("Success!");
        } else {
            // authentication denied!
            pw.println("Denied!");
        }
        pw.close();
    }
}   

Now you have everything, you can deploy the application on your servlet container, for example Apache Tomcat. Access your login page in the following address:

http://localhost:8080/login.jsp

You can also access the servlet directly from the following url:

http://localhost:8080/login

To pass the username and password information you can append the parameter like:

http://localhost:8080/login?username=administrator&password=secret

This will call the servlet and validate your login information.

Maven dependencies

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>4.0.1</version>
</dependency>

Maven Central

How do I get the command line arguments passed to the program?

When we create a Java application we might want to pass a couple of parameters to our program. To get the parameters passed from the command line we can read it from the main(String[] args) method arguments.

To make a class executable we need to create a main() method with the following signatures:

public static void main(String[] args) {
}

This method takes an array of String as the parameter. This array is the parameters that we pass to the program in the command line.

package org.kodejava.basic;

public class ArgumentParsingExample {
    public static void main(String[] args) {
        for (int i = 0; i < args.length; i++) {
            System.out.println("Argument " + (i + 1) + " = " +
                    args[i]);
        }

        // If you want to check if the number of supplied parameters
        // meet the program requirement you can check the size of 
        // the arguments array.
        if (args.length < 3) {
            System.out.println(
                    "You must call the program as follow:");
            System.out.println(
                    "java org.kodejava.example.basic.ArgumentParsingExample arg1 arg2 arg3");

            // Exit from the program with an error status, for
            // instance we return -1 to indicate that this program 
            // exit abnormally
            System.exit(-1);
        }

        System.out.println("Hello, Welcome!");
    }
}

When we try to run the program without argument we will see the following message:

$ java org.kodejava.basic.ArgumentParsingExample
You must call the program as follow:
java org.kodejava.basic.ArgumentParsingExample arg1 arg2 arg3

And when we pass three arguments we get something like:

$ java org.kodejava.basic.ArgumentParsingExample param1 param2 param3
Argument 1 = param1
Argument 2 = param2
Argument 3 = param3
Hello, Welcome!