javax.faces.Validator.BeanValidator.MESSAGE={1} {0}

Asked

Viewed 366 times

1

I created a form where I have the following Name, Job, Login and Password fields. I’m using the javax.faces.validator.BeanValidator.MESSAGE={1} {0} to returns error message to the user. I know it is working because all fields are being checked by him, but the login field he does not check where I am missing.

Below is the code of my form:

<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:f="http://xmlns.jcp.org/jsf/core"
xmlns:p="http://primefaces.org/ui">

<ui:define name="content">

    <p:tabView style="width:600px;height:370px;margin:auto;">
        <p:tab title="Cadastro de Funcionário">

            <h:form id="form-cadastro">

                <h:panelGrid id="panelGrid-campos-form" columns="2"
                    cellpadding="10">

                    <p:outputLabel value="Nome:" for="inputText-nome" />
                    <p:inputText id="inputText-nome" style="width:300px"
                        value="#{cadastroFuncionarioBean.pessoaModel.nome}"/>

                    <p:outputLabel value="Cargo:" for="inputText-cargo" />
                    <p:inputText id="inputText-cargo" style="width:300px"
                        value="#{cadastroFuncionarioBean.funcionarioModel.cargo}"/>

                    <p:outputLabel value="Login:" for="inputText-login" />
                    <p:inputText id="inputText-login" style="width:300px"
                        value="#{cadastroFuncionarioBean.usuarioModel.nomeUsuario}"/>

                    <p:outputLabel value="Senha:" for="inputText-senha" />
                    <p:inputText id="inputText-senha" style="width:300px"
                        value="#{cadastroFuncionarioBean.usuarioModel.senha}"/>

                    <p:spacer />

                    <p:commandButton value="Salvar" id="commandButton-salvar"
                        icon="ui-icon-disk"
                        actionListener="#{cadastroFuncionarioBean.salvar}"
                        update="panelGrid-campos-form" />

                </h:panelGrid>

                  <p:messages showDetail="false" showSummary="true" autoUpdate="true" />            

            </h:form>

        </p:tab>

        <p:tab title="Upload Xml Pessoa">

            <h:form id="form-upload" enctype="multipart/form-data">

                <h:panelGrid id="panelGrid-upload-xml" columns="2" cellpadding="10">

                    <p:fileUpload value="#{cadastroFuncionarioBean.file}"
                        mode="simple" skinSimple="true" label="Selecionar" />

                    <p:commandButton value="Importar..." ajax="false"
                        actionListener="#{cadastroFuncionarioBean.UploadRegistros}" />

                </h:panelGrid>

            </h:form>
        </p:tab>

    </p:tabView>

</ui:define>

My file Messages.properties

javax.faces.validator.BeanValidator.MESSAGE={1} {0}
javax.validation.constraints.NotNull.message = deve ser informado.
javax.validation.constraints.Size.message = deve ter tamanho entre \ {min} e {max}.
javax.validation.constraints.DecimalMin.message = deve ser maior ou \ igual a {value}.
org.hibernate.validator.constraints.NotEmpty.message = deve ser \ informado.
br.com.mensagens.NumeroDecimal.message = deve ser um número decimal \ positivo.

and my model class with the restrictions:

package br.com.model;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.Size;

import org.hibernate.validator.constraints.NotEmpty;

@Entity 
@Table(name="usuario")
public class UsuarioModel implements Serializable {

    private static final long serialVersionUID = 1L;

@Id
@GeneratedValue
@Column(name="id_usuario")
private Long codigo;

@NotEmpty
@Size(max = 20)
@Column(name="usuario",length = 20, nullable = false)
private String usuario;

@NotEmpty
@Size(max = 10)
@Column(name="senha",length = 10, nullable = false)
private String senha;

public Long getCodigo() {
    return codigo;
}
public void setCodigo(Long codigo) {
    this.codigo = codigo;
}
public String getUsuario() {
    return usuario;
}
public void setUsuario(String usuario) {
    this.usuario = usuario;
}
public String getSenha() {
    return senha;
}
public void setSenha(String senha) {
    this.senha = senha;
}

/* Abaixo hashCode() e equals */
@Override
public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + ((codigo == null) ? 0 : codigo.hashCode());
    return result;
}

@Override
public boolean equals(Object obj) {
    if (this == obj)
        return true;
    if (obj == null)
        return false;
    if (getClass() != obj.getClass())
        return false;
    UsuarioModel other = (UsuarioModel) obj;
    if (codigo == null) {
        if (other.codigo != null)
            return false;
    } else if (!codigo.equals(other.codigo))
        return false;
    return true;
}



}

loginbean class

package br.com.view;

import java.util.Date;

import javax.enterprise.context.RequestScoped;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;

import br.com.amarildo.controller.UsuarioController;
import br.com.amarildo.model.UsuarioModel;
import br.com.amarildo.repository.UsuarioRepository;
import br.com.amarildo.util.NegocioException;

@Named
@RequestScoped
public class LoginBean {
    @Inject
    private UsuarioController usuarioController;

    @Inject
    private UsuarioRepository usuarioRepository;

