Save data through POST in the database with Vraptor

Asked

Viewed 377 times

3

I have two methods in my Controller, one that lists all database data and a method to save data in the database. I can already list all data when accessing URI but when I try to save from that mistake:

java.lang.Illegalstateexception: Cannot call sendRedirect() after the Sponse has been Committed at org.apache.Catalina.connector.Responsefacade.sendRedirect(Responsefacade.java:494) at javax.servlet.http.HttpServletResponseWrapper.sendRedirect(Httpservletresponsewrapper.java:138) at br.com.Caelum.vraptor.http.VRaptorResponse.sendRedirect(Vraptorresponse.java:48) at br.com.Caelum.vraptor.view.Defaultlogicresult$2.Intercept(Defaultlogicresult.java:151) at br.com.Caelum.vraptor.proxy.Javassistproxifier$Methodinvocationadapter.invoke(Javassistproxifier.java:106) at com.vraptor.controller.Empresacontroller_$$_jvst52d_1.listAll(Empresacontroller_$$_jvst52d_1.java) at com.vraptor.controller.EmpresaController.save(Companyntroller.java:42)

What is the cause of this error and how can I solve it?

NOTE: when I test the POST it tries to do the insertion in the database, but only the primary key that is auto increment is saved.


Controller:

@Controller
@Path("/empresa")
public class EmpresaController {

    @Inject
    private Result result;
    @Inject
    private EmpresaDAO empresaDAO;

    @Get
    @Path("/list")
    public void listAll() {
        result.use(Results.json())
        .withoutRoot()
        .from(empresaDAO.listar())
        .serialize();
    }

    @Post
    @Path(value = { "/", "" })
    @Consumes(value = "application/json", options = WithoutRoot.class)
    public void salvar(Empresa empresa) {
        empresaDAO.salvar(empresa);
        result.redirectTo(this).listAll(); // Essa é a linha 42 que está lançando a exception
    }

}

DAO:

public void salvar(Empresa empresa) {
        Session sessao = HibernateUtil.getSessionFactory().openSession();
        Transaction transacao = null;
        try {
            transacao = sessao.beginTransaction();
            sessao.save(empresa);
            transacao.commit();

        } catch (RuntimeException ex) {
            ex.printStackTrace();
            throw ex;
        } finally {
            sessao.close();

        }
    }

I’m using the add-on RESTClient from Firefox to do the tests:

inserir a descrição da imagem aqui

1 answer

3


You can’t do this:

result.redirectTo(this).listAll()

The life cycle of a Controller does not allow you to redirect another request to it. It could cause loops infinite of request headers.

It is right to define EmpresaController.class, that will create a request with a Controller new:

result.redirectTo(EmpresaController.class).listAll()

EDIT

Better use another plugin to test. I use this.

  • 1

    Thanks for the help @Gypsy.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.