Passing json object to spring mvc controller using Ajax - spring

I am trying to send a json via Ajax request to a Spring mvc controller without success.
The json string has the following form:
{"Books":
[{'author':'Murakami','title':'Kafka on the shore'},{'author':'Murakami','title':'Norwegian Wood'}]}
The controller that parses the json wraps it through this java bean:
class Books{
List <Map<String, String>> books;
//...get & set method of the bean
}
The controller method has the following form:
#RequestMapping(method = { RequestMethod.GET, RequestMethod.POST }, value = "/checkBook.do")
public ModelAndView callCheckBook(
#RequestBody Books books){....}
Unfortunately this does not work, I get the following error when invoking the method:
"Null ModelAndView returned to DispatcherServlet with name..."
Where am I getting wrong?
Thank you in advance!
Regards

create a Model class
class Books
{
private string author;
private string title;
// gets and sets
}
And Also create Wrapper class like this
class BookWrapper{
private List<Books> Books; // this name should matches the json header
}
Now in controller
#RequestMapping(method = { RequestMethod.GET, RequestMethod.POST }, value = "/checkBook.do")
public ModelAndView callCheckBook(
#RequestBody BookWrapper Books){....}
in Ajax call create a seralizeArray of you forum this will give you json object and then it will bind to the wrapper class

Related

Error 400 when receiving data from URL parameters en Spring MVC

I am trying to receive data from an URL with two parameters like this one:
http://localhost:80000/xxx/xxx/tickets/search?codprovincia=28&municipio=110000
No matter the approach, I am always getting a 400 error, but if I access the URL without the two parameters, the controller returns the view correctly (without the parameters, naturally)
This is the code of my controller:
#Controller
#RequestMapping(value = "/xxx" )
public class BuscadorIncidenciasController extends BaseControllerWeb {
#RequestMapping("tickets")
public String tickets(Model model, #RequestParam ("codprovincia") String codprovincia, #RequestParam ("municipio") String municipio, HttpServletRequest request) throws NoAjaxException {
//...
return CONST.JSP_VIEW;
}
...}
Extra info: if I use this URL:
http://localhost:9081/xxx/xxx/tickets/search/28/790000
And this code:
#Controller
#RequestMapping(value = "/xxx" )
public class BuscadorIncidenciasController extends BaseControllerWeb {
#RequestMapping(value = "buscar/{codprovincia}/{municipio}", method = RequestMethod.GET)
public String buscar(#PathVariable Integer codprovincia, #PathVariable Integer municipio ,Model model, HttpServletRequest request) throws NoAjaxException {
//...
return CONST.JSP_VIEW;
}
...}
It gets the parameters correctly. The problem is that I have to use the first URL. I have reviewed similar questions about similar issues, and I have implemented the solutions to those issues, but I get the 400 error regardless what I try (add value="xxx=, required=false, and other suggestions.)
For RequestParam, you need to explicitly add 'name' attribute
#RequestParam(name = "codprovincia"), #RequestParam (name = "municipio")
No need to for HttpServletRequest, unless you have reason
Also, in your 'tickets' method, RequestMapping is not conforming to your URL path.
I think it should be
#RequestMapping("/xxx/tickets/search")
Cheers!

what is use case of #ResponseBody in Spring MVC

what is the usage of #ResponseBody in Spring MVC?
Because Can't I access that without that?
#RequestMapping(value = { "/employees" }, method = RequestMethod.GET)
public #ResponseBody ResponseEntity<JSONObject> employees( #SessionAttribute("emp") Employee emp, Model model ) {
The #ResponseBody annotation tells a controller that the object returned is automatically serialized into JSON and passed back into the HttpResponse object.

DTO has only null with GET request params, but not POST #RequestBody

I'm trying to get my query params in a DTO like in this question but my DTO has always null value.
Is there anything wrong in my code ? I made it as simple as possible.
Queries:
GET http://localhost:8080/api/test?a=azaz => null
POST http://localhost:8080/api/test with {"a":"azaz"} => "azaz"
Controller with a GET and a POST:
#RestController
#RequestMapping(path = {"/api"}, produces = APPLICATION_JSON_VALUE)
public class MyController {
// GET: dto NOT populated from query params "?a=azaz"
#RequestMapping(method = GET, path = "test")
public #ResponseBody String test(TestDto testDto){
return testDto.toString(); // null
}
// POST: dto WELL populated from body json {"a"="azaz"}
#RequestMapping(method = POST, path = "test")
public #ResponseBody String postTest(#RequestBody TestDto testDto){
return testDto.toString(); // "azaz"
}
}
DTO:
public class TestDto {
public String a;
#Override
public String toString() {
return a;
}
}
Thanks !
Full Spring boot sample to illustrate it
The problem is that you are missing setter for the field.
public void setA(String a) {
this.a = a;
}
should fix it.
I'm assuming that you have done required configuration like having Jackson mapper in the class path, consume json attribute, getter and setter in DTO classes etc.
One thing missed here is, in RequestMapping use value attribute instead of path attribute as shown below
#RequestMapping(method = POST, value= "/test", consumes="application/json")
public #ResponseBody String postTest(#RequestBody TestDto testDto){
return testDto.toString();
}
And, make sure that you set content-type="application/json" while sending the request
I think what you are trying to do is not possible. To access the query Parameter you have to use #RequestParam("a"). Then you just get the String. To get your object this way you have to pass json as Parameter. a={"a":"azaz"}
Kind regards

405 error while using POST method in Spring + google app engine

Whenever I try to use method post I am getting 405 error. The get method is working properly. I tried changing the type by using ajax. but it didn't work. Please help
#Controller
public class PaymentController {
#Autowired
private IAccountService accountService;
#RequestMapping(value = "/payment", method = RequestMethod.POST)
public String returnAccountInformation(HttpSession session, Model model) {
String email = (String) session.getAttribute("email");
PlanInfo planInfo = getAccountService().getPlanInfo(email);
PlanInfoBean planInfoBean = new PlanInfoBean();
planInfoBean.setPlanName(planInfo.getPlanName());
planInfoBean.setPlanType(planInfo.getPlanType());
planInfoBean.setFeatures(planInfo.getFeatures());
model.addAttribute(IPaymentConstants.PLANINFO2, planInfoBean);
// System.out.println(session.getAttribute("email"));
return "AccountDetails";
}

Request parameters in spring

I need to take two parameters in my spring controller.
http://mydomain.com/myapp/getDetails?Id=13&subId=431
I have controller which will return Json for this request.
#RequestMapping(value = "/getDetails", method = RequestMethod.GET,params = "id,subId", produces="application/json")
#ResponseBody
public MyBean getsubIds(#RequestParam String id, #RequestParam String subId) {
return MyBean
}
I am getting 400 for when i tried to invoke the URL. Any thoughts on this?
I was able to get it with one parameter.
Try specifying which parameter in the query string should match the parameter in the method like so:
public MyBean getsubIds(#RequestParam("id") String id, #RequestParam("subId") String subId) {
If the code is being compiled without the parameter names, Spring can have trouble figuring out which is which.
As for me it works (by calling: http://www.example.com/getDetails?id=10&subId=15):
#RequestMapping(value = "/getDetails", method = RequestMethod.GET, produces="application/json")
#ResponseBody
public MyBean getsubIds(#RequestParam("id") String id, #RequestParam("subId") String subId) {
return new MyBean();
}
P.S. Assuming you have class MyBean.

Resources