簡體   English   中英

Spring Boot Controller不支持請求方法'GET'

[英]Request method 'GET' not supported in Spring Boot Controller

我有以下代碼

@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或添加額外的@GetMaapping時,一切正常

任何人都可以解釋這個或我能做什么,以便@PostMapping按預期工作。

可能的原因 樣品

更新:如下面的評論中所述 - 我們可以在SpringData中直接使用@PathVariable https://stackoverflow.com/a/39871080/4853910

我想你必須改變HTML中的FORM,以便它在提交時使用POST,而不是GET:這樣做

<form method="post" ...>

至少屏幕截圖似乎在提交HTML FORM后顯示來自瀏覽器的提交請求,並且它顯示它是GET請求(所有表單字段作為請求參數)。

所以spring是正確的:URL(“/ recipe /?id = 2&description = Spicy ...”)只匹配saveAndUpdate()的Mapping,對於這個方法,你只注釋了“POST”,因此:沒有匹配的在你的控制器中獲取“/ recipe /?id = 2&description = Spicy ...”。

你能在這里發布帶有<FORM>...</FORM>部分的HTML片段嗎?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM