Spring Controller GET/POST/PUT to another interface - java

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)

Related

Getting a 400 Bad Request when Angular HttpClient posts a Set<> to a SpringBoot endpoint

I am exposing an endpoint that accepts a Set<> as a #RequestBody this way :
public #ResponseBody ResponseEntity<Response> addTeamOwner(#RequestParam("teamName") String teamName, #RequestBody Set<String> emails, HttpServletRequest request){...}
And my Angular frontend is calling this endpoint like this :
let params = new HttpParams().set('teamName', teamName);
let url = `${UrlManager.TEAMS}/addOwners?${params.toString()}`;
this.httpClient.post<any>(url, emails);
For some reason I'm getting 400 Bad Request : HttpErrorResponse {headers: HttpHeaders, status: 400, statusText: 'Bad Request', url: 'http://localhost:4200/api/teams/addOwners?teamName=DEMO_TEAM', ok: false, …}
It seems that the Set that Angular is sending is not accepted by the backend because when I change to an Array everything works fine !
FYI, my API is SpringBoot and my frontend is Angular.
Actually it is not possible to serialize data sent within Set because the data are not stored as properties.
The solution was to convert the set to an array this way :
this.httpClient.post<any>(url, [...emails]);
and the backend is able to deserialize it as a Set correctly.

Cross Site Scripting support on Rest based POST Web service

I have designed a REST based post Service using Spring 3.
The service method consumes parameter as String and responds data as String. The param and response can be json or string
#RequestMapping(value = "/service", method = RequestMethod.POST)
public #ResponseBody String Service(#RequestParam("param") String param) {
Sample POST Request:
http://IP:PORT/test-project/service
param={"name":"John"}
Sample response to above request:
{"age":"31"}
Is there a way to safeguard this request against Cross Site Scripting?
If yes then how can I achieve XSS support once I receive request on param parameter??
If you aren't returning the parameter value (or any manipulation of it) in the response, you don't have an XSS vulnerability.
Not that it means that your service is completely secure, of course.

Spring boot PutMapping with Enum as RequestBody issue

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.

Spring MVC Override Received Content Type

I'm working on a Spring MVC application and have a client that I have no control over. This client is POSTing JSON data but transmitting a application/x-www-form-urlencoded header. Spring naturally trusts this header and tries to receive the data but can't because its JSON. Has anyone had experience overriding the header that Spring receives or just specifying exactly what type of data is coming, regardless of the headers?
You can do two things;
Change the client to send the Content-Type:
application/json header
Write a Servlet Filter or Spring Interceptor which is on top of the Spring Controller and checks for the header Content-Type. If it is not application/json then it changes it to application/json.
Why don't you write a separate controller to handle application/x-www-form-urlencoded requests. If the request is a valid JSON, then you can parse it and forward it to to appropriate service.
This way you can also handle a case in future where you get request of same type which is not a valid JSON.
#RequestMapping(value = "/handleURLEncoded", method = RequestMethod.POST, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public #ResponseBody Object handleURLEncoded(HttpEntity<String> httpEntity) {
String json = httpEntity.getBody();
//now you have your request as a String
//you can manipulate it in any way
if(isJSONValid(json)) {
JSONObject jsonObj = new JSONObject(json);
//forward request or call service directly from here
//...
}
//other cases where it's not a valid JSON
}
Note: isJSONValid() method copied from this answer

What is format from url in AJAX to send POST method with RESPONSE ENTITY

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.

Categories

Resources