How do I get parameter names from servlet request?

This example show you how to obtain parameter name from servlet request. By calling request.getParameterNames() you will get an Enumeration object by iterating this object you can get the parameter names.

package org.kodejava.servlet;

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.Enumeration;

@WebServlet(name = "ParameterName", urlPatterns = "/parameter-names")
public class ParameterName extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        PrintWriter pw = response.getWriter();

        // Let's obtains parameters name here!
        Enumeration<String> enumeration = request.getParameterNames();
        while (enumeration.hasMoreElements()) {
            String parameterName = enumeration.nextElement();
            pw.println("Parameter = " + parameterName);
        }
        pw.close();
    }
}

When you call the servlet and pass some parameters you get the parameter name echoed on the web browser.

http://localhost:8080/parameter-names?txid=001&item=10&price=1000

Parameter = txid
Parameter = item
Parameter = price

Maven dependencies

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>4.0.1</version>
</dependency>

Maven Central

Wayan

Leave a Reply

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