Servlet HTTP Request Parameters Example

In this tutorial we will show you how to handling servlet HTTP request parameters. The HTTP request parameters are sent along with the request. You can send request parameters as part of the URL or as part of the body of an HTTP request.

Project structure

|   +--main
|       +--java
|           +--com
|               +--memorynotfound
|                   |
|       |--resources
|       |--webapp

Maven Dependency


Servlet HTTP Request Parameters

The request.getParameter() is used to get the HTTP request parameters from the request and returns a string. We can also get an array of parameters with request.getParameterValues() which returns an array of strings.

package com.memorynotfound;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;

public class ServletParameterExample extends HttpServlet{

    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // get parameters from request
        String param1 = req.getParameter("param1");
        String param2 = req.getParameter("param2");
        String[] paramArray = req.getParameterValues("paramArray");

        // print the response
        PrintWriter out = resp.getWriter();
        out.write("<h2>Servlet HTTP Request Parameters example</h2>");
        out.write("<p>param1: " + param1 + "</p>");
        out.write("<p>param2: " + param2 + "</p>");
        out.write("<p>paramArray: " + Arrays.toString(paramArray) + "</p>");


Servlet array of parameters

URL: …?paramArray=1&paramArray=2&paramArray=3

String[] paramArray = req.getParameterValues("paramArray");


Parameter page without setting parameters

URL: http://localhost:8080/servlet-parameter/parameters

Servlet HTTP Request Parameters no parameters

Parameter page with parameters

URL: http://localhost:8080/servlet-parameter/parameters?param1=hello&param2=world&paramArray=1&paramArray=2&paramArray=3

Servlet HTTP Request Parameters example



You may also like...