How do I check if parameter is exists in servlet request?

ServletRequest or HttpServletRequest object has a map object that maps parameter name and its value. By accessing this map we can check if a parameter was passed in servlet request. Let’s see the example below.

package org.kodejava.example.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class ParameterCheck extends HttpServlet {
    protected void doGet(HttpServletRequest req, HttpServletResponse res)
            throws ServletException, IOException {

        // Check if username parameter exists
        if (req.getParameterMap().containsKey("username")) {
            String username = req.getParameter("username");
        }

        // Check if password parameter exists
        if (req.getParameterMap().containsKey("password")) {
            String password = req.getParameter("password");
        }
    }
}