简体   繁体   中英

Use ModelAndView in a Rest API app

I'm writing a web app which only consists of Rest API endpoints. There is no jsp, nor any UI written in Java provided by the app. (I'm planning to write the front end in React in future)

Does it make sense to use ModelAndView in my controllers ? I want to do a redirect to another URL ? I see sample codes similar to the following code:

@Controller
@RequestMapping("/")
public class RedirectController {

    @GetMapping("/redirectWithRedirectPrefix")
    public ModelAndView redirectWithUsingRedirectPrefix(ModelMap model) {
        model.addAttribute("attribute", "redirectWithRedirectPrefix");
        return new ModelAndView("redirect:/redirectedUrl", model);
    }
}

If your controller is always going to redirect, you can just return a String eg

return "redirect:/redirectedUrl";

Otherwise, you can return a response entity:

final HttpHeaders headers = new HttpHeaders();
headers.add("Location", "/redirectedUrl");    
return new ResponseEntity<Foo>(headers, HttpStatus.FOUND);

I don't think it makes sense to return a ModelAndView if there is no view.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM