重定向到同一控制器中的POST方法

问题描述 投票:0回答:2

我有一个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,我愿意使用任何可行的解决方案。

java rest spring-mvc redirect
2个回答
1
投票

在这里检查: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");
}

0
投票

我在此页here上找到了很好的解释。

为了防止用户无意间(重新)提交他们不想要的POST事务,或将POST提交到他们不想要的上下文中。

因此,您可以在会话中设置数据,并使用get方法调用后置方法。

© www.soinside.com 2019 - 2024. All rights reserved.