有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

在JavaSpring中使用PostRedirectGet模式转换Post请求

我想使用post/redirect/get模式转换post请求,以防止出现“为HTTP路径映射的不明确处理程序方法”错误。详情见This question

以下是初始代码:

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

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


共 (1) 个答案

  1. # 1 楼答案

    您需要添加另一个方法来处理相同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;
        }