    private UsuarioModel usuarioModel;
    private String nomeLogin;
    private String numSenha;

public String login() {

    usuarioModel = usuarioRepository.ValidaUsuario(this.nomeLogin,this.numSenha);

    if (usuarioModel != null) {
        this.usuarioController.setNome(this.nomeLogin);
        this.usuarioController.setDataLogin(new Date());
        this.usuarioController.setCodigoId(usuarioModel.getCodigo());
        return "sistema/home?faces-redirect=true";
    } else if ((this.nomeLogin).isEmpty()) {
        NegocioException.MensagemAlerta("Favor informar o login!");
    } else if ((this.numSenha).isEmpty()) {
        NegocioException.MensagemAlerta("Favor informar a senha!");
    } else {
        NegocioException.MensagemErro("Usuário/senha inválidos!");
    }

    return null;
}

public String getNomeLogin() {
    return nomeLogin;
}

public void setNomeLogin(String nomeLogin) {
    this.nomeLogin = nomeLogin;
}

public String getSenha() {
    return numSenha;
}

public void setSenha(String numSenha) {
    this.numSenha = numSenha;
}
    public String Logout(){
        FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
        return "/index.xhtml?faces-redirect=true";
    }

}

class Usuariorepository

package br.com.repository;

import java.io.Serializable;
import java.util.List;

import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;

import br.com.amarildo.model.UsuarioModel;

public class UsuarioRepository implements Serializable {
    private static final long serialVersionUID = 1L;

    private EntityManager manager;

    @Inject
    public UsuarioRepository(EntityManager manager) {
        this.manager = manager;
    }

    public UsuarioModel porId(Long id) {
        return manager.find(UsuarioModel.class, id);
    }

    public List<UsuarioModel> todos() {
        TypedQuery<UsuarioModel> query = manager.createQuery("from UsuarioModel", UsuarioModel.class);
        return query.getResultList();
    }

    public UsuarioModel guardar(UsuarioModel usuario) {
        return this.manager.merge(usuario);
    }

    public void remover(UsuarioModel usuario) {
        this.manager.remove(usuario);
    }

    public UsuarioModel ValidaUsuario(String nomeUsuario,String senha){
        String Jpql = "Select u From UsuarioModel u Where u.nomeusuario = :usuario And u.senha = :senha";
        try {
            //Query que sera executada (Jpql)   
            TypedQuery<UsuarioModel> query = manager.createQuery(Jpql, UsuarioModel.class);
            //Parâmetros da Query
            query.setParameter("usuario", nomeUsuario);
            query.setParameter("senha", senha);
            //Retorna o Usuario se For Localizado
            return query.getSingleResult();
        } catch (Exception e) {
            return null;
        }

    }

}

Work record

    package br.com.amarildo.view;

import java.io.Serializable;
import java.io.IOException;

import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.view.ViewScoped;
import javax.inject.Inject;
import javax.inject.Named;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.primefaces.model.UploadedFile;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import br.com.amarildo.controller.FuncionarioController;
import br.com.amarildo.controller.PessoaController;
import br.com.amarildo.controller.UsuarioController;
import br.com.amarildo.model.FuncionarioModel;
import br.com.amarildo.model.PessoaModel;
import br.com.amarildo.model.UsuarioModel;
import br.com.amarildo.util.NegocioException;

@Named
@ViewScoped
public class CadastroFuncionarioBean implements Serializable {
    private static final long serialVersionUID = 1L;

    @Inject
    private FuncionarioController funcionarioController;

    @Inject
    private PessoaController pessoaController;

    @Inject
    private UsuarioController usuarioController;

    @Inject
    private FuncionarioModel funcionarioModel;

    @Inject
    private PessoaModel pessoaModel;

    @Inject
    private UsuarioModel usuarioModel;

    private UploadedFile file;

    boolean faz = false;

    @PostConstruct
    public void inicializar() {
        // Verifica se as entity PessoaModel,FuncionárioModel e UsuarioModel não está retornando null
        System.out.println("Passou Aqui no pessoaModel      !!! "+pessoaModel == null);
        System.out.println("Passou Aqui no funcionarioModel !!! "+funcionarioModel == null );
        System.out.println("Passou Aqui no UsuarioModel     !!! "+usuarioModel == null );
    }

