简体   繁体   English

在Rest API应用程序中使用ModelAndView

[英]Use ModelAndView in a Rest API app

I'm writing a web app which only consists of Rest API endpoints. 我正在编写一个仅由Rest API端点组成的Web应用程序。 There is no jsp, nor any UI written in Java provided by the app. 该应用程序没有提供jsp,也没有任何用Java编写的UI。 (I'm planning to write the front end in React in future) (我计划将来在React中编写前端)

Does it make sense to use ModelAndView in my controllers ? 在我的控制器中使用ModelAndView是否有意义? I want to do a redirect to another URL ? 我想重定向到另一个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 如果您的控制器总是要重定向,则可以返回一个String,例如

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. 我认为如果没有视图,则返回ModelAndView是没有意义的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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