How to receive simultaneously converted and raw request body on spring mvc - java

I have implemented Jaxb2RootElementHttpMessageConverter for converting XML request to my java object and it works. My controller looks like
#RequestMapping(value = "/post", method = RequestMethod.POST)
public MyResponse post(#RequestBody MyRequest request, BindingResult result)
I want to recieve simultaneously raw xml request for storing logs and converted java object for validation and another processes like
#RequestMapping(value = "/post", method = RequestMethod.POST)
public MyResponse post(#RequestBody String originalRequest, #RequestBody #Valid MyRequest request, BindingResult result)
I have tried to get response body as HttpServletRequest's InputStream, but I got IOException: Stream closed
How to do it if I want so Spring make transformation and validation instead of my code?

Related

How to receive application/x-www-form-urlencoded Request parameters in Spring rest controller

I'm trying to write a rest endpoint which receives application/x-www-form-urlencoded. But the endpoint does not accept request parameters for #RequestBody or #RequestParam
I Have tried using MultiValueMap to grab the request parameters. But I always get 0 parameters.
Is there a way to get request values to the MultiValueMap or some other POJO class.
AD=&value=sometestvalue - This is the application/x-www-form-urlencoded requestbody. I'm trying to do the request using postman
#RequestMapping(value = "/test/verification/pay/{id}", method = RequestMethod.POST,
consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
#ResponseBody
public Response testVerificationPay(#PathVariable("id") long id, #RequestParam MultiValueMap formData,
HttpServletRequest servletRequest, ServiceContext serviceContext){
log.info("!--REQUEST START--!"+formData.toString());
}
You need to use MultiValueMap<String, String>
#RequestMapping(value = "/test/verification/pay/{id}", method = RequestMethod.POST, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
#ResponseBody
public Response testVerificationPay(#PathVariable("id") long id, #RequestParam MultiValueMap<String, String> formData) {
System.out.println("!--REQUEST START--!" + formData.toString());
return null;
}
You do not use #RequestParam on a POST request as the data is not in the URL as in a GET request.
You should use #RequestBody (doc) along with registering appropriate HttpMessageConverter. Most likely you should use: FormHttpMessageConverter
Try #ResponseBody. Then, change to a String, not a MultiValueMap, to see if the body comes in to the request.

on submitting request control is always picking up GET method and not POST

I am trying this using spring3 hibernate3 and tiles2.
#RequestMapping(value = "/capturedetails", method = RequestMethod.GET)
public String getcapturedetails(Model model, HttpSession session,
HttpServletRequest request) {
Customer customer=new Customer();
model.addAttribute("customer", customer);
return "capturedetails";
}
#RequestMapping(value = "/capturedetails", method = RequestMethod.POST)
public String addcustomer(
#ModelAttribute("Customer") Customer customer, Model model,
HttpSession session, HttpServletRequest request) {
custBarcodeService.saveCustomer(customer);
model.addAttribute("customer ", new Customer());
return "capturedetails";
}
Upon submitting request control it always picking up GET method and not POST...
How can I fix this?
I had faced similar issue in the past. In my case I was trying to make a POST request from postman with a json body to an endpoint which was receiving the data in x-www-form-urlencoded format on the controller side.
Note that if you are using #ModelAttribute in your post controller method, it receives the data in x-www-form-urlencoded format. If this case, then possible solutions would be
make the post request method receive json data by using #RequestBody:
#RequestMapping(value = "/capturedetails", method = RequestMethod.POST)
public String addcustomer(#RequestBody Customer customer, Model model,
HttpSession session, HttpServletRequest request) {
custBarcodeService.saveCustomer(customer);
model.addAttribute("customer ", new Customer());
return "capturedetails";
}
Send data in x-www-form-urlencode format from rest client
I think you might have multiple form-element open...Check your tiles layout files and remove the multiple form elements and then try to post.
Because the same solution solved my problem as well.

Receiving a MultiPart file and JSON data using Spring and AngularJS

Here's my controller below:
#RequestMapping(value="/upload", method=RequestMethod.PUT)
public ResponseEntity<String> handleFileUpload(
#RequestParam("file") MultipartFile file,
#RequestParam("data") String campaignJson,
Principal principal) throws JsonParseException, JsonMappingException, IOException {
I want to be able to receive a MultipartFile as well as a JSON string containing data associated to the file (title, description, etc).
I can get MultipartFile uploading to work on it's own, and I can receive a JSON string and parse it on its own, but when I have them together in 1 controller, it fails. Whenever I print out the String campaignJson it says [object Object] instead of the data that I'm sending (when I print out the data being sent in angular, it's in correct JSON format.)
I've tried #RequestBody, #RequestParam, #RequestPart, but to no avail.
My question is: How do I receive both a MultipartFile and data in the form of JSON in one Spring controller?
This worked for me :
#RequestMapping(value = "/{id}/upload", method = RequestMethod.PUT)
public DocumentResource uploadPut(#PathVariable("id") Long id,
MultipartHttpServletRequest request,
HttpServletResponse response) {
String next = request.getFileNames().next();
MultipartFile file = request.getFile(next);
.....
}
Edit :
Using the MultipartHttpServletRequest should not limit you in any way to use other #PathVariables or #RequestParams, so passing title and description should be possible.
I used it to upload multiple images with AngularJS and FileUploader
( angular-file-upload v1.1.5 )
like this
var uploader = new FileUploader({
url: config.apiUrl('/machine/' + $scope.id + '/images/'),
method: "post",
queueLimit: maxFiles
});

How to ignore JSON processing for a request in Spring MVC?

I have a request handler for which I would like to skip json processing and retrieve the request body as a string. Eg -
#RequestMapping(value = "/webhook", method = RequestMethod.POST)
public void webHook(#RequestBody String body) {
}
However, the above method definition doesnt work as Spring forcibly tries to parse the posted string as json and thus throws an exception.
How do i tell spring to skip json processing for this request?
use like this it'll work.
#RequestMapping(value = "/webhook", method = RequestMethod.POST)
public void webHook(HttpServletRequest request) {
String body = IOUtils.toString( request.getInputStream());
// do stuff
}
Not using #RequestBody is key here. When spring sees #RequestBody it tries to map the entire body as object.

Mapping restful ajax requests to spring

I have this piece of code:
#RequestMapping(value = "/test.json", method = RequestMethod.GET)
#ResponseStatus(HttpStatus.OK)
public #ResponseBody Object[] generateFile(#RequestParam String tipo) {
Object[] variaveis = Variavel.getListVariavelByTipo(tipo);
return variaveis;
}
As far as I know it should take a request to test.json?tipo=H and return the JSON representation of Variavel[], however when I make such request I get:
HTTP Status 406 -
type Status report
message
descriptionThe resource identified by this request is only capable of generating responses with characteristics not acceptable according to the request "accept" headers ()
By using the following function I can get the expected json:
#RequestMapping(value = "/teste.json")
public void testeJson(Model model, #RequestParam String tipo) {
model.addAttribute("data", Variavel.getListVariavelByTipo("H"));
}
What I'm doing wrong?
#RequestBody/#ResponseBody annotations don't use normal view resolvers, they use their own HttpMessageConverters. In order to use these annotations, you should configure these converters in AnnotationMethodHandlerAdapter, as described in the reference (you probably need MappingJacksonHttpMessageConverter).

Categories

Resources