Arian
Arian

Reputation: 7719

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);
    }
}

Upvotes: 0

Views: 876

Answers (1)

hoipolloi
hoipolloi

Reputation: 8044

If your controller is always going to redirect, you can just return a String e.g.

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.

Upvotes: 1

Related Questions