简体   繁体   中英

Controller for delete request does not work

I'm really getting started with controllers for my small application, and i have this for now:

@RequestMapping("/users/{id}")
public ModelAndView showMemeber(@PathVariable Integer id) {

    ModelAndView mav = new ModelAndView("user/show");

    mav.addObject("title", "Show User");
    mav.addObject("user", userService.findById(id));
    return mav;

}

@RequestMapping(value="/users/{id}", method=RequestMethod.DELETE)
public String deleteMemeber(@PathVariable Integer id) {

    userService.delete(id);

    return "redirect:users";

}

the first one, is working properly, but the second doesn't, i have the following view for the first controller:

<div class="panel-heading">Personal information</div>
<div class="panel-body">

  <form>

    ...

    <button type="submit" class="btn btn-danger" onclick="return confirm('Are you sure you want to delete {{ user.username }}?')"><span class="glyphicon glyphicon-remove"></span> Delete</button>
  </form> 
</div>

like you see, i have two buttons here, one for edit the object and one for delete it. Once deleted it, must redirect to https://<my domain>/users .

The problem is, when i click on Delete it just refresh the page and the object persist on the database, what is wrong here?

  • I try send a DELETE request like curl -X "DELETE" http://localhost:8080/my-app/users/18 but this didn't work.
  • I try another alternative using jQuery's ajax-method (but the same error persist):

     $.ajax({ url: '/users/' + someUserId, type: 'DELETE', success: function(result) { // Do something with the result } }); 

You have to use ajax to send a DELETE from the web page. The form tag itself only supports POST or GET. In your submit-Handler you have to suppress the default behaviour of the submit button, ie the submit of the form via GET or POST ( event.preventDefault() ):

$("form").submit(function (event) {
        event.preventDefault();

        $.ajax({
                url: '/users/' + someUserId,
                type: 'DELETE',
                success: function(result) {
                        // Do something with the result
                }
        });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM