我有以下代码
@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
@GetMapping
添加到现有的@PostMapping
时它可以工作。 - RangerReturn@PathVariable Recipe id
注入到方法参数中,它会自动解析参数->Long->存储库查找。 - chrylis -cautiouslyoptimistic-