• Get all Request Parameters in Java

    In this tutorial, we’ll show you how to get all request parameters in java. Ideally, the server should know the parameter names that was sent by the client browser. I have created a simple Spring Controller that gets a request from the client and redirect the user to another page that displays all his request parameters and its values.

    Create A Servlet Controller

    In our Controller, we take a parameter HttpServletRequest which contains the client request including its parameters.

    @Controller
    @RequestMapping("/sample")
    public class SampleController {
    
    @RequestMapping(value = "/get", method= RequestMethod.GET)
    public ModelAndView getParameters(HttpServletRequest request){
        Enumeration enumeration = request.getParameterNames();
        Map<String, Object> modelMap = new HashMap<>();
        while(enumeration.hasMoreElements()){
            String parameterName = enumeration.nextElement();
            modelMap.put(parameterName, request.getParameter(parameterName));
        }
        ModelAndView modelAndView = new ModelAndView("sample");
        modelAndView.addObject("parameters", modelMap);
        return modelAndView;
    }
    }

    To get all request parameters in java, we get all the request parameter names and store it in an Enumeration object. Our Enumeration object now contains all the parameter names of the request. We then iterate the enumeration and get the value of the request given the parameter name.

    We store the the name and its value in a Map and add it to a ModelAndView and redirect to sample.jsp. Below is the sample.jsp file:

    <%@ page import="java.util.Map" %>
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
        <title>Display All Request Parameters</title>
    </head>
    <body>
    <h4>List of Request Parameter Names and its Values</h4>
        <%
            Map<String, Object> modelMap = (Map<String, Object>) request.getAttribute("parameters");
            for(String key: modelMap.keySet()){
                out.print(key);
                out.print(" : ");
                out.print(modelMap.get(key));
                out.print("<br />");
            }
        %>
    </body>
    </html>

    Testing our WebApp

    To test it, we type the url in the browser:

    http://localhost:8080/sample/get?name=javapointers&language=java&version=8

    When we hit Enter, the resulting page is below:

    get-all-request-parameters

    Related Post