Endpoint with or without parameter in Java - java

I´m using Spring Boot and I have the endpoint below:
/dashboards/views/{space}/{id}/{filter}
In my context, the filter parameter can exist or can not.
I would like to know if there is some way to represent this context at the endpoint string. I know that in some languages we can do something like this:
/dashboards/views/{space}/{id}/[filter]
Does exist something similar in Java?

Spring #RequestMapping supports array of path Strings. So, it can be achieved like -
#RequestMapping(
path = {
"/dashboards/views/{space}/{id}/{filter}", //with filter
"/dashboards/views/{space}/{id}". //without filter
}
)
Additionally, mark the filter object as #Nullable
#PathVariable #Nullable String filter

Generally, filter data mapped as query parameter rather path variable. You can use an optional query parameter using #RequestParam for this case
#GetMapping("/dashboards/views/")
public String getFoos(#RequestParam(required = false) String filter) {
...
}
And then you can send/skip data
/dashboards/views?filter="data"
/dashboards/views
A good article about #RequestParam here

Related

Get multiple values for same parameter name in request URL - Spring boot

In my spring boot application a request comes from the client with the following URL.localhost:8080/api/invoice?invoiceNo=1234&invoiceDate=050218&invoiceNo=6543&invoiceDate=060218
How can I get the values for the request property invoiceNo and invoiceDate. I know we can always use some delimiter while building the URL and fetch it.
I would like to know if there is any springboot way for achieving this.
Any help is much appreciated.
Now when I try request.getParameter("invoiceNo") I get only the first parameter.
use List
public void invoice(#RequestParam(name="invoiceNo") List<String> invoiceNos, #RequestParam(name="invoiceDate") List<String> invoiceDates) {
In spring you can get query parameters by using the annotation #RequestParam inside controller's endpoint method like this:
#GetMapping("/invoice")
public CustomResponse getInvoiceData(
#RequestParam(value="invoiceNo") List<Long> invoiceNoList,
#RequestParam(value="invoiceDate", required = false) List<Date> invoiceDateList){
...
}
You can see another values that this annotation can get (like required, default, etc..) in the docs
As #maruthi mentioned request.getParameterValues("invoiceNumber") is one way. Another way is to add #RequestParam(value="invoiceNo", required=false) List<String> invoiceNo as the controller method parameter.

How to pass generic List<User> to restful web services

I have the requirement to create the search operation using restful web services, i.e, using #GET. The method signature takes String and List as input argument and returns List.
public Generic List <Employer> getAllEmployer(String employeeName, Generic List <employeeLocation>);
Kindly request if someone could describe on how to implement the same. Should I use query param or path param or form param. I need to return the List of employer in json format.
if the employee locations are just string, pass them as comma seperated values and spring will take care of converting it to list. I would rather suggest just to have it as a pathparam rather than having it as a query param.
This is just my opinion but I think that the "RESTful" way to pass multiple parameters with the same name would be to a MultiValueMap.
Spring and Jersey both have implementations of MultiValueMap however, below is an example of a spring implementation:
#RequestMapping(method = RequestMethod.GET, value = {"/employer/_search"})
public List<Employer> search(#RequestParam MultiValueMap<String,String> params) {
return someService.search(params);
}
They way that you would call this url would then become:
/employer/_search?employeeName=name&location=1&location=2&location=3
Then behind the scenes spring will create the MultiValueMap for you which is a Map<String,List<String>> where any parameters with the same name are put into the same list.

How to get URL Query String values

I'm using Spring Framework and I want to get query string values in Controller
api/asset?param1=value&param2=value
some parameters can be empty like this
api/asset?param1=value&param2
Here is code for controller
#RequestMapping(value = "/api/assets", method = RequestMethod.GET)
public #ResponseBody String getAssetList(
#RequestParam("limit") int limit,
#RequestParam("offset") int offset
) {
}
I got it working when both parameters are given, but I cannot get values when one parameter is empty
Parameters are mandatory by default but you can set them as optional.
Take a look at spring documentation here:
http://docs.spring.io/spring/docs/3.1.x/spring-framework-reference/htmlsingle/spring-framework-reference.html#mvc-ann-requestparam
Parameters using this annotation are required by default, but you can
specify that a parameter is optional by setting #RequestParam's
required attribute to false (e.g., #RequestParam(value="id",
required=false)).

Spring, middle score in request parameter

Is there a way to map a query parameter with a middle score using requests in spring?
I have no problem binding single worded parameters doing this:
Uri example: http://localhost:8080/test/?product=hotels
public class CitiesRequest{
private ProductType product;
public ProductType getProduct() {
return this.product;
}
public void setProduct(String product) {
this.product = product;
}
}
But I'd like to be able to receive parameters like this:
http://localhost:8080/test/?product-type=hotels
As Misha stated it is syntactically incorrect to have a variable name with a hyphen in Java. But Spring is fine with that and allows you to specify a parameter name (in the request) different from the variable name (in java code). For exemple, when using RequestMapping driven controller, one can write :
#RequestMapping("/test")
public ModelAndView getProduct(
#RequestParam("product-type") String productType) {
...
}
That way, getProduct will be called for a url like http://localhost/test?product-type=hotels and the parameter productTypewill receive the value hotels. And all is still purely declarative.
By default, Spring maps the query parameter key to the name of the Java variable. However, it's syntactically incorrect to have a variable name with a hyphen in Java, which explains why you're finding it particularly difficult to get Spring to set the parameter's value for you.
One workaround that might work is to just have a Map<String, String[]> parameter to represent all of the parameters. Then Spring doesn't have to map any query parameters to variable names, so the hyphenated name might end up in that map of all parameters. It may not be as comfortable as pre-split parameter objects, but it might get the hyphenated keys.
Another solution might be to configure the WebDataBinder, which controls how data from HTTP requests are mapped onto your controller's request parameters. But that's a whole can of worms, especially if you're just starting out with Spring. You can read more about it in the documentation under "data binding".

Spring RequestMapping: differentiate PathVariable with different types

Is there a way to tell Spring to map request to different method by the type of path variable, if they are in the same place of the uri?
For example,
#RequestMapping("/path/{foo}")
#RequestMapping("/path/{id}")
if foo is supposed to be string, id is int, is it possible to map correctly instead of looking into the request URI?
According to the spring docs it is possible to use regex for path variables, here's the example from the docs:
#RequestMapping("/spring-web/{symbolicName:[a-z-]+}-{version:\\d\\.\\d\\.\\d}{extension:\\.[a-z]+}")
public void handle(#PathVariable String version, #PathVariable String extension) {
// ...
}
}
(example taken from http://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/mvc.html#mvc-ann-requestmapping-patterns )
Judging from that, it should be possible to write something like this for your situation:
#RequestMapping("/path/{foo:[a-z]+}")
#RequestMapping("/path/{id:[0-9]+}")

Categories