Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Request method 'GET' not supported in Spring Boot Controller

I have the following code

@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";
}}

Now when i go to http://localhost:8080/recipe/2/update and click on Submit I call the @PostMapping method which upon updating redirects me to return "redirect:/recipe/" + savedCommand.getId() + "/show";

But then i get this error on the console

Resolved exception caused by Handler execution: org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'GET' not supported

and this on the web

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

When i change the @PostMapping to @RequestMapping or add additional @GetMaapping everything works

Can any one explain this or what can i do so that @PostMapping works as expected.

Possible Reason sample

UPDATE: as mentioned in the comments below - we can directly use @PathVariable in SpringData https://stackoverflow.com/a/39871080/4853910

like image 980
RangerReturn Avatar asked Oct 20 '17 17:10

RangerReturn


1 Answers

I guess you have to change the FORM in the HTML so that it uses POST on submit, not GET: Do it this way

<form method="post" ...>

At least the screenshot seems to show the submit request from the browser after submitting the HTML FORM, and it shows there that it is a GET request (with all form fields as request parameters).

So spring ist right: the URL ("/recipe/?id=2&description=Spicy...") only matches the Mapping of saveAndUpdate(), and for this method you only annotated "POST", hence: there is no matching for GET on "/recipe/?id=2&description=Spicy..." in your Controller at all.

Can you post here the HTML snippet with the <FORM>...</FORM> part?

like image 184
Oliver Erdmann Avatar answered Oct 12 '22 23:10

Oliver Erdmann