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(); MapmodelMap = 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:
List of Request Parameter Names and its Values
modelMap = (Map) request.getAttribute("parameters"); for(String key: modelMap.keySet())< out.print(key); out.print(" : "); out.print(modelMap.get(key)); out.print("
"); > %>
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 query parameters java
Parameters of a resource method may be annotated with parameter-based annotations to extract information from a request. A previous example presented the use of the @PathParam parameter to extract a path parameter from the path component of the request URL that matched the path declared in @Path .
You can extract the following types of parameters for use in your resource class:
Query parameters are extracted from the request URI query parameters and are specified by using the javax.ws.rs.QueryParam annotation in the method parameter arguments. The following example, from the sparklines sample application, demonstrates using @QueryParam to extract query parameters from the Query component of the request URL:
@Path(«smooth») @GET public Response smooth( @DefaultValue(«2») @QueryParam(«step») int step, @DefaultValue(«true») @QueryParam(«min-m») boolean hasMin, @DefaultValue(«true») @QueryParam(«max-m») boolean hasMax, @DefaultValue(«true») @QueryParam(«last-m») boolean hasLast, @DefaultValue(«blue») @QueryParam(«min-color») ColorParam minColor, @DefaultValue(«green») @QueryParam(«max-color») ColorParam maxColor, @DefaultValue(«red») @QueryParam(«last-color») ColorParam lastColor )
If the query parameter step exists in the query component of the request URI, the value of step will be extracted and parsed as a 32-bit signed integer and assigned to the step method parameter. If step does not exist, a default value of 2, as declared in the @DefaultValue annotation, will be assigned to the step method parameter. If the step value cannot be parsed as a 32-bit signed integer, an HTTP 400 (“Client Error”) response is returned.
User-defined Java programming language types may be used as query parameters. The following code example shows the ColorParam class used in the preceding query parameter example:
public class ColorParam extends Color < public ColorParam(String s) < super(getRGB(s)); >private static int getRGB(String s) < if (s.charAt(0) == '#') < try < Color c = Color.decode("0x" + s.substring(1)); return c.getRGB(); >catch (NumberFormatException e) < throw new WebApplicationException(400); >> else < try < Field f = Color.class.getField(s); return ((Color)f.get(null)).getRGB(); >catch (Exception e) < throw new WebApplicationException(400); >> > >
The constructor for ColorParam takes a single String parameter.
Both @QueryParam and @PathParam can be used only on the following Java types:
- All primitive types except char
- All wrapper classes of primitive types except Character
- Any class with a constructor that accepts a single String argument
- Any class with the static method named valueOf(String) that accepts a single String argument
- Any class with a constructor that takes a single String as a parameter
- List , Set , or SortedSet , where T matches the already listed criteria. Sometimes, parameters may contain more than one value for the same name. If this is the case, these types may be used to obtain all values
If @DefaultValue is not used in conjunction with @QueryParam , and the query parameter is not present in the request, the value will be an empty collection for List , Set , or SortedSet ; null for other object types; and the default for primitive types.
URI path parameters are extracted from the request URI, and the parameter names correspond to the URI path template variable names specified in the @Path class-level annotation. URI parameters are specified using the javax.ws.rs.PathParam annotation in the method parameter arguments. The following example shows how to use @Path variables and the @PathParam annotation in a method:
@Path("/") public class MyResourceBean < . @GET public String printUsername(@PathParam("username") String userId) < . >>
In the preceding snippet, the URI path template variable name username is specified as a parameter to the printUsername method. The @PathParam annotation is set to the variable name username. At runtime, before printUsername is called, the value of username is extracted from the URI and cast to a String . The resulting String is then available to the method as the userId variable.
If the URI path template variable cannot be cast to the specified type, the JAX-RS runtime returns an HTTP 400 (“Bad Request”) error to the client. If the @PathParam annotation cannot be cast to the specified type, the JAX-RS runtime returns an HTTP 404 (“Not Found”) error to the client.
The @PathParam parameter and the other parameter-based annotations ( @MatrixParam , @HeaderParam , @CookieParam , and @FormParam ) obey the same rules as @QueryParam .
Cookie parameters, indicated by decorating the parameter with javax.ws.rs.CookieParam , extract information from the cookies declared in cookie-related HTTP headers. Header parameters, indicated by decorating the parameter with javax.ws.rs.HeaderParam , extract information from the HTTP headers. Matrix parameters, indicated by decorating the parameter with javax.ws.rs.MatrixParam , extract information from URL path segments.
Form parameters, indicated by decorating the parameter with javax.ws.rs.FormParam , extract information from a request representation that is of the MIME media type application/x-www-form-urlencoded and conforms to the encoding specified by HTML forms, as described in http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.1. This parameter is very useful for extracting information sent by POST in HTML forms.
The following example extracts the name form parameter from the POST form data:
@POST @Consumes("application/x-www-form-urlencoded") public void post(@FormParam("name") String name) < // Store the message >
To obtain a general map of parameter names and values for query and path parameters, use the following code:
@GET public String get(@Context UriInfo ui) < MultivaluedMapqueryParams = ui.getQueryParameters(); MultivaluedMap pathParams = ui.getPathParameters(); >
The following method extracts header and cookie parameter names and values into a map:
@GET public String get(@Context HttpHeaders hh) < MultivaluedMapheaderParams = ui.getRequestHeaders(); Map pathParams = ui.getCookies(); >
In general, @Context can be used to obtain contextual Java types related to the request or response.
For form parameters, it is possible to do the following:
@POST @Consumes("application/x-www-form-urlencoded") public void post(MultivaluedMap formParams) < // Store the message >
RestTemplate GET Request with Parameters and Headers
In this article, you will learn how to make different HTTP GET requests using the RestTemplate class in a Spring Boot application.
To make a GET HTTP request, you can use either getForObject() or getForEntity() method. Here is an example that uses the getForObject() method to fetch the user information as a JSON string:
// request url String url = "https://jsonplaceholder.typicode.com/posts/1"; // create an instance of RestTemplate RestTemplate restTemplate = new RestTemplate(); // make an HTTP GET request String json = restTemplate.getForObject(url, String.class); // print json System.out.println(json);
To pass query parameters, you can append them directly to the URL or use placeholders. Here is an example of a GET request made with query parameters appended to the URL:
// request url String url = "https://google.com/search?q=java"; // create an instance of RestTemplate RestTemplate restTemplate = new RestTemplate(); // make an HTTP GET request String html = restTemplate.getForObject(url, String.class);
// request url String url = "https://google.com/search?q="; // create an instance of RestTemplate RestTemplate restTemplate = new RestTemplate(); // make an HTTP GET request String html = restTemplate.getForObject(url, String.class, "java");
To add custom request headers to an HTTP GET request, you should use the generic exchange() method provided by the RestTemplate class. The following GET request is made with query parameters and request headers:
// request url String url = "https://jsonplaceholder.typicode.com/posts/"; // create an instance of RestTemplate RestTemplate restTemplate = new RestTemplate(); // create headers HttpHeaders headers = new HttpHeaders(); // set `Content-Type` and `Accept` headers headers.setContentType(MediaType.APPLICATION_JSON); headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); // example of custom header headers.set("X-Request-Source", "Desktop"); // build the request HttpEntity request = new HttpEntity(headers); // make an HTTP GET request with headers ResponseEntityString> response = restTemplate.exchange( url, HttpMethod.GET, request, String.class, 1 ); // check response if (response.getStatusCode() == HttpStatus.OK) System.out.println("Request Successful."); System.out.println(response.getBody()); > else System.out.println("Request Failed"); System.out.println(response.getStatusCode()); >
// request url String url = "https://jsonplaceholder.typicode.com/posts"; // create an instance of RestTemplate RestTemplate restTemplate = new RestTemplate(); // create headers HttpHeaders headers = new HttpHeaders(); // add basic authentication header headers.setBasicAuth("username", "password"); // build the request HttpEntity request = new HttpEntity(headers); // make an HTTP GET request with headers ResponseEntityString> response = restTemplate.exchange( url, HttpMethod.GET, request, String.class ); // check response if (response.getStatusCode() == HttpStatus.OK) System.out.println("Request Successful."); System.out.println(response.getBody()); > else System.out.println("Request Failed"); System.out.println(response.getStatusCode()); >
Using RestTemplate, you can also map the JSON response directly to a Java object. Let us first create a simple model class: Post.java
public class Post implements Serializable private int userId; private int id; private String title; private String body; public Post() > public Post(int userId, int id, String title, String body) this.userId = userId; this.id = id; this.title = title; this.body = body; > // getters and setters, equals(), toString() . (omitted for brevity) >
// request url String url = "https://jsonplaceholder.typicode.com/posts/1"; // create an instance of RestTemplate RestTemplate restTemplate = new RestTemplate(); // create headers HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); // build the request HttpEntity request = new HttpEntity(headers); // make an HTTP GET request with headers ResponseEntityPost> response = restTemplate.exchange( url, HttpMethod.GET, request, Post.class ); // check response if (response.getStatusCode() == HttpStatus.OK) System.out.println("Request Successful."); System.out.println(response.getBody()); > else System.out.println("Request Failed"); System.out.println(response.getStatusCode()); >
Check out the Making HTTP Requests using RestTemplate in Spring Boot guide for more RestTemplate examples. ✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.