Button does not execute the Managedbean method

Asked

Viewed 1,691 times

7

When I click the change or delete buttons, Managedbean methods are not executed.

Anyone have any ideas? Some settings are missing on the buttons?

Project: https://github.com/fercosmig/Forum

UsuarioListaAtivos.xhtml

<ui:composition template="/WEB-INF/template/Layout.xhtml"
xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://xmlns.jcp.org/jsf/core"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
xmlns:p="http://primefaces.org/ui"
xmlns:c="http://java.sun.com/jsp/jstl/core">

<f:metadata>
    <f:viewAction action="#{usuarioBean.listaAtivos}" />
</f:metadata>

<ui:define name="titulo">Home .:: Fer Cos Mig ::.</ui:define>
<ui:define name="corpo">

    <div id="centraliza">
        <h1>Lista de usuarios ativos.</h1>
    </div>

    <h:form id="frm1">
        <p:messages showDetail="false" showSummary="true" autoUpdate="true" />
        <p:dataTable id="dtUsuarios" paginator="true" rows="50"
            paginatorPosition="botton" value="#{usuarioBean.usuarios}"
            var="usuarioDaLista">

            <p:column headerText="ID" sortBy="#{usuarioDaLista.id}">
                <h:outputText value="#{usuarioDaLista.id}" />
            </p:column>
            <p:column headerText="Nome" sortBy="#{usuarioDaLista.nome}">
                <h:outputText value="#{usuarioDaLista.nome}" />
            </p:column>
            <p:column headerText="E-mail" sortBy="#{usuarioDaLista.email}">
                <h:outputText value="#{usuarioDaLista.email}" />
            </p:column>
            <p:column headerText="UserName" sortBy="#{usuarioDaLista.username}">
                <h:outputText value="#{usuarioDaLista.username}" />
            </p:column>
            <p:column headerText="Tipo" sortBy="#{usuarioDaLista.tipoUsuario}">
                <h:outputText value="#{usuarioDaLista.tipoUsuario}" />
            </p:column>
            <p:column headerText="Data de cadastro"
                sortBy="#{usuarioDaLista.dataCadastro}">
                <h:outputText value="#{usuarioDaLista.dataCadastro}">
                    <f:convertDateTime pattern="dd/MM/yyyy" />
                </h:outputText>
            </p:column>

            <p:column>

                <h:commandLink action="#{usuarioBean.editar}" value="Editar" />

                <p:commandButton id="btnEdi" icon="ui-icon-pencil"
                    action="#{usuarioBean.editar}" immediate="true">
                    <f:setPropertyActionListener value="#{usuario}"
                        target="#{usuarioBean.usuarioSelecionado}" />
                </p:commandButton>

                <p:commandButton id="btnExc" icon="ui-icon-trash"
                    action="#{usuarioBean.desativar}" immediate="true">
                    <f:setPropertyActionListener value="#{usuario}"
                        target="#{usuarioBean.usuarioSelecionado}" />
                </p:commandButton>

            </p:column>

        </p:dataTable>
    </h:form>

</ui:define>

UsuarioBean.java

/**
 * 
 */
package com.fercosmig.login.controller;

import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.context.FacesContext;
import javax.faces.view.ViewScoped;
import javax.persistence.EntityManager;
import javax.servlet.http.HttpServletRequest;

import com.fercosmig.login.model.Usuario;
import com.fercosmig.login.repository.UsuarioRepository;
import com.fercosmig.util.JpaUtil;

/**
 * @author Fernando Costa Migliorini - [email protected]
 * @since Sep 2, 2015
 */
@ManagedBean
@ViewScoped
public class UsuarioBean {

    private Usuario usuario = new Usuario();
    private List<Usuario> usuarios;
    private Usuario usuarioSelecionado;

    public String editar(){
        System.out.println("@@@==> Entrou no método editar do UsuarioBean. Aqui não entra!");
        return "/UsuarioAlteracao?faces-redirect=true";

    }


    public void desativar() {
        System.out.println("@@@==> Entrou no método desativar do UsuarioBean. Aqui não entra!");

        /*FacesContext context = FacesContext.getCurrentInstance();
        EntityManager em = JpaUtil.getEntityManager();
        UsuarioRepository ur = new UsuarioRepository(em);


        this.usuarioSelecionado = ur.buscaPorId(usuarioSelecionado.getId());

        try {
            ur.desativar(this.usuarioSelecionado);
            context.addMessage(null, new FacesMessage("Usuario desativado com sucesso!"));
        } catch (Exception e) {
            FacesMessage mensagem = new FacesMessage(e.getMessage());
            mensagem.setSeverity(FacesMessage.SEVERITY_ERROR);
            context.addMessage(null, mensagem);
        }*/

    }

