Spring mvc - send xml text string to controller - java

I'm working on a java spring mvc application. I need to send an xml string to my controller, and get this xml as a simple text string inside controller. But can not find any solution yet. I tried this way:
#RequestMapping(value = "/test", method = RequestMethod.POST)
public String test(String post, HttpServletRequest request, HttpServletResponse response){
System.out.println("post: " + post);
}
and I have contentType: 'text/xml' in my ajax config. But the variable post always printed as null.
Also I tried consumes = MediaType.APPLICATION_XML_VALUE and consumes = MediaType.TEXT_XML_VALUE in my method, but returns me HTTP Status 415 – Unsupported Media Type. What is the problem? How can I send simple xml text to my controller?

You can read your string using RequestParam:
#RequestMapping(value = "/test", method = RequestMethod.POST)
public String test(
#RequestParam(value="post") String post, Model model){
...
}

Related

getting http 400 bad request spring mvc

I am working on Spring mvc project.
I have to implement rest apis, one api which i am implementing now return http 400 bad request. in it get method request. another api working properly for same json but this api returns HTTP 400
controller function
#RequestMapping(value = "/getSlotsByDateRange/hosid/{hos_id}/from/{start_date}/to/{end_date}" , method = RequestMethod.GET, produces = "application/json")
public ResponseEntity<SlotByDateRange> getSlotsByDateRange(#PathVariable String hos_id,#PathVariable String start_date,#PathVariable String end_date) {
return new ResponseEntity<SlotByDateRange>(hospitalService.getSlotsByDateRange(hos_id,start_date,end_date),HttpStatus.ACCEPTED);
}
Request url:
getSlotsByDateRange/hosid/0009/from/2021-04-15/to/2021-04-22
I have just implemented it and it is working for me.
#GetMapping(value = "/getSlotsByDateRange/hosid/{hos_id}/from/{start_date}/to/{end_date}" , produces = "application/json")
For get requests you can use #GetMapping instead of #RequestMapping. As #GetMapping itself contains
#RequestMapping(
method = {RequestMethod.GET}
)
Hope this helps someone else as well.

How to request origin and body of a request in Spring controller

