gpt4 book ai didi

java - 重定向到同一 Controller 中的 POST 方法

转载 作者:行者123 更新时间:2023-12-02 08:57:07 28 4
gpt4 key购买 nike

我有一个 Spring RestController,并且想要使用 RequestBody 重定向到同一 Controller 中的 POST 方法。欢迎任何解决方案,而不仅仅是重定向。

我的 Controller :

@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";
}

我需要将我的请求从同一 Controller 中的 addCompany 方法重定向到 /postmethod,我愿意使用任何可行的解决方案。

最佳答案

在这里检查: https://www.baeldung.com/spring-redirect-and-forward#redirecting-an-http-post-request

As per HTTP 1.1 protocol reference, status codes 301 (Moved Permanently) and 302 (Found) allow the request method to be changed from POST to GET. The specification also defines the corresponding 307 (Temporary Redirect) and 308 (Permanent Redirect) status codes that don't allow the request method to be changed from POST to 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");
}

请求正文将被传递。这是使用您的代码的示例:

@RestController
@RequestMapping("app")
public class TestController {

@PostMapping("/addCompany")
public ModelAndView addCompany(@RequestBody Company company, HttpServletRequest request) {
System.out.println("First method: " + company.name);
request.setAttribute(
View.RESPONSE_STATUS_ATTRIBUTE, HttpStatus.TEMPORARY_REDIRECT);
return new ModelAndView("redirect:/app/postmethod/");
}

@PostMapping("/postmethod")
public void getData(@RequestBody Company company) {
System.out.println("Redirected: " + company.name);
}

public static class Company {
String name;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}
}
}

当使用 POST 请求到 http://localhost:8080/app/addCompany 时,主体为 {"name": "Test Company"},在输出中我接收下一个:

First method: Test Company
Redirected: Test Company

关于java - 重定向到同一 Controller 中的 POST 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60431441/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com