    public void listaAtivos() {
        System.out.println("@@@==> Entrou no método listaAtivos do UsuarioBean. Aqui está OK!");
        EntityManager em = JpaUtil.getEntityManager();
        UsuarioRepository ur = new UsuarioRepository(em);

        this.usuarios = ur.listaAtivos();
    }

    public String login() {
        System.out.println("@@@==> Entrou no método login do UsuarioBean. Aqui está OK!");
        FacesContext context = FacesContext.getCurrentInstance();

        Usuario usuarioParaAutenticacao = new Usuario();
        usuarioParaAutenticacao.setUsername(usuario.getUsername());
        usuarioParaAutenticacao.setPassword(usuario.getPassword());

        EntityManager em = JpaUtil.getEntityManager();
        UsuarioRepository ur = new UsuarioRepository(em);
        Usuario usuarioAutenticado = ur.login(usuarioParaAutenticacao);

        if (usuarioAutenticado != null) {

            this.setUsuario(usuarioAutenticado);

            HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest();
            request.getSession().setAttribute("usuario", usuarioAutenticado);

            return "/Home?faces-redirect=true";

        } else {

            FacesMessage mensagem = new FacesMessage("Usuário e/ou senha inválidos!");
            mensagem.setSeverity(FacesMessage.SEVERITY_ERROR);
            context.addMessage(null, mensagem);
            return "/AccessDenied?faces-redirect=true";
        }
    }

    public String logout(){
        System.out.println("@@@==> Entrou no método logout do UsuarioBean. Aqui está OK!");
        FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
        return "/Login?faces-redirect=true";
    }

    /**
     * 
     */
    public UsuarioBean() {
    }

    /**
     * @return the usuario
     */
    public Usuario getUsuario() {
        return usuario;
    }

    /**
     * @param usuario
     *            the usuario to set
     */
    public void setUsuario(Usuario usuario) {
        this.usuario = usuario;
    }

    /**
     * @return the usuarios
     */
    public List<Usuario> getUsuarios() {
        return usuarios;
    }

    /**
     * @param usuarios
     *            the usuarios to set
     */
    public void setUsuarios(List<Usuario> usuarios) {
        this.usuarios = usuarios;
    }

    /**
     * @return the usuarioSelecionado
     */
    public Usuario getUsuarioSelecionado() {
        return usuarioSelecionado;
    }

    /**
     * @param usuarioSelecionado
     *            the usuarioSelecionado to set
     */
    public void setUsuarioSelecionado(Usuario usuarioSelecionado) {
        this.usuarioSelecionado = usuarioSelecionado;
    }

}
  • I don’t know if that’s it, but it wouldn’t be right <f:setPropertyActionListener value="#{usuarioDaLista}"&#xA; target="#{usuarioBean.usuarioSelecionado}" /> instead of #{usuario}?

  • good night utluiz, tried the way you said, but unsuccessfully, does not execute the methods, does not print anything on the console.

  • 2

    Anyway, I think the first step would be to implement what utluiz suggested, and edit your question if the problem persists. I didn’t read the comments and ended up posting the same suggestion of him.

  • Your problem is in calling action or instead of actionListener , would look like this actionListener="#{usuarioBean.desativar}"

  • The import viewScope is wrong, it should use javax.faces.bean.viewscoped and not import javax.faces.view.ViewScoped;, is mixing JSF Beans with CDI Beans.

3 answers

0

  • First do not use "setPropertyActionListener" use the method itself
  • Change the edit signature to public String editar(Usuario usuarioEditar){
  • Another where this "value=#{user}" comes from place in the code

   p:commandButton id="btnEdi" icon="ui-icon-pencil" 
        action="#{usuarioBean.editar(usuarioBean.usuarioSelecionado)}" 
      immediate="true" process="this"

0

Use ajax=false on button and userDaList on setPropertyActionListener like this:

<p:commandButton id="btnEdi" icon="ui-icon-pencil" action="#usuarioBean.editar}" immediate="true" ajax=false>
    <f:setPropertyActionListener value="#{usuarioDaLista}" target="#{usuarioBean.usuarioSelecionado}" />
</p:commandButton>
  • 1

    Thanks guys, I’ll do tests here.

  • when I put the button alone inside the <h:form> works, if I put the button inside a <h:datatable>, <p:datatable> <p:dataList> or <p:datagrid> does not work. I tried to put process="@this", immediate="true", ajax "false" all together, separated.. in all ways.. unsuccessfully. Is there any library missing?

  • Dude, I ran some tests here, it includes several users to test the pagination, a logout button on the menubar, no button works, no page changes, if I try to sort it clears the datatable. I’m sure there’s something missing. or a lot of things!

  • Yes, you will need to put the button in a form. I usually put the whole datatable inside the form. About your project, you should then evaluate from the beginning to see if something has not been forgotten.

-1

Check that in Entity User there is no field marked as @Notnull.

No more @Managedbean will be discontinued in the future. Use the CDI implementation much more robust @Named

Browser other questions tagged

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