Request method 'POST' not supported in Spr

2019-08-31 03:47发布

问题:

This is My form :

<form action="${pageContext.request.contextPath}/admin/editc" method="POST" id="editForm">
    <input type="text" name="username" class="form-control" />
    <input type="text" name="password" class="form-control" />
    <input type="submit" value="submit" >
</form>

This is My controller method:

@RequestMapping(value = "/admin/edit", method = RequestMethod.GET)
public ModelAndView editPage() {

    ModelAndView model = new ModelAndView();
    model.addObject("title", "User edit Form - Database Interaction");
    model.addObject("message", "This page is for ROLE_ADMIN only!");
    model.setViewName("editpage");
    System.out.println("getting edit page");

    return model;

}


@RequestMapping(value = "/admin/editc", method = RequestMethod.POST)
public ModelAndView updateCredentials() {
//      System.out.println("Username= "+username+"  password= "+password);
     ModelAndView model = new ModelAndView();
    model.addObject("title", "Credential Edit Operation");
    model.addObject("message", "You are successfully updated your credentials");
    model.addObject("edited", "TRUE");
    model.setViewName("editpage");
    System.out.println("executed updateCredentials POST method");

    return model;

}

Now the issue is I am getting 405 error in console like below:

org.springframework.web.servlet.PageNotFound handleHttpRequestMethodNotSupported
 WARNING: Request method 'POST' not supported

Can any one please help me resolving this error ?

回答1:

The signature of your java method is wrong, you need to add also what you are expecting from the POST. Have a look in to this guide to correct your code.



回答2:

You first need a GET method to display the form and a POST to submit it.

@RequestMapping(value = "/admin/editc", method = RequestMethod.GET)
public ModelAndView updateCredentials() {
    return new ModelAndView("editPage");
}

@RequestMapping(value = "/admin/editc", method = RequestMethod.POST)
public ModelAndView updateCredentials(@ModelAttribute UserCredentials credentials) {
    someService.save(credentials);
    ...
}