How to get URL Query String values - java

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)).

Related

Endpoint with or without parameter in 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

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.

Regarding REST Path Conflict

I am creating two methods(GET) in a REST service in which the URL is for the first method is of the form
/a/b/{parameter}?start=1 &
end=100 & name="some value"
and for the second method it is
/a/b/{parameter}
When i run the code it gives a conflict.
Can anyone please suggest me how these can be configured for the methods and also to make the query paramters OPTIONAL?
Thanks
This should work fine:
#GET
#Path("/a/b/{parameter}")
public Response get(#PathParam("parameter") String parameter, #QueryParam("start") Integer start, #QueryParam("end") Integer end, #QueryParam("name") String name) {
// switch here according to the values received. All are optional and non-sent are nulls here
}
If in the future you will have default values you can add them inline like this (for the name query param for example):
#DefaultValue("some-name") #QueryParam("name") String name

How to deal with the url with value like root=, the parameter with key and without value?

I have the problem just like the title. I know there is a #RequesetParam in spring mvc, it has a parameter required=false. But it failed when try to use it.
Actually I found the #RequestParam is useless. According to my trying, It always be O.K. using #RequestParam(value="root", required=true) where the URL is with/without value=some value except blank.
So, I don't know what totally the required=true is. Then, whichever the required=false or required=trueis, it throws exception with URL parameter like ...&root=.
And my HandlerMapping & AdapterMapping are RequestMappingHandlerMapping and RequestMappingHandlerAdapter
the version of spring mvc is 3.2.4
Please tell me what's going on with the spring mvc?
Thanks advance:)
According to the documentation:
public abstract boolean required
Whether the parameter is required. Default is true, leading to an
exception thrown in case of the parameter missing in the request.
Switch this to false if you prefer a null in case of the parameter
missing.
Alternatively, provide a defaultValue, which implicitly sets this flag
to false.
so if the parameter is missing inside a request, you can decide whether an exception should have been thrown or not !
according to your question you are amazed why no exception does throw, It's because these two URL have different meaning :
http://my-domain.ir:8080/your-project-name/main.html?p=something&root=
http://my-domain.ir:8080/your-project-name/main.html?p=something
in the first case the value root exist but It doesn't have any value But in the second case it is missing, Your case meet the first condition and this is because no exception does throw .
//if you use the code below, in your case the root will get no value exactly like you define String root =""
#RequestParam("root") String root
I suggest you always use #ModelAttribute in spring and validate/not validate your Bean class variables as you wish with JSR303 standard and receive your Parameter value using the GETTER/SETTER methods of that bean class.
You should use placeholder to get value in URL and use #PathVariable to get the values from url,
for example:
#RequestMapping(value="/customer/{customerId}/show", method = RequestMethod.GET)
public ModelAndView showCustomerById(
#PathVariable("customerId") int customerId) {
...
}
and the requested url will look like:
http://localhost:8080/HelloWorld/customer/1234/show
and if you want to pass parameter with above then, do like:
#RequestMapping(value="/customer/{customerId}/show", method = RequestMethod.GET)
public ModelAndView showCustomerByIdAndName(
#PathVariable("customerId") int customerId,
#RequestParam(value = "name", required = false) String name){
...
}
and the requested url will look like now:
http://localhost:8080/HelloWorld/customer/1234/show?name=myName
Note: the default value of required field is true, and if the parameter is not found then exception will raise.

In SpringMVC, is there anyway to select a controller method using a form element value?

In Spring MVC, is there anyway to select a controller method using a form element value? For example, let's say we have two buttons both with name "action" in a form. Is there anyway to execute different controller methods based on the button which was clicked by the user without using any javascript?
Yes, using #RequestMapping(params="..."). See docs.
You can narrow path mappings through parameter conditions: a sequence of "myParam=myValue" style expressions, with a request only mapped if each such parameter is found to have the given value. For example:
#Controller
#RequestMapping("/owners/{ownerId}")
public class RelativePathUriTemplateController {
#RequestMapping(value = "/pets/{petId}", params="myParam=myValue")
public void findPet(#PathVariable String ownerId, #PathVariable String petId, Model model {
// implementation omitted
}
}

Categories