java examples
Home Java Examples Resources Java Interview Questions
Brainpower SEO

How to check if parameter is exists in servlet request?

ServletRequest 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 com.javacoderanch.example.servlet;

import java.io.IOException;

import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ParameterCheck extends HttpServlet implements Servlet {
	private static final String EMPTY = "";
	
	public ParameterCheck() {
		super();
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		
		String username = EMPTY;
		String password = EMPTY;
		
		//
		// Check if username parameter exists
		//
		if (request.getParameterMap().containsKey("username")) {
			username = request.getParameter("username");
		}
		
		//
		// Check if password parameter exists
		//
		if (request.getParameterMap().containsKey("password")) {
			password = request.getParameter("password");
		}
	}

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