Search code examples
javaspring-boothttp-redirectmodelandview

Redirect to an API that has @RequestBody arguments


The below API is called from the UI, as well as it wants to be redirected to, by other APIs.

@RequestMapping(value = "/showAbc", method = RequestMethod.POST)
public ModelAndView showAbc(@RequestBody Abc abcInstance) {
    //doSomething
}

The below API is also called from the UI end, but it fetches an instance of Abc class using a repository call and now wants to call the above API using redirect, and also wants to pass the instance as an argument.

@RequestMapping(value = "/showBcd", method = RequestMethod.POST)
public ModelAndView showBcd(@RequestParam String bcdId){
    Abc abc = abcRepository.findByBcdId(bcdId);
    /* How to pass the instance of Abc, when redirecting to /showAbc */
    return new ModelAndView("redirect:/showAbc");
}

Now, in the above redirect I also want to pass the instance of Abc, when redirecting to /showAbc from /showBcd.


Solution

  • I wouldn't recommend calling one API to another if it's in the same application. This way you are tightly coupling API to API. Either leave the API contract to be called to UI or handle the delegation via plain java service calls.

    @RequestMapping(value = "/showAbc", method = RequestMethod.POST)
    public ModelAndView showAbc(@RequestBody Abc abcInstance) {
        return new ModelAndView("abc",abcService.get());
    }
    
    @RequestMapping(value = "/showBcd", method = RequestMethod.POST)
    public ModelAndView showBcd(@RequestParam String bcdId){
        // You should move this repo call to bcdService.java
        Abc abc = abcRepository.findByBcdId(bcdId);
        //Use a normal service call to get the instance instead of a API call
        return new ModelAndView("abc",abcService.getViaInstance(abc));
    }
    

    However, to have a model passed to the view(Forward the request), you need to add to the model as :

    ModeAndView m = new ModelAndView("forward:/showAbc");
    Abc abc = getAbcInstance();
    m.addObject("abc",abc);
    return m;