How to map POST parameters to model object using spring MVC method - spring

I have a form that contains a file and some other input field elements.
Submit is done as follows:
var xhrArgs = {
form: attachmentForm,
handleAs: "json",
load: dojo.hitch(this, this._uploadSuccess),
error: dojo.hitch(this, this._uploadError)
};
var deferred = dojo.io.iframe.send(xhrArgs);
On backend i have a Spring controller listening for this POST request as follows:
#RequestMapping(value="/uploadAttachment.spr", consumes = { "multipart/form-data" })
public String execute(HttpServletRequest request, HttpServletResponse response)
Everything works fine so far.
I would like now to get all request parameters (basically the POST payload) inside a POJO object.
I tried adding a #RequestBody parameter, but it fails with bad request(400):
#RequestMapping(value="/uploadAttachment.spr", consumes = { "multipart/form-data" })
public String execute(HttpServletRequest request, HttpServletResponse response,
#RequestBody AttachmentFormModel model)
I assume it fails because the payload is not in JSON format.
So my question is: what is the best way to automatically map all request parameters into a model object?

I've managed to fix this using #ModelAttribute instead of #RequestBody

Related

How to send JSON response from controller?

I want to pass a boolean value from my controller to javascript using json but couldnot find a way as I am new to spring mvc.
While using servlet we wrote:
response.getWriter().println(somevalue)
and the somevalue can be received using ajax.
Here my controller method is:
#RequestMapping(value = REGISTERACTION , method = RequestMethod.POST)
#ResponseBody
public boolean RegisterUser(#ModelAttribute("register") Register register,HttpServletRequest request, HttpServletResponse response)
{
boolean Registrationsuccess = userService.RegisterUser(register);
return Registrationsuccess;
}
So, here the boolean variable is Registrationsuccess which I want to send to js file and receive it using ajax.
And in my javascipt function which is called using onsubmit event-->
function AccountExists()
{
$.ajax({
type: 'POST',
url: 'registerProcess',
success: function(data){
let detail = JSON.parse(data);
if( data == true)
alert("Success");
else
alert("Not ");
}
});
}
Getting error --
The target resource does not have a current representation that would be acceptable to the user agent, according to the proactive negotiation header fields received in the request, and the server is unwilling to supply a default representation.
You need to use ResponseEntity and #RestController for JSON Response.
Note : #RestController includes both annotations #Controller and #ResponseBody.
Try with this :
#RestController
#RequestMapping("controller")
public class Controller {
#PostMapping("REGISTERACTION")
public ResponseEntity<Boolean> RegisterUser(#ModelAttribute("register") Register register)
{
Boolean registrationSuccess = userService.RegisterUser(register);
return new ResponseEntity<Boolean>(registrationSuccess , HttpStatus.OK);
}
}
Try to use #ResponseBody annotation in your controller's method. And change the return type of the method to Boolean, then return Registrationsuccess instead of ModelAndView.
You can achieve this using 2 approach
Approach 1: Set model attribute and using expression language you can find on jsp
model.addAttribute("test",true);
in Jsp page
${test}
Approach 2: If you are sending ajax request instead of ModelAndView create a object
set any attribute boolean and return object from method #ResponseBody annotation you will get json in Ajax Response
#RequestMapping(value = REGISTERACTION , method = RequestMethod.POST)
public #ResponseBody MyCustomObject RegisterUser(#ModelAttribute("register") Register register,HttpServletRequest request, HttpServletResponse response)
{
boolean Registrationsuccess = userService.RegisterUser(register);
MyCustomObject cusobj=new MyCustomObject();
cusobj.setStatus(true);
return cusobj;
}
Whatever code you have written it will not return json(It is basically form submission approach) so you have to go with first approach.

Redirect POST request with additional form data in Spring

I am developing a container app for my Angular frontend in Spring. I have a mock payment gateway, which I am submitting a Angular form using POST method.
#RequestMapping(path = "/pay", method = RequestMethod.POST)
public String handleMockPayment(HttpServletRequest request, HttpServletResponse response) {
// APPEND MOCK PAYMENT STATUS CODE HERE (ResponseCode)
// something like,
// response.setParameter("ResponseCode", "1");
request.setAttribute(View.RESPONSE_STATUS_ATTRIBUTE, HttpStatus.TEMPORARY_REDIRECT); // to allow redirecting POST requests
return "redirect:/confirm";
}
In this mock controller, I need to append an additional data field to the original data received (which is the form submitted from Angular app). This data field is the mock payment success/failure code. This controller will then redirect to another controller, which is the real controller I am going to use to handle callback request from the payment server.
#RequestMapping(path = "/confirm", method = RequestMethod.POST)
public String paymentVerification(HttpServletRequest request, HttpServletResponse response) {
String orderId = request.getParameter("OrderID");
String responseCode = request.getParameter("ResponseCode"); // this is null
// do some stuff with orderId and responseCode
// ...
return "redirect:/booking";
}
The orderId is available as it was set from the initial form submission. But all the methods I tried (using Model, FlashParams, ... ), did not work (responseCode was null all the time).
How can I append this new parameter here?
Any alternative method to mock payment gateway is also appreciated. My goal is to either append a response code to the existing form data, or create a new form within the mock controller (handleMockPayment) with necessary mock attributes. Thanks in advance.
you can use RedirectView to achieve this.
#RequestMapping(value = "test/{id}")
public RedirectView handleMockPayment (HttpServletRequest request, HttpServletResponse response) {
...
RedirectView rv = new RedirectView();
rv.setContextRelative(true);
rv.setUrl("/confirm/{responseCode}");
return rv;
}
you can access same in /confirm using path variable.

How to pass json parameters with jax-rs?

if I want to post json parameter to a url with jax-rs, how to receive the parameters in the back end and convert it into an integer array?
parameters:{"sbfIdList":[14]}
backend service(in java): I tried below , but feel no luck, I just got an empty array.
#POST
#Consumes(MediaType.APPLICATION_JSON)
#Path("/delete")
public String deleteSbc(#QueryParam("sbfIdList") List<Long> sbfIds,#Context HttpServletRequest request, #Context HttpServletResponse response) {
return "";
}
I request the backend service using POST method.

Spring 3.2 forward request with new object

I'm trying to forward a request from one controller to another controller and set a object in request so that the forwarded controller can use it in #RequestBody.
Following is the exact scenario:
Twilio calls a controller method with data sent by client as following:
#RequestMapping(value = "/sms", method = RequestMethod.POST)
public String receiveSms(#RequestParam("Twiml") String twiml,
HttpServletRequest request,
HttpServletResponse response) {
//TODO - Create new instance of Activity and populate it with data sent from client
return "forward:/activity/new";
}
Now, I want to forward this request to ActivityController which already handles the request from web/rest clients.
ActivityController.java has a method with following signature:
#RequestMapping(value = "/activity/new", method = RequestMethod.POST)
public ResponseEntity<Activity> updateLocation(
#RequestBody Activity activity) {
}
Is it possible? If yes, how?
Thanks,
Create the object and add it to the request as an attribute in the first controller,
request.setAttribute("object",new OwnObject()),
return "forward:/activity/new";
In the updateLocation Method retrieve that object from the request
#RequestMapping(value = "/activity/new", method = RequestMethod.POST)
public ResponseEntity<Activity> updateLocation(
#RequestBody Activity activity, HttpServletRequest request) {
OwnObject o = (OwnObject) request.getAttribute("object");
}

Using both #RequestBody and #RequestParam together in spring mvc3

I am using spring-mvc 3.1.0.RELEASE and for some reason, mapping POST with query params and request body does not work.
Here is how my controller method looks:
#RequestMapping(method = POST, value = "/post-to-me/")
public void handlePost(
#RequestBody Content content,
#RequestParam("param1") String param1,
#RequestParam("param2") String param2
){
//do stuff
}
However, if I convert all the request params to path params, mapping works. Has anyone run into something similar?
Thanks!
EDIT:
"does not work" == 404 when I try doing, POST /post-to-me?param1=x&param2=y
First, your POST url doen't match the controller method url, your POST url must be "/post-to-me/?param1=x&param2=y" not "/post-to-me?param1=x&param2=y"
Second, where did Content class come from?? I used a String and works fine for me
#RequestMapping(method = RequestMethod.POST, value = "/post-to-me/")
public void handlePost(#RequestBody String content,
#RequestParam("param1") String param1,
#RequestParam("param2") String param2, HttpServletResponse response) {
System.out.println(content);
System.out.println(param1);
System.out.println(param2);
response.setStatus(HttpServletResponse.SC_OK);
}
Note that I used HttpServletResponse to return a HTTP 200 code, but I think there is a better solution for return Http codes, check this: Multiple response http status in Spring MVC
Trailing slash at the end of your request mapping value might be the problem.
Try:
#RequestMapping(method = RequestMethod.POST, value = "/post-to-me")
or send your POST request to POST /post-to-me/?param1=x&param2=y

Resources