使用 java spring 中的 Post-Redirect-Get 模式转换 Post 请求

jay*_*g22 4 java spring spring-mvc

我想使用 post/redirect/get 模式转换 post 请求,以防止“为 HTTP 路径映射的模糊处理程序方法”错误。有关详细信息,请参阅此问题

这是初始代码:

@Controller
@RequestMapping("/bus/topologie")
public class TopologieController {
    private static final String VIEW_TOPOLOGIE = "topologie";

    @RequestMapping(method = RequestMethod.POST, params = { "genererCle" })
    public String genererCle(final Topologie topologie, final Model model)
        throws IOException {
        cadreService.genererCle(topologie);
        return VIEW_TOPOLOGIE;
    }
Run Code Online (Sandbox Code Playgroud)

我真的不明白如何使用 PRG 模式重新编码。即使我认为我理解基本概念。

per*_*nio 6

您需要添加另一个可以处理相同 url 映射的 GET 请求的方法。因此,在您的 POST 方法中,您只需进行重定向,而在您的 GET 方法中,您可以完成所有业务流程。

@Controller
@RequestMapping("/bus/topologie")
public class TopologieController {
    private static final String VIEW_TOPOLOGIE = "topologie";

    @RequestMapping(method = RequestMethod.POST, params = { "genererCle" })
    public String genererClePost(final Topologie topologie, final RedirectAttributes redirectAttributes, @RequestParam("genererCle") final String genererCle, final Model model)
        throws IOException {
        redirectAttributes.addAttribute("genererCle", genererCle);
        return "redirect:/bus/topologie";
    }

    @RequestMapping(method = RequestMethod.GET, params = { "genererCle" })
    public String genererCleGet(final Topologie topologie, final Model model)
        throws IOException {
        cadreService.genererCle(topologie);
        return VIEW_TOPOLOGIE;
    }
Run Code Online (Sandbox Code Playgroud)