How to read request parameter values ​​in spring using HTTPServletRequest

I want to read requestParams data from url using HttpServletRequest

http://localhost:8080/api/type?name=xyz&age=20 

@RequestParam will not be defined in my controller, it will be just

 @RequestMapping(value = "/**", method = RequestMethod.GET) public ResponseEntity<String> getResponse( final HttpServletRequest request) {} 

I want to read using the request only parameters, not the entire URL.

+4
source share
4 answers

first, why do you define:

 @RequestMapping(value = "/**", method = RequestMethod.GET)` 

?

perhaps you should use:

 @RequestMapping(value = "/api/type", method = RequestMethod.GET) 

and read the parameter:

 request.getParameter("name"); request.getParameter("age"): 
+8
source

xiang is suitable for your exact question: "I want to read only parameters using a query"

But why do you want to make it so difficult. Spring supports you, so you don’t have to process the request object yourself for such general tasks:

I recommend using

 @RequestMapping(value = "/*", method = RequestMethod.GET) public ResponseEntity<String> getResponse( @RequestParam("name") String name @RequestParam("age") int age){ ... } 

instead.

@See Spring Link 15.3.2.4. Linking request parameters to method parameters using @RequestParam

+5
source

you can use

 request.getParameter("parameter name") 
+1
source

Is this what you are looking for?

 public java.lang.String getParameter(java.lang.String name) 

From the API :

getParameter

String getParameter (String name) Returns the value of the request parameter as String or null if the parameter does not exist. Request parameters - additional information sent with the request. For HTTP servlets, parameters are contained in the query string or data forms are submitted. You should use this method only if you are sure that the parameter has only one value. If the parameter can have more than one value, use getParameterValues ​​(java.lang.String).

If you use this method with a multi-valued parameter, the return value is equal to the first value in the array returned by getParameterValues.

If the parameter data was sent to the request body, for example, with an HTTP POST request, then reading the body directly through getInputStream () or getReader () may interfere with the execution of this method.

Parameters: name - a string indicating the name of the parameter Returns: a string representing the only value of the parameter See Also: getParameterValues ​​(java.lang.String)

0
source

Source: https://habr.com/ru/post/1398191/


All Articles