0

I am trying to retrieve some JSON data in my javascript by making a call to the controller. The controller returns a MappingJacksonJsonView ModelandView, but the .getJSON is always reporting a 404 at .../handhygiene.json.

Is there a problem with the way I am returning the ModelandView from the controller?

Controller

@RequestMapping(value = "/{room}/handhygiene.json", method = RequestMethod.GET)
public ModelAndView getHandHygienePageAsync(
    @PathVariable(value = "room") String roomCode) {
ModelAndView mav = new ModelAndView(new MappingJacksonJsonView());
mav.getModelMap().addAttribute(blahblahblah); //adds some attributes
...

return mav;
}

Javascript

var currentURL = window.location;
$.getJSON(currentURL + ".json",
    function(data) {
    ... //does stuff with data
}
Takkun
  • 6,131
  • 16
  • 52
  • 69
  • HTTP 404 is ... not found. – Brian Roach Feb 23 '13 at 20:04
  • The .getJSON call is successfully reaching the controller, which returns a modelandview. The question I have is why is the returned modelandview object resulting in a 404? (It reaches the controller but not the function(data){} part of the javascript.) – Takkun Feb 23 '13 at 20:06

1 Answers1

1

If you're trying to get only an JSON object from Ajax request, you need to add @ResponseBody to your method, and make you result object as return from your method.

The @ResponseBody tells to Spring that he need to serialize your object to return to the client as content-type. By default, Spring uses JSON Serialization. ModelAndView will try to return an .JSP page. Maybe you don't have this jsp page on your resources so, the server return 404 error.

I Think this code should work for you:

@RequestMapping(value = "/{room}/handhygiene.json", method = RequestMethod.GET)
public @ResponseBody Room getHandHygienePageAsync(@PathVariable(value = "room") String roomCode) {
    Room room = myService.findRoomByRoomCode(roomCode);
    return room;
}

I'm assuming you're using the Room as your result object, but it may be another object or ArrayList, for example.

You cant take a look here for Spring example, and here for example and configuration.

Community
  • 1
  • 1
Deividi Cavarzan
  • 10,034
  • 13
  • 66
  • 80