How to use @Delete annotation in Vraptor + AJAX?

4

In my Vraptor project I'm trying to delete a record from a list without the page being reloaded. From the book I'm following, AJAX is used so that the removed record "adds" without the whole page being loaded. The error below occurs when I try to use the @Delete annotation of vraptor.

HTTP Status 405 -

type: Status report

description: The specified HTTP method is not allowed for the requested resource.

My controller:

@Controller
@Path("/pessoa")
public class PessoaController {
[...]

@Delete("/remove/{codPessoa}")
public void remove(Long codPessoa) {
Pessoa pessoaEncontrada = repository.findById(codPessoa, 1);
    if (pessoaEncontrada != null) {
       repository.delete(pessoaEncontrada);
       result.nothing();
    } else
       result.notFound();
}}

On the JSP page:

<script src="${pageContext.request.contextPath}/js/jquery-2.1.4.min.js"></script>
<script>
    $("#pessoas.remove").on("click", function(event) {
        event.preventDefault();
        var pessoa = $(this).closest(".pessoa");
    });
    $.ajax({
        url : $(this).attr("href"),
        type : "POST",
        data : {_method : "DELETE"}
    }).done(function(data, textStatus, jqXHR) {
        pessoa.fadeOut();
    }).fail(function(jqXHR, textStatus, errorThrown) {
        alert("Cliente não foi alterado! " + errorThrown);
    });

[...]

<ul id=pessoas>
    <c:forEach items="${pessoaList}" var="pessoa">
        <li class="pessoa">${pessoa.codPessoa}-${pessoa.nomeFantasia}
            <a href="${linkTo[PessoaController].edita(pessoa.codPessoa, pessoa.codEmpresa)}"> -Editar</a> 
            <a class="remove" href="${linkTo[PessoaController].remove(pessoa.codPessoa)}"> -Remover</a>
        </li>
    </c:forEach>
</ul>
    
asked by anonymous 11.05.2015 / 22:05

2 answers

1

The problem is that you are trying to make a POST for a resource that only accepts DELETE , the solution is easy, you only need to correctly indicate which html method you want to use in the request:

$.ajax({
    url : $(this).attr("href"),
    method : "DELETE"
})

If you are using a jQuery version prior to 1.9.0, instead of method use type itself. Any questions about the attributes of the ajax method, check the documentation .

    
12.05.2015 / 04:49
1

I made it work. But not using @Delete. In fact, attribute "_method: 'DELETE'" is a parameter that passed to VRaptor (according to what I read). Solution: Replace @Delete with @Path in method and deletion was performed. The error I was making is that in my script (js), $ .ajax was outside the function , and the # people.remove > should have a space between "#people" and ".remove" ( "# people .remove" ). By changing these structures the implementation worked out.

    
12.05.2015 / 22:14