how to get both value #RequestBody and #RequestParam together - spring

how to get both values #RequestBody and #RequestParam together??
below the code:
#RequestMapping(value = "/sign-up", method = RequestMethod.POST)
public ResponseEntity<?> addUser(#RequestBody User user,#RequestParam("location") String location,#RequestParam("deviceid") String deviceid) {
System.out.println(location);
System.out.println(deviceid);
it is possible?
for #RequestParam Content-Type application/x-www-form-urlencoded
and for #RequestBody Content-type application/json
i want both value location and deviceid if there is any other way?

#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
#RequestParam is to obtain an parameter — see Spring Reference Chapter 16.3.3.3 Binding request parameters to method parameters with #RequestParam
If URL http://localhost:8080/MyApp/user/1234/invoices?date=12-05-2013 gets the invoices for user 1234 on December 5th, 2013, the controller method would look like:
#RequestMapping(value="/user/{userId}/invoices", method = RequestMethod.GET)
public List<Invoice> listUsersInvoices(
#PathVariable("userId") int user,
#RequestParam(value = "date", required = false) Date dateOrNull) {
...
}
Also, request parameters can be optional, but path variables cannot--if they were, it would change the URL path hierarchy and introduce request mapping conflicts. For example, would /user/invoices provide the invoices for user null or details about a user with ID "invoices"

Related

Issue with Spring Rest #RequestMapping when negating params

I have two spring controller methods :
#RequestMapping(value="/requestotp",method = RequestMethod.POST,params = "!applicationId") //new customer
public OTPResponseDTO requestOTP( #RequestBody CustomerDTO customerDTO){
return customerService.requestOTP(customerDTO);
}
#RequestMapping(value="/requestotp",method = RequestMethod.POST,params = {"idNumber","applicationId"}) //existing customer
public String requestOTP( #RequestParam(value="idNumber") String idNumber , #RequestParam(value="applicationId") String applicationId) {
return customerService.requestOTP(idNumber, applicationId);
}
using "!applicationId" , I am expecting that when I call the url with applicationId parameter there that the second method will be called , but actually when I pass a request like this :
{"idNumber":"345","applicationId":"64536"}
The first method gets called
This is the part of the params paremeters documentation that I rely on :
Finally, "!myParam" style expressions indicate that the specified
parameter is not supposed to be present in the request.
Can't you just simply delete first request params?
#RequestMapping(value="/requestotp",method = RequestMethod.POST) //new customer
public OTPResponseDTO requestOTP( #RequestBody CustomerDTO customerDTO){
return customerService.requestOTP(customerDTO);
}
The issue actually wasn't with negating the parameter, the issue was that I was sending {"idNumber":"345","applicationId":"64536"} in the POST body and I was expecting the variables to be mapped to the method parameters annotated with #RequestParam ... this is not correct ... #RequestParam only map URL parameters .... so the controller was trying to find the best match so it was using the first method as it contained #RequestBody

HttpServletRequest in spring getting parameters values as null for post request

#ResponseBody
#RequestMapping(value = {"apiRequest"}, method = {RequestMethod.POST})
public String contestApiSignUp(HttpServletRequest req) throws JSONException {
try {
String username = req.getParameter("username");
String firstname = req.getParameter("firstname");
String lastname = req.getParameter("lastname");
String password = req.getParameter("password");
String phone = req.getParameter("phone");
Here the values I am getting all are null. That is username =null, firstname =null...
I am hitting post request with the values
http://localhost:8080/apiRequest.htm
username = Subhajit
firstname = Subha
...
like this.
But while I am using same code but,
#RequestMapping(value = {"apiRequest"}, method = {RequestMethod.GET})
using GET instead of POST then I am getting the proper values.
When you sent your HTML Form by POST to your URL /apiRequest, did you fill your data (username, firstname etc.) in fields in your form, or did you attached them to the sent URL (eg. apiRequest.htm?username=test&...) ?
Because with the second approach, you data will be accessible only through a GET request, not a POST. The first approach will work with a POST request.
Also, you do not need to call explicitly getParameter on the HttpServletRequest in a Spring Controller.
You can do this :
#ResponseBody
#RequestMapping (value = "apiRequest", method = RequestMethod.POST)
public String contestApiSignUp(
#RequestParam ("username") String username,
#RequestParam ("firstname") String firstname,
#RequestParam ("lastname") String lastname,
#RequestParam ("password") String password,
#RequestParam ("phone") String phone) {
return "Hello World";
}
From the comments, you said you are trying with postman to post the request, So are you building website or webservices? either way you should not be sending your data in the headers.
If you are building a website put together an HTML file from which
you can submit a form to this controller
If you are building webservice, change the controller and let it
accept JSON (or XML -I would discourage this though) body. Follow
this https://stackoverflow.com/a/40226580/6785908. And then from
postman (or curl), post a json instead.

Spring MVC form parameters and query parameters

In Spring 4 MVC, I'm trying to figure out how to accept both form parameters and query parameters posted to my rest endpoint and also trigger validation, but am struggling to figure out how to get this to work.
Ideally, my controller would look something like this:
#RequestMapping(value="/someurl", method=RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public someMethod(#Valid #ModelAttribute Order order, #RequestParam String parm1, #RequestParam String parm2) {
}
I need to post the form parameters to the controller URL along with some query parameters and a Content-Type = application/x-www-form-urlencoded
Any ideas on how to get this to work?
Suppose the Order class has the order_id and order_x attributes, with the following endpoint:
#RequestMapping(value="/someurl", method=RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public someMethod(#Valid #ModelAttribute Order order, BindingResult validation, #RequestParam String parm1, #RequestParam String parm2) {
}
If a client sends a POST request with application/x-www-form-urlencoded content type with following request body:
order_id=1&order_x=something&parm1=foo&parm2=bar
then an Order instance with {order_id=1, order_x=something} will be instantiated. In addition, parm1 and parm2 will contain foo and bar, respectively. BindingResult contains validation results for a preceding command or form object (the immediately preceding method argument).
See this discussion about Query Parameters in POST requests. Also Forms Spec is a good reference.

optional parameter in Spring MVC method

I am learning spring MVC and come across these methos in spring contrller MVC 3.1
ControllerClass(){
#RequestMapping(....)
public String show( Model uiModel) {
return ".....";
}
#RequestMapping(value = "/{id}", params = "form", method = RequestMethod.POST)
public String update(#Valid Contact contact, BindingResult bindingResult, Model uiModel,
HttpServletRequest httpServletRequest, RedirectAttributes redirectAttributes, Locale locale,
#RequestParam(value="file", required=false) Part file) {
if (bindingResult.hasErrors()) {
...........
return ".....";
}
parameters like BindingResult , Model ,
HttpServletRequest , RedirectAttributes , Locale ,
#RequestParam(value="file", required=false) Part are optional but I wonder where I can find these optional parameter and under which situation it can appear in method.
Parameter:
BindingResult - imagine you have an registration-form and you would pre validate the user input, then you can use the BindingResult.
Model - After the user is registered, he wants to edit his own profile he goes to a edit site, in this site you would show the data from the user. Here you can search for the user and add the user-object to the model and in the template you can read the values from the model-attribute.
HttpServletRequest provides request information.
#RequestParam(value="file", required=false) from Spring:
annotated parameters for access to specific Servlet request parameters. Parameter values are converted to the declared method argument type
Imagine you have a table of users and you would edit one of these, you select an entry and there you can send the userId as a requestparam.
There is a similar attribute, it's called #PathVariable the main difference, the #PathVariable is mandatory. The #RequestParam is optional respectively for this exist a "fallback/default value".
The #PathVariable is a part from the url:
#RequestMapping(value = "/{login}/edit", method = RequestMethod.GET)
public ModelAndView editUserByLogin(#PathVariable("login") final String login, final Principal principal) {}
The other two I have not used yet.

Need to set parameter value and datatypes taken from URI of resful web service into HashMap

#RequestMapping(value = "/{methodName}/{responseType}", method = RequestMethod.GET)
public ModelAndView execute(#PathVariable String methodName, #PathVariable String responseType,
HttpServletRequest request, HttpServletRequest response){
Map<String,String> yesMap = new HashMap<String,String>();
}
As shown in code above I need to get data types of parameters passed from {responseType} and set the same in yesMap against parameter values.
String param=request.getParameter("id");
is returning null values.
need to get data types of parameters passed from {responseType}
Its type will always be String as you are collecting it in responseType which is String.
get data types of parameters passed from {responseType} and set the same in yesMap against parameter values
I think yesMap.put("String",responseType); will do.
In the code you posted above, the follwign call
yourRootUrl/cheese/stilton
will result in these being true in your "execute" method:
methodName.equals("cheese");
responseType.equals("stilton");
I don't understand what you are trying to achieve. Your parameter names are confusing.
Its quite simple, you have declared two string paramters, which thanks to spring can be path variables.
This is a GET request, so getParamter won't work, try using String param=request.getAttribute("id"); which is completely unrelated to your path variables. Or the differetn annaotion RequestParam like so :
#RequestMapping(value = "/{methodName}/{responseType}", method = RequestMethod.GET)
public ModelAndView execute(#PathVariable String methodName, #PathVariable String responseType, #RequestParam int id)

Resources