【问题标题】:Request method 'GET' not supported in Spring Boot ControllerSpring Boot Controller 不支持请求方法“GET”
【发布时间】: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


【解决方案1】:

我猜你必须更改 HTML 中的 FORM,以便它在提交时使用 POST,而不是 GET:这样做

<form method="post" ...>

至少屏幕截图似乎显示了提交 HTML FORM 后来自浏览器的提交请求, 它在那里显示它是一个 GET 请求(所有表单字段都作为请求参数)。

所以春天是对的:URL ("/recipe/?id=2&description=Spicy...") 只匹配 saveAndUpdate() 的映射,并且对于这个方法,你只注释了“POST”,因此:有在你的控制器中,“/recipe/?id=2&description=Spicy...”上的 GET 完全没有匹配。

你能把 HTML sn-p 用 <FORM>...</FORM> 部分?

【讨论】:

  • 谢谢 - 我添加了该方法并且它有效 :) 我现在知道为什么添加 @GetMapping 有效!
猜你喜欢
  • 2016-07-29
  • 2018-06-20
  • 2017-10-21
  • 2018-05-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-12
  • 2018-06-03
相关资源
最近更新 更多