我有由 UserController 处理的 URL /users
和 /users/58
。
现在,我想将 /users/58/images
重定向到 ImageController,以便将所有与图像相关的代码移动到 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);
}
首先,这是一个好的设计吗?如果是的话,我如何从一个 Controller 调用另一个 Controller ?
最佳答案
您无法从 Controller 调用另一个 Controller ,因为前端 Controller (Dispatcher Servlet)正在协调所有请求。根据您的 URI 请求将通过匹配的 Controller /请求处理程序进行处理。因此,您可以使用重定向 Controller 中的 URI 进行重定向,并在重定向 Controller 中获取该 URI。示例(处理程序方法不必位于同一 Controller 中)
重定向 Controller 中的处理程序
@RequestMapping(method = RequestMethod.GET, value = "/users/{id}/images")
public String getUserId() {
return "redirect:/getUsersPage/{id}";
}
重定向 Controller 中的处理程序
@Autowired
ImageService imageService;
@RequestMapping(value = "/getUsersPage/{id}", method = RequestMethod.GET)
public String getUsersPage(@PathVariable Long id, Model model) {
return imageService.getByUser(id);;
}
关于设计:如果它是 REST 服务并且没有前端,因此您的请求处理程序返回消息正文,您可以注入(inject)服务(例如 imageService)并返回从服务获取的值。
关于java - 从另一个 Spring Controller 调用 Spring Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45038144/