I am working on spring boot with graphql implementation. And, I am mapping my pojo request parameters to an internal project with help of mapstruct. I have written my mapper class where I have mapped my request parameters [source] to the target parameters. I have two different request payload in place and parameters will be mapped based on the request body.
Whatever parameters are given in the request, only those parameters should get mapped and should return the mapped request body. But in my case, When I don't send few parameters in the request payload, after mapping parameters those are not sent in the request also gets added in the conversion.
Sample Request1:
{
GetOrder( input : {
orderId: xxxxxx,
orderType: Online
})
}
Sample Request2:
{
GetOrder( input : {
orderId: xxxxxx,
orderType: Online,
user :{
userName: "ABC"
})
}
In this sample, "User" object is required in the request2, where in request1, I am not sending the user object. But when I send request1, this "User" object is also getting added in the request payload as an empty object after the mapping using mapstruct.
Could you someone please guide me on this.? Thanks in advance!
Related
I want to make a GET request to my server that receives two parameters, uniqueConfig and commitHash. The code for this operation in my Controller class is as follows:
#GetMapping("/statsUnique")
public ResponseEntity<Object> hasEntry(#RequestParam("uniqueConfig") String uniqueConfig,
#RequestParam("commitHash") String commitHash) {
Optional<Stats> statsOptional =
codecService.findByUniqueConfigAndCommitHash(uniqueConfig, commitHash);
if (statsOptional.isPresent()) {
return ResponseEntity.status(HttpStatus.OK).body(true);
}
return ResponseEntity.status(HttpStatus.OK).body(false);
}
The issue is, when I try to make the GET request using Postman, the server returns a 400 - Bad Request with the following error message:
MissingServletRequestParameterException: Required request parameter 'uniqueConfig' for method parameter type String is not present]
my JSON on Postman looks like this:
{
"commitHash": "ec44ee022959410f9596175b9424d9fe1ece9bc8",
"uniqueConfig": "bowing_22qp_30fr_29.97fps_fast-preset"
}
Please note that those aren't the only attributes and I've tried making the same request with all of them on the JSON. Nonetheless, I receive the same error.
What am I doing wrong here?
A GET request doesn't (or at least shouldn't) have a body. Parameters defined by the #RequestParam annotations should be sent in the query string, not a JSON body, i.e., the request should be something like
http://myhost/statsUnique?commitHash=commitHash&uniqueConfig=bowing_22qp_30fr_29.97fps_fast-preset
I am using React as frontend and Java Spring Boot as backend.
React sends JSON form data as GET/PUT/POST requests to my backend url (http://localhost:8080/test). Now, I wan't to send this JSON forward to another interfaces GET endpoint (https://another/interface/add?id={id}). This interface then queries database based on the id and answers 200 OK message with a JSON reply which I need to display (send back to frontend).
1. What is the correct way of sending a request to another interface from Spring Boot backend? In the same method I catched the frontends data?
2. I also have to set HTTP headers to the GET request, how would I go on about this?
Example of how Frontend is sending an id field as a JSON to backend:
React POST
addId = async (data) => {
return this.post(/localhost:8080/test/id, data)
}
Example of how Backend is receiving the id field:
Spring Boot POST
#PostMapping("test/id")
public String test(#RequestBody String id) {
return id;
}
As I understand you want to get data from backend with json body and httpstatuscode 200 . Am i right?
May be you can try this
#GetMapping(/interface/add)
public ResponseEntity<?> test(#RequestParam("id") String id){
//write code you want
return ResponseEntity.status(HttpStatus.OK).body("string" or dto possible);
}
ResponseEntity send body with httpstatus code and if you want to send requestparam you set #RequestParam annotation to set .
When I do project with springboot and react. I use json type to exchange data. And Most Services usually exchange data with json data type.
2.I confused about this Question if you send data React to springboot your code is right
Axios.get("localhost....", data) you can change http type with
Axios.(get, post, delete)
I have a spring boot controller endpoint as follows.
#PutMapping("/manage/{id}")
public ResponseEntity<Boolean> manage(#PathVariable Long id, #RequestBody Type type) {
...
}
Where Type is an Enum as follows.
public enum Type {
ONE,
TWO
}
ISSUE 1: When I test this controller, I have to send the content as "ONE" instead of ONE for a successful invocation. i.e. it works with the following code.
mvc.perform(put("/api/manage/1")
.contentType(MediaType.APPLICATION_JSON_VALUE)
.content("\"" + Type.ONE + '\"'))
.andExpect(status().isOk());
It does not work with
mvc.perform(put("/api/manage/1")
.contentType(MediaType.APPLICATION_JSON_VALUE)
.content(Type.ONE.name()))
.andExpect(status().isOk());
ISSUE 2: I am not able to invoke this method from the Angular service.
this.http.put<string>('/api/manage/' + id, type)
gives me
org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'text/plain;charset=UTF-8' not supported
Everything works when I add the Enum to a Dto and send an object from the client. But due to some business requirements, I want to use the current structure itself. i.e the Enum as a RequestBody.
UPDATE
I also tried to change the controller method structure to
#PutMapping(value = "/manage/{id}", consumes = MediaType.TEXT_PLAIN_VALUE)
I get the following error.
Content type 'text/plain' not supported
Both issues stem from trying to use a JSON endpoint as a plain text endpoint.
Ad 1, ONE is invalid JSON ("ONE" is valid)
Ad 2, when you just post a string, it is sent as text/plain and the endpoint complains.
Probably adding consumes="text/plain" to your #PutMapping will solve the problem, but frankly - I am not sure if string/enum mappings work out-of-the-box in the hodge-podge that is spring boot.
I already search tutorial in spring for method POST, insert the data with response entity (without query) and I getting error in ajax. I want to confirm, What is format url from ajax to java? below my assumption:
localhost:8080/name-project/insert?id=1&name=bobby
is the above url is correct? because I failed with this url. the parameter is id and name.
mycontroller:
#PostMapping(value={"/insertuser"}, consumes={"application/json"})
#ResponseStatus(HttpStatus.OK)
public ResponseEntity<?> insertUser(#RequestBody UserEntity user) throws Exception {
Map result = new HashMap();
userService.insertTabelUser(user);
return new ResponseEntity<>(result, HttpStatus.CREATED);
}
my daoimpl:
#Transactional
public String insertUser(UserEntity user) {
return (String) this.sessionFactory.getCurrentSession().save(user);
}
the code running in swagger (plugin maven) but not run in postman with above url.
Thanks.
Bobby
I'm not sure, but it seems that you try to pass data via get params (id=1&name=bobby), but using POST http method implies to pass data inside body of http request (in get params, as you did, data is passed in GET method) . So you have to serialize your user data on client side and add this serialized data to request body and sent it to localhost:8080/name-project/insert.
As above answer suggest. You are trying to pass data as query parameters.but you are not reading those values in your rest API.either you need to read those query parameters in your API and then form an object or try to pass a json serialized object to your Post api as recommendation. Hope it helps.
I am trying to perform an ajax request using the jsonp data type due to cross domain issues in a clustered environment.
I can make jsonp requests to methods mapped with no #RequestBody parameters, but when I do try to implement a RequestMapping with a #RequestBody parameter I get a 415 Unsupported Media Type error.
Usually when I get this problem it is due to some property not mapping correctly between the json object posted and the Java object it is mapped to in Spring. But the only discrepency I can find is that using jsonp it adds a parm named callback and one with the name of an underscore "_"
So I added the tag #JsonIgnoreProperties(ignoreUnknown = true) to my Java object and figured that should solve that, however it is still throwing this error.
Is there anything else I need to do?
EDIT: I am now seeing this stack trace in the debug log output from Spring:
org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/octet-stream' not supported
$.ajax({
url : 'http://blah/blah.html',
data : { abc : '123' }, (I also tried to JSON.stringify the object but no difference)
dataType : 'jsonp',
success : function(response) {
alert('ok '+JSON.stringify(response));
},
fail : function(response) {
alert('error'+JSON.stringify(response));
}
});
The Spring controller is:
#RequestMapping({ "blah/blah" })
#ResponseBody
public ReturnObject getBlahBlah (#RequestBody MyObject obj) throws Exception {
}
The parameter object is:
#JsonIgnoreProperties(ignoreUnknown = true)
public class MyObject {
private String abc;
// getter and setter for abc auto generated by MyEclipse
}
I have a breakpoint on the Controller method which is never hit.
JSONP means that jQuery will create a <script> element with src pointing to your controller URL.
As you can see, this approach doesn't allow you to pass any data in request body, all data should be passed in URL as query parameters. data : { abc : '123' } means that abc=123 is added to the URL.
At controller side you need to use either #RequestParam (to bind inidividual parameters) or #ModelAttribute (to bind multiple parameters into an object):
public ReturnObject getBlahBlah (#RequestParam("abc") int abc) throws Exception { ... }