#RequestParam for unknown key value pair - spring-mvc

I am very new to WebApp in general and Spring MVC in particular. I am writing a small project where I wish to get the key value pair posted by a client. I can do it if I know the value of the key beforehand. The tutorials I've read in parameter processing also assumes that you know the parameter name. But what if I don't know the parameter name.
#Controller
#RequestMapping(value = "/keyvaluepost")
public class ProcessController {
#RequestMapping(method = RequestMethod.POST)
public String doPost(
HttpServletRequest request,
HttpServletResponse response,
#RequestParam("knownKey") String knownKey) {
// process knownKey here
// but what if i do not know the key?
}
Basically, I am looking for something similar to $_POST in php where I can get the key value pair. Any help will be greatly appreciated. Thanks.

Related

Can Spring be directed to take a parameter from either the body or the URL?

An argument to a Spring MVC method can be declared as RequestBody or RequestParam. Is there a way to say, "Take this value from either the body, if provided, or the URL parameter, if not"? That is, give the user flexibility to pass it either way which is convenient for them.
You can make both variables and check them both for null later on in your code
like this :
#RequestMapping(value = GET_SOMETHING, params = {"page"}, method = RequestMethod.GET)
public
#ResponseBody
JSONObject getPromoByBusinessId(
#PathVariable("businessId") String businessId, #RequestParam("page") int page,
#RequestParam("valid") Boolean valid,
#RequestParam("q") String promoName) throws Exception {}
and then use a series if if-else to react to requests.
I wrote it to work with any of the three params be null or empty, react to all different scenarios.
To make them optional, see :
Spring Web MVC: Use same request mapping for request parameter and path variable
HttpServletRequest interface should help solve this problem
#RequestMapping(value="/getInfo",method=RequestMethod.POST)
#ResponseBody
public String getInfo(HttpServletRequest request) {
String name=request.getParameter("name");
return name;
}
Now, based on request data coming from body or parameter the value will be picked up
C:\Users\sushil
λ curl http://localhost:8080/getInfo?name=sushil-testing-parameter
sushil-testing-parameter
C:\Users\sushil
λ curl -d "name=sushil-testing-requestbody" http://localhost:8080/getInfo
sushil-testing-requestbody
C:\Users\sushil
λ

provide query string request mapping variable at class level

I am trying to make spring boot application & swagger. Application is for REST service provide. I have made application running each page.
I have made a simple controller that have RequestMapping("/group/user/contact").
Which is working fine.
I am trying to do something like RequestMapping("/group/{type}/contact") at class level.
So my question is that is it possible ?
If yes then just want some basic guidance. and if no then fine.
My all request working fine. All request came from CORS filter class.
You can do this, the handler method should look something like
#Controller
#RequestMapping("/group/{type}/contact")
public class ClassLevelPathVariableController {
#ResponseBody
#RequestMapping(method = RequestMethod.GET)
public String classLevelMapping(#PathVariable String type) {
return type;
}
}
In this setup a GET request like e.g. /group/test/contact would be handled by the classLevelMapping method and the type variable will be populated with the value "test"

Smart way to add parameters' signature with Square's Retrofit

`I need to contact an API which requires that every request contain the signature of all parameters and url + nonce.
Example:
#GET("/users/{type}")
public void getUsers(
#Path("type") String type,
#Query("sort") boolean sort)
I should add a X-Signature header with contains signature(nonce+"/users/"+type+"sort="+sort).
I thought I could do this with a RequestInterceptor's addHeader(String name, String value) but I can`t as the signature varies for every request.
Is there a smart way to do this with Retrofit or will I just have to manually sign every request?
Am I right in thinking that your signature is generated from [nonce]+[path]+[query params]
You could look at implementing a custom client and passing this into your RestAdapter.Builder().setClient(new CustomClient) method.
Something like CustomClient extends OkClient and then override the execute(Request) method. You will need to create a new Request object and pass that to super.execute(updatedRequest).
#Override
public Response execute(Request request) throws IOException {
List<Header> headers = new ArrayList<>();
// do work here to parse the request.getUrl() and extract path/params and generate the signature
headers.addAll(request.getHeaders());
headers.add(new Header("X-Signature", "signature"));
Request updated = new Request(request.getMethod(), request.getUrl(), headers, request.getBody());
return super.execute(updated);
}
If however there is no consistency to the generation of the signature then you will need to create the signature manually and add a #Header value in your call to your client.

Multiple #RequestBody values in one controller method

I'm receiving error 400 when I send PATCH request to my endpoint that looks like this
#RequestMapping(value = "...",
method = RequestMethod.PATCH,
consumes = "application/json",
produces = "application/json")
#ResponseBody
public User updateUserPartial(#PathVariable("userId") String userId,
#RequestBody Map<String, Object> userMap,
#RequestBody User user,
HttpServletResponse response) {
...
}
so basically both userMap and user should contain same data in different structure.
If I omit one #RequestBody value, this seems to work correctly.
Is it somehow possible to have both #RequestBody values?
You cannot use two #RequestBody as it can bind to a single object only (the body can be consumed only once). As Luke explained the easiest would be to create one object that will capture all the relevent data, and than create the objects you have in the arguments.
On the other hand, if you're insisting on your approach, you can create a custom ArgumentResolver as explained here
I'm pretty sure that won't work. There may be a workaround, but the much easier way would be to introduce a wrapper Object and change your signature.
Here you will find more info about it: Spring MVC controller with multiple #RequestBody

How to pass single parameter to contoller in Spring MVC?

I have some questions from a design point of view in Spring Web MVC.
Is it good practice to use Request Object in controller? If not, then what is alternative way to pass pass one text fields value to controller? Do I need to create one new from bean for this single fields?
It depends of the situation, in a few cases I used the HttpServletRequest; for example for writing a file to the output stream.
If you want to get the Request Parameters you can use the annotation #RequestParam, that it´s more easy to get the parameters from the request.
Depends that you want to handle, for example for a form you can use #ModelAttribute and this attribute can be in a session or in the request.
For example:
#Controller
public class YourController {
#RequestMapping(value = "someUrl", method = RequestMethod.GET)
public String someMethod(#RequestParam("someProperty") String myProperty)
{
// ... do some stuff
}
}
Check the documentation here:
#RequestParam
#ModelAttribute
#PathVariable

Resources