we have recently started migrating our web application from spring to spring boot 2.4.5. In spring we were able to send ModelAndView as a result from spring controller in Ajax call from UI, but after migrating to spring boot 2.4.5 we are not able to return ModelAndView in ajax call, getting 404 HTTP error.

Can anyone please help me with this, I have missed something during migration?

Thanks

sample code, which was working fine with spring but breaking in spring boot:

public ModelAndView saveData(HttpServletRequest request, @RequestParam final Map<String, String> map) { 
ModalAndView mav = new ModelAndView();
modelAndView.addObject("status"), "IS_WORKING");
return mav;
}

If i update the above code with below, then the ajax call is working fine witn spring boot:

public @ResponseBody ModelMap saveData(HttpServletRequest request, @RequestParam final Map<String, String> map) 
{
        ModelMap modelMap = new ModelMap();
       modelMap .addAttribute("status"), "IS_WORKING");
       return modelMap ;
}
2

There are 2 best solutions below

1
S. Anushan On

To return only data to front end then use Modelmap. The ModelAndView will used for return values and view together at the same time by controller.

1
Wim Deblauwe On

I cannot tell you why it worked like it did in older Spring versions, but the best way forward will be to use the framework as intended:

  1. Use @RestController instead of @Controller. If you want to build a REST API with Spring, that is the best since there would be no need to add @ResponseBody on each method in your controller. @Controller is used if you want to use a templating engine like Thymeleaf for doing Server Side Rendering of HTML.
  2. You can return any Java object and it is serialized to JSON automatically (using Jackson under the hood). If you want to return ad-hoc data without creating a dedicated response DTO, then just return a java.util.Map instance:
Map<String,Object> response = new HashMap<>();
response.put("status", "IS_WORKING");
return response;