Save data via POST on the bank with Vraptor

3

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

  

java.lang.IllegalStateException: Can not call sendRedirect () after the   response 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.CompanyController _ $$ _ jvst52d_1.listAll (CompanyController _ $$ _ jvst52d_1.java)     at   com.vraptor.controller.CompanyController.save (CompanyController.java:42)

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

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 RESTClient Firefox plugin to run the tests:

    
asked by anonymous 10.09.2015 / 20:12

1 answer

3

You can not 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 endless request headers.

The correct one is to define EmpresaController.class , which will create a request with a new Controller :

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

EDIT

Better to use another plugin to test. I use this .

    
10.09.2015 / 20:43