[英]Call a Spring Controller from another one
我有由UserController處理的URL /users
和/users/58
。 現在,我想將/users/58/images
重定向到ImageController,以便將所有與Images有關的代碼移動到ImageController。
這是UserController的樣子:
@RequestMapping(method = RequestMethod.GET, value = "/users")
List<User> paginate() { ... }
@RequestMapping(method = RequestMethod.GET, value = "/users/{id}")
List<User> get(Long id) { ... }
@RequestMapping(method = RequestMethod.GET, value = "/users/{id}/images")
List<Image> images(Long userId) {
// What I want to do is something like this
ImageController images = new ImageController();
return images.getByUser(userId);
}
首先,這是一個好的設計嗎? 如果是,如何從一個控制器調用另一個控制器?
您不能從控制器調用另一個控制器,因為前端控制器(Dispatcher Servlet)正在協調所有請求。 根據您的URI請求,將通過匹配Controller / Request Handler進行處理。 因此,您可以從重定向控制器使用URI進行重定向,並在重定向控制器中獲取該URI。示例(處理程序方法不必位於同一控制器中)
重定向控制器中的處理程序
@RequestMapping(method = RequestMethod.GET, value = "/users/{id}/images")
public String getUserId() {
return "redirect:/getUsersPage/{id}";
}
重定向控制器中的處理程序
@Autowired
ImageService imageService;
@RequestMapping(value = "/getUsersPage/{id}", method = RequestMethod.GET)
public String getUsersPage(@PathVariable Long id, Model model) {
return imageService.getByUser(id);;
}
關於設計:如果它是REST服務,並且沒有前端,則您的請求處理程序將返回消息正文,則可以注入服務(例如imageService)並返回從服務獲取的值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.