    //Salva Registro via Input
    public void salvar() {

        FacesContext context = FacesContext.getCurrentInstance();

        try {

            //Informa que o Cadastro foi Via Input e/ou Via Xml
            if (pessoaModel.getOrigemCadastro() == "X"){
                faz = false;
                pessoaModel.getOrigemCadastro();
            }else{
                faz = true; 
                pessoaModel.setOrigemCadastro("I");
            }

            //Salvar Insert Dados de Usuário na Tabela Usuário e o Id do Objeto Usuario para Tabela Funcionario Id_Usuario
            usuarioModel = this.usuarioController.salvar(this.usuarioModel);
            this.funcionarioModel.setUsuarioModel(usuarioModel);
            this.usuarioModel = new UsuarioModel();

            //Salvar Insert Dados de Funcionário na Tabela Funcionário e o Id do Objeto Funcionário para Tabela Pessoa Id_Funcionario
            funcionarioModel = this.funcionarioController.salvar(this.funcionarioModel);
            this.pessoaModel.setFuncionarioModel(funcionarioModel);
            this.funcionarioModel = new FuncionarioModel();

            //Salvar Insert Id do Objeto Usuario que está cadastrando o Funcionario para Tabela Pessoa Id_Usuario
            usuarioModel = this.usuarioController.addId(this.usuarioController.getCodigoId());
            this.pessoaModel.setUsuarioModel(usuarioModel);         

            //Salvar Insert Dados Tabela Pessoa 
            this.pessoaController.salvar(this.pessoaModel);
            this.pessoaModel = new PessoaModel();

            if (faz){
              context.addMessage(null, new FacesMessage("Funcionario salvo com sucesso!"));
            }

        } catch (NegocioException e) {
            FacesMessage mensagem = new FacesMessage(e.getMessage());
            mensagem.setSeverity(FacesMessage.SEVERITY_ERROR);
            context.addMessage(null, mensagem);
        }

    }


    // Salva Registro via Upload
    public void UploadRegistros() throws NegocioException {

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

        try {

            if (this.file.getFileName().equals("")) {
                NegocioException.MensagemAtencao("Nenhum arquivo selecionado!");
                return;
            }

            DocumentBuilder builder = factory.newDocumentBuilder();

            Document doc = builder.parse(this.file.getInputstream());

            Element element = doc.getDocumentElement();

            NodeList nodes = element.getChildNodes();

            for (int i = 0; i < nodes.getLength(); i++) {

                Node node = nodes.item(i);

                if (node.getNodeType() == Node.ELEMENT_NODE) {

                    Element elementDados = (Element) node;

                    // Pegando os Elementos da entidade em Xml
                    String nome  = elementDados.getElementsByTagName("nome").item(0).getChildNodes().item(0).getNodeValue();
                    String cargo = elementDados.getElementsByTagName("cargo").item(0).getChildNodes().item(0).getNodeValue();
                    String usuario = elementDados.getElementsByTagName("usuario").item(0).getChildNodes().item(0).getNodeValue();
                    String senha = elementDados.getElementsByTagName("senha").item(0).getChildNodes().item(0).getNodeValue();

                    // Informa que o Cadastro foi Upload
                    pessoaModel.setOrigemCadastro("X");

                    // Seta os dados dos Elementos em Xml
                    pessoaModel.setNome(nome);
                    funcionarioModel.setCargo(cargo);
                    usuarioModel.setNomeUsuario(usuario);
                    usuarioModel.setSenha(senha);

                    // Executa o metodo Salvar desenvolvido Acima.
                    salvar();

                }
            }

            NegocioException.MensagemInformacao("Registros cadastrados com sucesso!");

        } catch (ParserConfigurationException e) {

            e.printStackTrace();

        } catch (SAXException e) {

            e.printStackTrace();

        } catch (IOException e) {

            e.printStackTrace();
        }

    }

    public FuncionarioModel getFuncionarioModel() {
        return funcionarioModel;
    }

    public void setFuncionarioModel(FuncionarioModel funcionarioModel) {
        this.funcionarioModel = funcionarioModel;
    }

    public PessoaModel getPessoaModel() {
        return pessoaModel;
    }

    public void setPessoaModel(PessoaModel pessoaModel) {
        this.pessoaModel = pessoaModel;
    }

    public UsuarioModel getUsuarioModel() {
        return usuarioModel;
    }

    public void setUsuarioModel(UsuarioModel usuarioModel) {
        this.usuarioModel = usuarioModel;
    }

    public UploadedFile getFile() {
        return file;
    }

    public void setFile(UploadedFile file) {
        this.file = file;
    }

}

good is there if anyone knows what my mistake is and who can help me.

follows below the image for better understanding.teste

Thanks for the attention of all problem was solved I changed the name of my property user name to user in my user class I don’t know why else in my el it appeared Username with the capital U which caused this error since it should be exactly like my good model class I changed and solved.

Grateful to all

  • What value is entered in the login you submit and validation is not done?

  • Thank you, Giuliana, for answering. yes there is a login class where I do the validation , I’m finding that somehow the value I’m typing in the login and password to access the system, is returned to the login and password registration , good I will post the password validation code and registration if you can help me I am very grateful.

  • When adding code, please format it for better reading of it. Just select it and click on {}

  • Notice that on your screen the name is nomeUsuario and in your bean is nomeusuario. That’s probably it, right.

  • Thank you Douglas, however I did as you recommended, I changed the name of the property nameUsuario to nameLogin in the Loginbean class and the Usuariomodel class got the property nameUsuario and yet the error persists.

  • Update the codes in question.

  • A quick test was to change the name on the page to nomeusuario. You built your project again ? Put a breakpoint on your model class set and see if it goes there.

  • i already did the test I tried to change the name to user name on the page but it does not run even because when I use the shortcut key Ctrl more space to call my property that appears is userName which is very strange since in my model class is minuscule user name

Show 3 more comments
No answers

Browser other questions tagged

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