i want to call REST API Controller from my REST API Controller.
"http://localhost:8080/function/1?filter={"id":1435263}"
Since we cannot send directly ({"id":1435263})JSON query String along with url because of spring mvc cannot read "{",i am sending query string(Search variables) in the form of map .
Object response = restTemplate.getForObject(crudControllerURL,
Object.class, map);
where map contains the values .
On Server side i am unable to retrieve this map. I tried #RequestParam Object obj but it did not work . I am clueless how can i get these values there?
Do i need to convert it into POST?
EDIT
when i try to use whole url with query String then i recieve
java.lang.IllegalArgumentException: Not enough variable values available to expand '"id"'
Adding Server side contoller code snippet(not whole) and please note i need to access map in Server REST API Controller .
Server side controller
#RequestMapping(value = "/{function}/{type}", method = RequestMethod.GET)
public List<Order> performFetchAll(#PathVariable String function,
HttpServletRequest request) throws JsonParseException,
JsonMappingException, IOException, InvalidAttributesException {
String requestQueryString = request.getQueryString();
if (requestQueryString == null
|| requestQueryString.equalsIgnoreCase(""))
return orderService.findAll();
Please provide your feedback. Thanks.
You should do this probably than complicating the request:
URL can be changed like this : http://localhost:8080/function/1?idFilter=1435263
#RequestMapping(value = "/{function}/{type}", method = RequestMethod.GET)
public List<Order> performFetchAll(#PathVariable String function, #RequestParam("idFilter") String id, HttpServletRequest request) throws JsonParseException,
JsonMappingException, IOException, InvalidAttributesException {
//DO something
}
If your filter request is going to be big and complex like a json, change your method to POST and take the JSON and do your logic.
Related
If I have a method that has like 10 request parameters and I may not always need all of them
#GetMapping("/whatever")
public ResponseEntity<String> sendSomethingBack(#RequestParam String optionalRequestParam1,
#RequestParam String optionalRequestParam2,
...
#RequestParam String optionalRequestParam10)
So in this header I'd like something that is like
#GetMapping("/whatever")
public ResponseEntity<String> sendSomethingBack(#RequestParam RequestParamBuilder requestParamBuilder)
and then it would just build an object for me with all valid parameters sent through filled out and the rest being null or something
You can have multiple parameters without defining their names by just using a Map:
#GetMapping("/whatever")
public ResponseEntity<String> sendSomethingBack(#RequestParam Map<String, Object> params) {
log.info("Params: {}", params.entrySet();
}
How to make the call:
curl --location --request GET 'http://localhost:8080/whatever?integer=45&string="some text"&boolean=true'
Output:
Params: [integer=45, string="some text", boolean=true]
If you wanted the parameters to be passed into an object, you can use a POJO as you were but remove the #RequestParam notation:
#GetMapping("/whatever")
public ResponseEntity<String> sendSomethingBack(RequestParamBuilder requestParamBuilder)
Then create a class for RequestParamBuilder. You can mark the fields inside the POJO as #NotNull etc to handle validation and build out the object with only the params that were included in the request, but the POJO must be annotated with #Valid if you wish for spring to validate it this way:
#GetMapping("/whatever")
public ResponseEntity<String> sendSomethingBack(#Valid RequestParamBuilder requestParamBuilder)
I'm trying to write a simple HTTP REST service using Spring 4.
I'm having troubles sending data to a POST endpoint
#RequestMapping(value = "/onlyPost", produces = "application/json", method
= RequestMethod.POST)
public #ResponseBody ResponseEntity<?> createUser(#RequestParam("value1")
String param1, #RequestParam("value2") String param2) {
....
}
While trying to send data with Postman, I receive a 400 message (obviously the values are setted in the request's body)
"message": "Required String parameter 'value1' is not present",
What I have noticed is that the issue is somewhat related to the headers, because when I remove the postman's header (Content-Type: application/json) everything works fine.
I tried for more than one hour fixing this by myself with no results. Any hints?
#RequestParam is used to read a URL query parameter.
http://localhost:8080/springmvc/onlyPost?value1=foo&value2=bar
For instance, in the URL above, value1 and value2 are query parameters that you can read using that annotation.
But if you want to read a JSON request instead, you need to change the method to:
#RequestMapping(value = "/onlyPost", method = RequestMethod.POST,
consumes = "application/json")
public #ResponseBody ResponseEntity<?> createUser(#RequestBody User user) {
....
}
where User is a POJO holding the two fields:
public class User {
private String value1;
private String value2;
// getters and setters...
}
HTTP 400 is returned when your request is badly formatted, i.e. missing required request parameters
#RequestParam is for URL Params, if you want to pass them like that, you call
<api_url>/onlyPost?value1=<value1>&value2=<value2>
but... if you want to create user you should rather use #RequestBody and put your user data there. Something like that:
#RequestMapping(value = "/users", produces = "application/json", method
= RequestMethod.POST)
public #ResponseBody ResponseEntity<?> createUser(#RequestBody User user) {
[...]
}
if you are creating REST api you should use concrete endpoints, here is a pretty cool reading with some tips: http://www.vinaysahni.com/best-practices-for-a-pragmatic-restful-api
I have generic controller which has encoded request body. I would like this controller decode body and set this decoded body and redirect to specific controller. Below is my controller
#RequestMapping(value = "/{type}", method = RequestMethod.POST)
public String save(#RequestBody String base64Body, #PathVariable("type") String type) throws IOException {
String json = decompress(Base64.getDecoder().decode(base64Body));
//now I'd like set json to request body, change header, and redirect to "type" controller
return format("redirect:/%s/save", type);
}
Above code should call my controller from addres /type/save with decoded body, Is it even possible? Thanks
format("redirect:/%s/save/json=%s", type, json);
OR just autowire the redirect target controller to the main one and call the method directly without http transport.
I am new to Spring and I want to write a controller which will take Collection/Iterable as arguments. Like this:
#RequestMapping(value = "friends", method = RequestMethod.POST)
public #ResponseBody Callable<Iterable<User>>
getFriendsOfUser(#RequestParam(required = true, name = "mobiles") Iterable<String> mobs) {
// return callable
}
There is no compilation error, but I cannot make it work. Can you say how will this work? And how shall be the request to this api be constructed?
public String getFriendsOfUser(#RequestParam(required = true, value = "mobiles") String[] mobiless){
....
}
and your mobile should be
mobiles=myValue1&mobiles=myValue2&mobiles=myValue3
or
mobiles=myvalue1,myValue2,myValue3
still if you have any doubt post your front-end code and Ajax call.
You've mapped a POST method so you might need #RequestBody instead of #RequestParam
#RequestParam is, as the name implies, for request parameters: [host]/endpoint?param=foo&secondParam=bar
whereas
#RequestBody is for JSON/XML or any other type content sent as the request's body.
I have a requirement where the back-end Spring controller is expecting certain values in the request header, i.e certain custom headers.
The view, a jsp has a html form which will submit the parameters from the end user to the controller. Since it is not possible to send custom headers from an html form or javascript function without using XMLHttpHeader. I cannot use XMLHttpHeader in this case since that will be an AJAX call and in my case i want a form submit.
The only option left for me is, add a mediator servlet which will intercept the call from the jsp, read the values from the request parameter and then add them as request headers and forward them to the final controller. Since it is not possible to add custom header in HttpServletRequest, i used HttpServletRequestWrapper as given in the
example.
The problem is to forward it to the Spring controller , the following code
MockHttpRequestWrapper req = new MockHttpRequestWrapper(request);
req.addHeader("REMOTE_USER", ssoId);
req.addHeader("REALM", realmId);
RequestDispatcher dispatcher = request.getRequestDispatcher(url);
dispatcher.forward(req, response);
where MockHttpRequestWrapper is a type of HttpServletRequestWrapper as per the example
public class MockHttpRequestWrapper extends HttpServletRequestWrapper {
private Map customHeaderMap = null;
public MockHttpRequestWrapper(HttpServletRequest request) {
super(request);
customHeaderMap = new HashMap();
}
public void addHeader(String name,String value){
customHeaderMap.put(name, value);
}
#Override
public String getParameter(String name) {
String paramValue = super.getParameter(name); // query Strings
if (paramValue == null) {
paramValue = (String) customHeaderMap.get(name);
}
return paramValue;
}
}
I haven't tested the sample with Filters but i expected the same to work with RequestDispatchers. The final controller is called but the headers are not to be found.
Is the same Request object not passed to the controller? IN the controller the code
request.getHeader("REMOTE_USER")
returns null.
Looking forward to answers to expand my understanding on the subject :)