【发布时间】:2018-04-01 22:18:03
【问题描述】:
我有以下代码
@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 并单击 Submit 我调用 @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 或添加额外的@GetMaapping 时,一切正常
任何人都可以解释这一点或我能做些什么以使@PostMapping 按预期工作。
更新:正如下面的 cmets 中提到的 - 我们可以直接在 SpringData 中使用 @PathVariable https://stackoverflow.com/a/39871080/4853910
【问题讨论】:
-
@Arpit 不是真的,正如我提到的,当我将
@GetMapping添加到现有的@PostMapping时它会起作用 -
请注意,如果您为配方使用 Spring Data 存储库,则可以直接注入
@PathVariable Recipe id作为方法参数,它将解析参数->Long->存储库查找。跨度>
标签: java spring spring-boot