I'm building a REST API using Java and Spring and I need to handle a POST request in my controller, but I need to extract the body from that request which is a JSON and also the "origin" of that request,
#RequestMapping(value = "/create", method = RequestMethod.POST)
public XXX createMyObject(#RequestBody String data, YYY){
MyObject mo = new MyObject();
mo.setData = data;
mo.setOrigin = yyy;
myRepository.save(mo);
return XXX;
}
I have a few questions: First is how can I obtain the origin of that request( which I guess is an url that travels in the header?), is there a similar annotation as the #RequestBody for that?.
My second question is what is usually the proper object to return in these kind of post methods as a response.
To answer your questions:
If you include HttpServletRequest in your method parameters you will be able to get the origin information from there. eg.
public XXX createMyObject(#Requestbody String data, HttpServletRequest request) {
String origin = request.getHeader(HttpHeaders.ORIGIN);
//rest of code...
}
For rest responses you will need to return a representation of the object (json) or the HttpStatus to notify the clients whether the call wass successful or not. eg
Return ResponseEntity<>(HttpStatus.ok);
You should be able to get headers and uris from HttpServletRequest object
public XXX createMyObject(#RequestBody String data, HttpServletRequest request)
As for response I'd say return String which would be a view name to which you can pass some attributes saying that operation was successful or not, or ModelAndView.
#Autowired
private HttpServletRequest servletRequest;
You can declare request object and then access in method to get Uri
Try this:
#RequestMapping(value = "/create", method = RequestMethod.POST)
public XXX createMyObject(HttpServletRequest request, #RequestBody String body) {
String origin = URI.create(request.getRequestURL().toString()).getHost();
System.out.println("Body: " + body + " Origin:" + origin);
return XXX;
}

Receiving a POST Request on Spring From Another Site

I'm a little new in Java Spring. What I want to do is as follows:
Some 3rd party is asking a "return URL" from me and I set it as follows:
https://localhost:9002/my-account/order-history
Then they send me a POST request and I'm supposed to handle it within my controller. The request has both url parameters and a form data. The request is
Request URL:https://localhost:9002/my-account/order-history?responseCode=0000&token=E0ECFC1214B19E5D11B9B587920FC5F164C5CB17E7DC67F083E0EC6676F79467DFBDF4B6CCF3C39BF47F0232D1AA42F1FA112F29B0157DDF98EE3997F781CCB1FEB070A44E530691BA36674BEA4CF56A4A43F2B9746D9C3591CF288D745A6694
Request Method:POST
Status Code:403 Bad or missing CSRF token
Remote Address:127.0.0.1:9002
Referrer Policy:no-referrer-when-downgrade
A part of the form data is:
I added the whole form data and other request info as attachment.
The controller I'm desperately trying to use is as follows:
#Controller
#RequestMapping(value = "/my-account")
public class MaviAccountPageController extends MaviAbstractController
{
#RequestMapping(value = "/order-history", method = RequestMethod.POST)
public ModelAndView process(#RequestBody final String req)
{
//consumes = "text/plain"
System.out.println(req);
System.out.println(req);
return new ModelAndView("deneme");
}
....
}
And I keep getting 403 - Bad or missing CSRF token error.
How should I implement my controller? I have checked below links and they did not work out unfortunately:
How to retrieve FORM/POST Parameters in Spring Controller?
How to explicitly obtain post data in Spring MVC?
I tried, but failed to regenerate issue on postman.
Can anyone, please, advise me about how to move on?
you can annotate your method with #CrossOrigin
#CrossOrigin
#RequestMapping(value = "/order-history", method = RequestMethod.POST)
public ModelAndView process(#RequestBody final String req)
{
//consumes = "text/plain"
System.out.println(req);
System.out.println(req);
return new ModelAndView("deneme");
}
https://spring.io/guides/gs/rest-service-cors/

Spring MVC 4 AJAX upload MultipartFile with extra parameters

I'm currently developing a file upload with AJAX (jQuery) and Spring MVC 4. Besides the file itself I have to send some extra parameters, such as a description of the file being uploaded. I'm using an $.ajax() call that sends a FormData object along with my CSRF token, like described below:
var formdata = new FormData();
formdata.append("description", $('#description').val());
formdata.append("file", $("#file")[0].files[0]);
$.ajax({
url: '/upload',
type: 'POST',
headers : {"X-CSRF-TOKEN" : $('#myToken').val()}
data: formdata,
enctype: 'multipart/form-data',
processData: false,
contentType: false,
success: function (data) {
alert("Data Uploaded: "+data);
}
});
I've found multiple examples of how to upload files using javascript's FormData object along with a Spring controller that receives a MultipartFile object, but when I try to retrieve the other parameters using #RequestParam I end up getting errors. Below is an example of what I was trying (which didn't work):
#RequestMapping(value = "/upload", method = RequestMethod.POST)
#ResponseBody
public boolean uploadFile(
#RequestParam(value = "file") MultipartFile file,
#RequestParam(value = "description") String description) {
//Do stuff...
}
After a lot of research and attempting different approaches, I found out that I could declare HttpServletRequest as a parameter and it would allow me to retrieve each parameter (but not the file itself). Below is an working example:
#RequestMapping(value = "/upload", method = RequestMethod.POST)
#ResponseBody
public boolean uploadFile(
#RequestParam(value = "file") MultipartFile file,
final HttpServletRequest request) {
String description = request.getParameter("description");
//Do some other stuff...
}
Even though the example above worked, the fact that I couldn't use annotations and have my parameters explicit in the method's signature was bugging me. So I tried a different approach changing the #PRequestParam annotation for a #ModelAttribute annotation, which surprisingly worked.
My questions are:
Why didn't #RequestParam worked, if the parameter was retrievable in the HttpServletRequest object?
Why did #ModelAttribute worked? Should I use it instead of retrieving things explicitly from HttpServletRequest?
this comes probably too late but you could pass the description as a parameter in the url:
url: '/upload?' + $.param({description: $('#description').val()});
don't forget the question mark!
and for the data you just pass the actual file:
data: $("#file")[0].files[0]
and your controller would look like this:
#RequestMapping(value = "/upload", method = RequestMethod.POST)
#ResponseBody
public boolean uploadFile(
#RequestParam(value = "file") MultipartFile file,
#RequestParam(value = "description") String description) {
//Do stuff...
}
hope that helps!

Spring REST webservice with JSON param to be consumed using Jquery AJAX

I am trying to learn Spring Framework for creating RESTful web service for my future projects. So far I have tried using GET and consume it with no problem using a simple Ajax request. I have also tried using query strings to input parameters.
As of now I am trying to create an endpoint that receives a POST request. I've been researching for some days now but to no avail (some tuts are too complicated for a beginner like me).
Here is my simple code:
Java Spring
#RequestMapping(value = "/test", method = RequestMethod.POST)
#ResponseBody
public String testString(String jsonString)
{
System.out.println(jsonString);
return jsonString;
}
Ajax
var data = {"name":"John Doe"}
$.ajax({
url: "http://localhost:8080/springrestexample/test",
method:"POST",
data:data,
dataType:'text',
success: function( data ) {
alert(data);
},
error: function( xhr, status, errorThrown ) {
alert("Error:" + errorThrown + status);
}
});
I have tried debugging tomcat and it seems like I am not passing any value on the testString. Do I need to add something on my java code?
#RequestMapping only maps your method to some url.
To access data you need #RequestParam annotation to get data, eg:
#RequestMapping(value = "/test", method = RequestMethod.POST)
#ResponseBody
public String testString(#RequestParam("name") String jsonString)
{
System.out.println(jsonString);
return jsonString;
}
Look at this manual for more examples.
Since you are passing data into body from your ajax request, so you need to retrieve from the
#RequestBody
Add this annotation before the arguments like this way;
public String testString(#RequestBody String jsonString) {
System.out.println(jsonString);
return jsonString;
}
And you are done :)

Categories