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
+--src
| +--main
| +--java
| +--com
| +--memorynotfound
| |--ServletParameterExample.java
| |--resources
| |--webapp
pom.xml
Maven Dependency
<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
</dependencies>
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.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
@WebServlet("/parameters")
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
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
out.write("<html><body>");
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¶mArray=2¶mArray=3
String[] paramArray = req.getParameterValues("paramArray");
Demo
Parameter page without setting parameters
URL: http://localhost:8080/servlet-parameter/parameters
Parameter page with parameters
URL: http://localhost:8080/servlet-parameter/parameters?param1=hello¶m2=world¶mArray=1¶mArray=2¶mArray=3