How in the xhtml commandButton to identify that an error was generated in Dao and keep navigation on the same page?

0

In the xhtml page on a commandButton I call the action confirm () to confirm the recording of an object. The return of this method is a string directing to a new page.

<p:commandButton id="botaoSalvar" value="Confirma" update="msgs" action="#{usuario_MB.confirma()}" ajax="false" process="@form"/>

Method confirms

public String confirma(){

        Grupo grupo = grupoDao.consulta("ROLE_USER");
        List<Grupo> grupos = new ArrayList<>();
        grupos.add(grupo); 
        usuario.setGrupos(grupos);
        usuarioDao.inclusao(usuario);
        return "/Login.xhtml";
    }

In the method included in the user class, treat exceptions.

public void inclusao(Usuario usuario) {


        System.out.println("\n -------- Entrou no Usuario.consulta - antes do EM");
        try {
            entityManager.getTransaction().begin();
            entityManager.persist(usuario);
            entityManager.getTransaction().commit();
            FacesUtil.addInfoMessage("Usuario cadastrado com sucesso!");
        } catch (EntityExistsException e){
            System.out.println("\n -------- Erro ao incluir usuario - ChaveDublicada");
            System.out.println(e.getStackTrace());
            FacesUtil.addErrorMessage("Usuario já cadastrado!");
        } catch (Exception e) {
            System.out.println("\n -------- Erro ao incluir usuario");
            FacesUtil.addErrorMessage("Algo não funcionou! Tente mais tarde.");
            System.out.println(e.getMessage());
            System.out.println(e.getStackTrace());
        }

    }

The question is:

  

As in the xhtml commandButton I identify that an error was generated and   do I keep browsing on the same page?

    
asked by anonymous 04.07.2016 / 15:12

1 answer

1

You only have to "" return your managedBean:

public String confirma(){
    Grupo grupo = grupoDao.consulta("ROLE_USER");
    List<Grupo> grupos = new ArrayList<>();
    try{
        grupos.add(grupo); 
        usuario.setGrupos(grupos);
        usuarioDao.inclusao(usuario);
        return "/Login.xhtml";
    }catch(Exception e){//...}
    return ""; //<- isso faz com que não haja troca de página
}

Note: You should see the exception in your method inclusao()

    
04.07.2016 / 15:20