SpringMVC RequestMapping for GET url parameters - java

How to make the RequestMapping to handle GET parameters in the url? For example i have this url
localhost:8080/MyApplication/spm/gcNkyLXkwv
how to get the spm value from the above url

This can be done using PathVariable. I will just give example how it can be done. You can incorporate in your example
Suppose you want to write a url to fetch some order, you can say
www.mydomain.com/order/123
where 123 is orderId.
So now the url you will use in spring mvc controller would look like
/order/{orderId}
Now order id can be declared a path variable
#RequestMapping(value = " /order/{orderId}", method=RequestMethod.GET)
public String getOrder(#PathVariable String orderId){
//fetch order
}
if you use url www.mydomain.com/order/123, then orderId variable will be populated by value 123 by spring
Also note that PathVariable differ from requestParam as pathVariable are part of URL. The same url using request param would look like www.mydomain.com/order?orderId=123

Related

GetMapping with JSON array parameter

I am using a FeignClient and a GetMapping to interact with an external system.
My GetMapping is defined as:
#GetMapping(value = "/path/to/endpoint?fields=[\"nm\",\"label\"]")
public String hitEndpoint() {}
Debug shows that the endpoint is being called with:
https://url/path/to/endpoint?fields=[%22nm%22&fields=%22label%22]
Which is failing because the endpoint expects valid json for the fields parameter:
https://url/path/to/endpoint?fields=[%22nm%22,%22label%22]
How do I convince GetMapping to make the request correctly?
Thanks for any help.
Although I think its better to pass JSON as body of a POST method to your controller. But if you insist on doing this I can propose to you 2 solutions:
First Solution
Encode your JSON array into Percent-encoding so you can send it via URL.
For example, your array will be like this:
["nm","label"] -> %5B%22nm%22%2C%22label%22%5D
I used this online tool to encode it.
Second Solution
Encode your array into Base64 and GET it via URL to your controller.
Decode the given Base64 string in the controller and parse it as a JSON array.
There is no need to define your Array parameter in the URL, using spring you can define your API as below and with the power of #RequestParam annotation you can define that you expect to receive an array as a parameter in the URL
#RequestMapping(value = "/path-to-endpoint", method = RequestMethod.GET)
public ResponseEntity<YourResponseDTO> yourMethodName(
#RequestParam("ids") List<Long> arrayParam) {
// Return successful response
return new ResponseEntity<>(service.yourServiceMethod(requestDTO), HttpStatus.OK);
}
Then you can call your GET endpoint using below URL:
/path-to-endpoint?ids=1,2,3,4

Spring MVC Binding Request parameters to POJO fields

I want a controller with the following mapping (incomplete):
#GetMapping(/searchitems)
public #ResponseBody Page<Item> get(Item probe)
From the Item probe parameter I want to query by example in a repository of items and return the result.
Question:
How can I complete the mapping above for a search URL? As search URL I was thinking something like /searchitems?itemAttributeA=foo&itemAttributeB=bar&...itemAttributeZ=xyz. How can I tell spring to inject the passed request parameters into the Item probe fields with the same names?
Adding #ModelAttribute should bind the individual request parameters into your Item POJO.
public #ResponseBody Page<Item> get(#ModelAttribute Item probe)
You can create a POJO and pass as a parameter in the controller class. Pojo should have the fields which you want to read and set. Spring will read and map those attributes in the Pojo which you will define as the request.
#GetMapping(/searchitems)
public ResponseEntity<List<Items>> searchItems(ItemRequest itemRequest) {
}
Only thing needs to be taken care is to check for binding result. If there are errors, we need to stop the request and handle or throw.
For e.g. All of the below attributes in the URL will be set in the Pojo.
https://domain/search-items?pageNumber=1&sortOrder=ascending&itemName=test&itemType=apparel&sortField=itemId&pageSize=5
You can use #RequestParam for this.
public #ResponseBody Page<Item> get(#RequestParam("itemAttributeA") String itemAttributeA ,
#RequestParam("itemAttributeB") String itemAttributeB,...)

Spring MVC and #RequestParam with x-www-form-urlencoded

I'm trying to build an API that takes a POST with one parameter in the body that should be x-www-form-urlencoded. I've currently mapped it as:
#RequestMapping(method = POST, consumes = APPLICATION_FORM_URLENCODED_VALUE, produces = APPLICATION_JSON_VALUE)
public ResponseEntity<LinkEntity> createShortLink(#RequestBody String url) {
LinkEntity savedLink = linkService.create(url);
}
When I do a POST with Postman (REST Chrome extension) with one form parameter url=http://www.drissamri.be it comes into this method as url=http%3A%2F%2Fwww.drissamri.be as expected.
When I try to change the #Requestbody into #RequestParam(value = "url") I still get the URL with the url= prefix (as expected) but it is not urlencoded anymore. Why doesn't the encoding take place any more? Is this a bug or is there another way to take in the parameter as urlencoded value
As correctly mentioned by Pavel Horal the parameter is retrieved by ServletRequest#getParameter and is already decoded. If you need to access the origin parameter you can access the parameter by other means.
One way would be to inject a HttpServletRequest and use HttpServletRequest#getQueryString() which does not decode the values.

Spring MVC - what is url path info?

I would like to know what is a url path info?
For example in
http://myserver:8080/servletname/handlermethod
Is it the whole path including server name:
http://myserver:8080/servletname/handlermethod
or is it just
/servletname/handlermethod
getPathInfo() according to the doc:
Returns any extra path information associated with the URL the client
sent when it made this request. The extra path information follows the
servlet path but precedes the query string and will start with a "/"
character.
so in your example it will return /handlermethod
If you want to have /servletname/handlermethod you should use getRequestURI().
getRequestURL() will return the full URL made by the client (except string parameters).
The path info in Spring MVC may imply for the info sent via a URL. In a Spring MVC Controller you can easily set a request mapping which include a variable value place holder which is bound to an argument with #PathVariable annotation in the method signature - related to the request mapping. For eaxmple:
#RequestMapping(value = "/user/{userId}")
public ModelAndView getUserByPathVariable(#PathVariable Long userId, HttpServletRequest request, HttpServletResponse response) {
System.out.println("Got request param: " + userId);
You take a look here for a more detailed example: Spring MVC Controller Example

Handling special characters in post parameters for Spring-mvc

I have an application using spring-mvc 3.0.
The controllers are configured like this:
#RequestMapping(value = "/update", method = RequestMethod.POST)
public ModelAndView updateValues(
#RequestParam("einvoiceId") String id){
...}
When posting an id that contains special characters (in this case pipe |), url-encoded with UTF-8 (id=000025D26A01%7C2014174) the string id will contain %7C. I was expecting spring-mvc to url decode the parameter. I am aware that I can solve this by using
java.net.URLDecoder.decode()
but since I have a large number of controllers, I would like this to be done automatically by the framework.
I have configured the Tomcat connector with URIEncoding="UTF-8" and configured a CharacterEncodingFilter, but as I understand it this will only affect GET requests.
Any ideas on how I can make spring-mvc url decode my post parameters?
http://wiki.apache.org/tomcat/FAQ/CharacterEncoding#Q3
This page says CharacterEncodingFilter can change POST parameters
I believe you encounter the same issue as I did.
Try using #PathVariable instead #RequestParam.
#PathVariable is to obtain some placeholder from the uri (Spring call it an URI Template) — see Spring Reference Chapter 16.3.2.2 URI Template Patterns
If you do, you have to change your url and don't provide parameter 'id'.
Just "/update/000025D26A01%7C2014174".
More information can be found where I found the solution for my problem #RequestParam vs #PathVariable

Categories