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

Wayan Saryada

Founder at Kode Java Org
I am a programmer, a runner, a recreational diver, currently live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA. You can support my works by donating here. Thank you.

Leave a Reply

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