我有一个Spring RestController,想与RequestBody在同一控制器中重定向到POST方法。欢迎使用任何解决方案,不仅重定向。
MyController:
@RequestMapping(value = "/addCompany", method = RequestMethod.POST)
public String addCompany(@Valid Company company, BindingResult result,
HttpServletRequest request, Model model) throws Exception {
//some logic
//need to pass Company Object as RequestBody
return "redirect:/app/postmethod/";
}
//Method to redirected
@RequestMapping(value = "/postmethod", method = {RequestMethod.POST, RequestMethod.GET})
public String getData( @RequestBody(required=false) Company compnay, HttpServletRequest request, Model model) throws Exception {
//some logic
//required company object
return "htmlpage";
}
我需要在同一控制器中将请求从/postmethod
方法重定向到addCompany
,我愿意使用任何可行的解决方案。
在这里检查:https://www.baeldung.com/spring-redirect-and-forward#redirecting-an-http-post-request
根据HTTP 1.1协议参考,状态代码301(已移动永久)和302(找到)允许更改请求方法从POST到GET。该规范还定义了相应的307(临时重定向)和308(永久重定向)状态代码,不允许将请求方法从POST更改为GET。
@PostMapping("/redirectPostToPost")
public ModelAndView redirectPostToPost(HttpServletRequest request) {
request.setAttribute(
View.RESPONSE_STATUS_ATTRIBUTE, HttpStatus.TEMPORARY_REDIRECT);
return new ModelAndView("redirect:/redirectedPostToPost");
}
@PostMapping("/redirectedPostToPost")
public ModelAndView redirectedPostToPost() {
return new ModelAndView("redirection");
}