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

Asked

Viewed 19 times

0

On the xhtml page in a commandButton call the action confirms() to confirm the recording of an object. The return of this method is a string pointing 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 class User I treat the 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 doubt is as follows:

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

1 answer

1


Just return "" in 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: Glance at Exception in your method inclusao()

Browser other questions tagged

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