How to change page after inserting object in database?

2

I created a JSF page with a client form, after saving client by pressing the button register. The object persisted in the DB, and consequently I would like you to switch pages by going to index.xhtml or clearing the form fields to continue to register clients.

cadastroCliente.xhtml

<form>
    <!-- inputTexts referentes ao cliente. Aqui-->
    <p:commandButton value="Cadastrar" id="cadastrar" ajax="false" 
        style="margin-top: 25px; margin-bottom:7px;"
        action="#{clienteBean.inserir}">
    </p:commandButton>
</form>

ClientBean.java

public void inserir(){
    dataCadastro = new Date();
    Session session = DAOHibernateUtil.getSessionFactory().getCurrentSession();
    try{
        session.beginTransaction();
        if(!isCpfValido(session)){
            FacesContext.getCurrentInstance().addMessage("cpfmessage", new FacesMessage(FacesMessage.SEVERITY_WARN,"CPF já cadastrado", "este CPF já esta sendo utilizado!"));
        }else{
            Cliente cliente = this;
            session.save(cliente);
            session.getTransaction().commit();
            cliente = new Cliente();
        }
    }catch(RuntimeException e){
        session.getTransaction().rollback();
    }finally{
        if(session.isConnected()){
            session.close();
        }
    }
}

I'm starting now with JSF behaving if my code is wrong I'm grateful for help correcting, but this code is working by persisting in the database correctly.

The problem is like opening another page or clearing the inputtext of the form after clicking the register button.

    
asked by anonymous 09.11.2014 / 20:36

1 answer

4

I suggest you read the official JSF tutorial . > in Java EE, especially in the Navigation Model chapter. of JSF. This is a reasonably complex subject.

To give you a pragmatic answer, your method should return a String with the outcome of the action.

public String inserir() {
   // ...
   return "index";
}

In this case there is implied navigation from view cadastroCliente to view index .

You can also declare explicit browsing rules in configuration files as faces-config.xml :

<navigation-rule>
    <from-view-id>/cadastroCliente.xhtml</from-view-id>
    <navigation-case>
        <from-outcome>success</from-outcome>
        <to-view-id>/index.xhtml</to-view-id>
    </navigation-case>
</navigation-rule>

In this case, the outcome of an action in cadastroCliente.xhtml is success will display the view index .

    
09.11.2014 / 21:09