Can we use #RequestParam along with #RequestBody in Spring Controller - spring

public ResponseEntity<String> action(#RequestParam(value = "id") final String id,#RequestBody item item)
throws IllegalAccessException {
System.out.println("");
}
I get Bad request error whenever I hit this URL.
Request JSON:
{
"id": "rw121232323e",
"item":{
"code": "shirt",
"qty":10
}
}
But the code works when I have only #RequestBody in my controller method.
Wanted to know if #RequestParam and #RequestBody can be used together.

With the example json you provided, the id is part of the body, not a request parameter. Also, the default value for the "required" attribute of #RequestParam is true, and this I suspect is the reason you are getting the Bad Request response. Either you specify the parameter in the url (by putting ?id=yourId at the end of it), or you specify the request parameter like this :
#RequestParam(required = false) String id

Related

Error 400 when receiving data from URL parameters en Spring MVC

I am trying to receive data from an URL with two parameters like this one:
http://localhost:80000/xxx/xxx/tickets/search?codprovincia=28&municipio=110000
No matter the approach, I am always getting a 400 error, but if I access the URL without the two parameters, the controller returns the view correctly (without the parameters, naturally)
This is the code of my controller:
#Controller
#RequestMapping(value = "/xxx" )
public class BuscadorIncidenciasController extends BaseControllerWeb {
#RequestMapping("tickets")
public String tickets(Model model, #RequestParam ("codprovincia") String codprovincia, #RequestParam ("municipio") String municipio, HttpServletRequest request) throws NoAjaxException {
//...
return CONST.JSP_VIEW;
}
...}
Extra info: if I use this URL:
http://localhost:9081/xxx/xxx/tickets/search/28/790000
And this code:
#Controller
#RequestMapping(value = "/xxx" )
public class BuscadorIncidenciasController extends BaseControllerWeb {
#RequestMapping(value = "buscar/{codprovincia}/{municipio}", method = RequestMethod.GET)
public String buscar(#PathVariable Integer codprovincia, #PathVariable Integer municipio ,Model model, HttpServletRequest request) throws NoAjaxException {
//...
return CONST.JSP_VIEW;
}
...}
It gets the parameters correctly. The problem is that I have to use the first URL. I have reviewed similar questions about similar issues, and I have implemented the solutions to those issues, but I get the 400 error regardless what I try (add value="xxx=, required=false, and other suggestions.)
For RequestParam, you need to explicitly add 'name' attribute
#RequestParam(name = "codprovincia"), #RequestParam (name = "municipio")
No need to for HttpServletRequest, unless you have reason
Also, in your 'tickets' method, RequestMapping is not conforming to your URL path.
I think it should be
#RequestMapping("/xxx/tickets/search")
Cheers!

ResponseEntity<MyDTO> is Returning Missing/Incomplete JSON

I'm seeing an issue with JSON cut-off/missing/incomplete when getting a response back from my service in Spring Boot.
Example:
ResponseEntity<MyDTO> responseEntity = myService.getMyDTO();
return responseEntity;
public class MyService {
public ResponseEntity<MyDTO> getMyDTO() {
return restTemplate.exchange(requestUrl, HttpMethod.GET, new HttpEntity<>(httpHeaders), MyDTO.class)
}
}
When debugging and inspecting the body of ResponseEntity, which is MyDTO instance, it contains
all the expected fields.
public class MyDTO {
private Information information;
private Address address;
}
public class Information {
private String firstName;
private String lastName;
}
public class Address {
private String streetName;
}
Debugging:
MyDTO
body
information
firstName > "John"
lastName > "Doe"
address > null
Expected JSON:
{
"information": {
"firstName": "John",
"lastName": "Doe"
},
"address: null
}
Actual JSON:
{
"information": {
"firstName": "Jo
Yes, the ending brackets are even missing from the response JSON.
Note: address is null because the response from upstream service returns a 400 and we map that response to our DTO (MyDTO). Initially, I thought this was the problem until debugging confirmed that the mapping was done correctly.
Here's what's really strange. If I take that ResponseEntity's body and put it in another ResponseEntity, than it returns fine and works. The service even returns faster, which is weird too.
ResponseEntity responseEntity = myService.getMyDTO();
return new ResponseEntity(responseEntity.getBody(), responseEntity.getStatusCode());
Anyone knows what's going on? Is it a networking, Spring Boot, or my code issue? Why would returning a new ResponseEntity fix the issue?
Found the issue. The upstream service contains a 'Content-Length' header, which is too small and causing the missing/incomplete JSON on client-side.
This is happening because you are calling the restTemplate.exchange() method; if you use the getForObject() method (in case of post call postForObject()) instead it will work.
This method will first create the MyDTO class object and then you need to add that object in the ResponseEntity object to return it.
Example:
MyDTO myDtoObject = restTemplate.getForObject(requestUrl, MyDTO.class);
return new ResponseEntity<>(myDtoObject, HttpStatus.OK);

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

how to get both value #RequestBody and #RequestParam together

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"

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.

Resources