Spring Boot 控制器中不支持请求方法“GET”。

4

我有以下代码

@Controller
@RequestMapping("/recipe")
public class RecipeController {
private IRecipeService recipeService;

@Autowired
public RecipeController(IRecipeService recipeService) {
    this.recipeService = recipeService;
}

@GetMapping("/{id}/show")
public String showById(@PathVariable String id, Model model) {

    model.addAttribute("recipe", recipeService.findById(Long.valueOf(id)));

    return "recipe/show";
}
@GetMapping("/{id}/update")
    public String updateRecipe(@PathVariable String id, Model model) {
        model.addAttribute("recipe", recipeService.findCommandById(Long.valueOf(id)));

    return "recipe/recipeform";
}

@PostMapping("/")
public String saveOrUpdate(@ModelAttribute RecipeCommand command) {
    RecipeCommand savedCommand = recipeService.saveRecipeCommand(command);

    return "redirect:/recipe/" + savedCommand.getId() + "/show";
}}

现在当我访问 http://localhost:8080/recipe/2/update 并点击 提交 按钮时,会调用 @PostMapping 方法,该方法会在更新后重定向到 return "redirect:/recipe/" + savedCommand.getId() + "/show";。但是,然后我在控制台上收到了这个错误信息。
Resolved exception caused by Handler execution: org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'GET' not supported

并且这在网络上

There was an unexpected error (type=Method Not Allowed, status=405). Request method 'GET' not supported

当我将 @PostMapping 更改为 @RequestMapping 或添加额外的 @GetMapping 时,一切都正常工作。

有人可以解释一下这是什么原因,或者我该怎么做才能使 @PostMapping 正常工作。

可能的原因 示例

更新:如下评论所述 - 我们可以直接在 SpringData 中使用 @PathVariable https://stackoverflow.com/a/39871080/4853910


可能是 Springboot Request method 'POST' not supported 的重复问题。 - Arpit Aggarwal
@Arpit 不是很对,正如我所提到的,当我将 @GetMapping 添加到现有的 @PostMapping 时它可以工作。 - RangerReturn
请注意,如果您正在使用Spring Data存储库来管理您的食谱,您可以直接将@PathVariable Recipe id注入到方法参数中,它会自动解析参数->Long->存储库查找。 - chrylis -cautiouslyoptimistic-
1个回答

3
我猜您需要更改HTML中的FORM,以便在提交时使用POST而不是GET:请按照以下方式进行更改: <form method="post" ...> 至少截图显示浏览器提交HTML表单后的提交请求, 并且它显示它是一个GET请求(所有表单字段都作为请求参数)。
所以Spring是正确的:URL(“/recipe/?id=2&description=Spicy…”)仅匹配saveAndUpdate()的映射, 对于此方法,您只注释了“POST”,因此:在您的控制器中根本没有匹配“/recipe/?id=2&description=Spicy…”的GET。
您能否在此处发布带有<FORM>...</FORM>部分的HTML片段?

谢谢 - 我添加了这个方法,它运行成功了 :) 现在我明白为什么加上 @GetMapping 能够奏效了! - RangerReturn

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接