recieve data as json and process at server side (java spring) - spring

Send the parameters to server(spring framework) via get request, i am thinking of making a json object of all those parameters and send in get request so that in java spring i can recieve at as a map at the controller class in spring , how to achieve this
I am new to spring please help me out
I so far tried to send those parameters singly like(pram1,param2,param3,param4)
and recieve at the server side as string by setting param to string in type script before making get request to the server->i recieved parameters as map in controller
but i dont think it is a best way
{
param1: "param1"
param2: "param2
paramn: "paramn"
}
Send the above to server in the controller class ↓
#RequestParam MultiValueMap<String, String> requestMap
I want to recieve parameters as
String param1= requestMap.get("param1");
String param2=requestMap.get("param2");
If map type was an object it would be great so that i can recive any kind of object
example
at client side i am sending {param1: "myName", id: 0001}
at server side requestMap.get("param1"); requestMap.get("id");

As suggested by chrylis there's no need to manually extract parameters you can define a DTO/Request/POJO class, and Spring will map it automatically.
public class SampleDTO{
private String param1;
private String param2;
.
.
//getters and setters
}

if you specify RequestParam as hashmap, it gets automatically converted from json by jackson. Alternatively, if you are using String as the param, you can use ObjectMapper to convert it to a Map and get values from there.

You can map your incoming json to a Hashmap like so
#RequestMapping(method = RequestMethod.GET)
public String yourMethod(#RequestParam Map<String, String> parameters) {
String name = parameters.get("A"); //If your URL is http://test.com?A=ABC
...
}

Related

Get raw json string in Spring MVC Rest

Im have #RestController and this method. how can I get any json and then select the handler depending on the method and pass it there for processing
PS. I use GSON instead of JACKSON
You can use #RequestBody in your method and take a String parameter:
public AbstractJsonResponse(#PaqthVariable String method, #RequestBody String json) {
...
}
See here: https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/bind/annotation/RequestBody.html
Mainly the part that says:
Annotation indicating a method parameter should be bound to the body of the web request

how to validate map as #RequestParam in spring controller

how to validate map as #RequestParam in spring controller
public class Controller {
#RequestMapping(value="/")
public ModelAndView requestMethod(#RequestParam Map<String, String> mapParam){
////some stuff here
};
First of All you should send Map as RequestBody not as RequestParam.
You should create request DTO object instead of Map, to validate the Map you need to traverse and validate each key individually but using DTO you can directly validate using #Valid with your #RequestBody.
Refer this link for #Valid related code : https://www.baeldung.com/spring-boot-bean-validation

Spring's RestTemplate: complex object to query params

I have a complex object like this:
public class ComplexObject {
private String a;
private String b;
...
private String z;
//getters and setters
}
I want to call a web service that receives all the complex object fields: http://localhost:8080/api/some_service?a=something&b=something&...&z=something
Is there any way to pass a ComplexObject to RestTemplate and have the work done automatically or I have to do the manual mapping by myself?
Thanks!
YES! there is a way to pass complete complex object to make the service call and then for sure it can be achieved automatically.
And for this you have to alter the way you send this complexObject and have to use HTTP POST (highly recommended ), as:
public HttpStatus send()
{
ComplexObject complexObj = getYourFilledObject();
ResponseEntity<HttpStatus> response = restTemplate.postForEntity(ROOT_URI, complexObj, HttpStatus.class);
return response;
}
And if not and GET is the only option then unfortunately you have to send as you’re. Because at the end of the day either you use rest templates ‘s function which intake params map or you create your own URI with params, it is the same HTTP GET and you have to achieve programmatically.
For examples & illustration you can visit here and best reference will be spring resttemplate doc

Get request body as string/json to validate with a json schema- Spring boot REST API

I'm trying to validate JSON (passed by a client as a request body) before it is converted into a model in Controller method.
If validation passes then return nothing, let the process continue as it was (spring boot to convert JSON into a model marked as #RequestBody). Throw error in case validation fails (everit-org/json-schema).
I tried to two way:
Implement HandlerMethodArgumentResolver, but resolveArgument() doesn't give request body details as it is already read and stored in ContentCachingRequestWrapper.
NOTE: inputStream in ContentCachingRequestWrapper doesn't have any request body details.
Using spring Interceptor. But this doesn't help me to find request body type passed in the request. As JSON schema is different for each request.
Any other approaches I can try with?
I cannot add a comment ... so ...
What kind of validation do you need? If you only want to validate the fields like length of a string or range of a number and so on. I recommend you use #Validated on controller mehtod parameter, and model:
#NotNull
#Size(min = 32, max = 32)
private String id;
controller:
#PatchMapping
public Object update(#RequestBody #Validated User user, Errors errors) {
...
}
If there is something wrong, errors.hasErrors() will return true.
edit:
OK, I did some tests, in a filter :
HttpServletRequest httpServletRequest = (HttpServletRequest)request;
ServletInputStream inputStream = httpServletRequest.getInputStream();
byte[] a = new byte[1024];
inputStream.read(a);
System.out.println(IOUtils.toString(a));
I got a json string (a piece of request body) :
{"template":"5AF78355A4F0D58E03CE9F55AFA850F8","bd":"" ...

Mock controller with an object parameter

I'm trying to test a method with this signature:
#RequestMapping(value="/Employee/{id}", method=RequestMethod.PUT, consumes="application/json")
#Transactional
public #ResponseBody Map update(#PathVariable Integer id,
#RequestBody HashMap<String, Object> information) {
}
The problem is that MockMvc param attributes accept only String parameters, is there a way to pass a HashMap or an instance class object to the RequestBody as parameter?
When I try to pass a HashMap as a string, I get a MismatchException.
You need to use Jackson for this. The idea is to deserialize your objects (doesn't matter that it's HashMap) into JSON string and pass it into MockMvc.
Here is tutorial how to do that. Just search for TestClass there and take a look how it is used. Skip the unit testing of GET requests.

Resources