在Wildfly的JavaEE应用程序中设置CDI时出错

时间:2019-07-08 12:36:55

标签: jpa jsf wildfly cdi

设置了某些类的CDI资源后,我的应用不再构建了。

创建,建模,控制器和服务以提供登录系统。

将生产者添加到实体管理器

EntityManagerProducer.java

https://github.com/rkhleics/wagtailmenus

在src.main.resources.META-INF包中: beans.xml

package br.com.sys.util;

import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.context.RequestScoped;
import javax.enterprise.inject.Disposes;
import javax.enterprise.inject.Produces;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

@ApplicationScoped

public class EntityManagerProducer {
    private EntityManagerFactory factory;
    public EntityManagerProducer() {
        this.factory = Persistence.createEntityManagerFactory(
                "SistemaPU");
    }
    @Produces
    @RequestScoped
    public EntityManager createEntityManager() {
        return factory.createEntityManager();
    }
    public void closeEntityManager(@Disposes EntityManager manager) {
        manager.close();
    }
}

我的模特 Usuario.java

<?xml version="1.0" encoding="UTF-8"?>
<beans
    xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                      http://xmlns.jcp.org/xml/ns/javae/beans_1_1.xsd"
    bean-discovery-mode="all">
</beans>

我的控制器 LoginBean.java

package br.com.sys.model;

import javax.enterprise.context.SessionScoped;
import javax.inject.Named;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import java.io.Serializable;
import java.util.Objects;

@Named
@SessionScoped
@Entity
public class Usuario implements Serializable {
    private static final long serialVersionUID = 7371518231621030644L;

    @Id @GeneratedValue
    private Long id;
    private String usuario;
    private String senha;
    private String nome;
    private Long perfil;
    private String cpf;
    private String email;


    public boolean isLogado() {
        return nome != null;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    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;
    }

    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

    public Long getPerfil() {
        return perfil;
    }

    public void setPerfil(Long perfil) {
        this.perfil = perfil;
    }

    public String getCpf() {
        return cpf;
    }

    public void setCpf(String cpf) {
        this.cpf = cpf;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Usuario usuario = (Usuario) o;
        return Objects.equals(id, usuario.id);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id);
    }
}

使用此服务

Logins.java

package br.com.sys.controller;

import br.com.sys.model.Usuario;
import br.com.sys.repository.Usuarios;
import br.com.sys.service.Logins;
import br.com.ufs.sys.util.JpaUtil;

import javax.faces.application.FacesMessage;
import javax.enterprise.context.RequestScoped;
import javax.faces.context.FacesContext;
import javax.faces.view.ViewScoped;
import javax.inject.Inject;
import javax.inject.Named;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;

@Named
@RequestScoped
public class LoginBean {

    @Inject
    private Logins dologin;

/*    @Inject
    private Usuarios usuarios;
*/
    private Usuario user = new Usuario();
    private String usuario;
    private String password;


    public String login() {
        EntityManager manager = JpaUtil.getEntityManager();
        try {
            this.user = dologin.autenticar(this.usuario);
        }
        catch (Exception e){
            e.printStackTrace();
        }
        finally {
            manager.close();
        }
        FacesContext context = FacesContext.getCurrentInstance();
        if (this.usuario.equals(this.user.getUsuario())
                && this.password.equals(this.user.getSenha())) {

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

        } else {
            FacesMessage mensagem = new FacesMessage(
                    "Usuário/senha inválidos!");
            mensagem.setSeverity(FacesMessage.SEVERITY_ERROR);
            context.addMessage(null, mensagem);
        }
        return null;
    }

    public String logout() {
        FacesContext.getCurrentInstance().getExternalContext()
                .invalidateSession();
        return "/Login?faces-redirect=true";
    }

    public Logins getDologin() {
        return dologin;
    }

    public void setDologin(Logins dologin) {
        this.dologin = dologin;
    }

    public Usuario getUser() {
        return user;
    }

    public void setUser(Usuario user) {
        this.user = user;
    }

    public String getUsuario() {
        return usuario;
    }

    public void setUsuario(String usuario) {
        this.usuario = usuario;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

这个存储库类 Usuarios.java

package br.com.sys.service;

import br.com.sys.model.Usuario;
import br.com.sys.repository.Usuarios;


import javax.inject.Inject;
import java.io.Serializable;

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

    @Inject
    private Usuarios usuarios;

    public void salvar(Usuario usuario) throws NegocioException {
        if (usuario.getUsuario() != null) {
            throw new NegocioException(
                    "Usuario vazio ou já existente");
        }
        this.usuarios.adicionar(usuario);
    }

    public Usuario autenticar(String user) throws NegocioException{
        return usuarios.porUsuario(user);
    }
}

Login.xhtml:

package br.com.sys.repository;

import br.com.sys.model.Usuario;

import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.NoResultException;
import javax.persistence.TypedQuery;
import java.io.Serializable;
import java.util.List;

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

    private EntityManager manager;

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

    public Usuario porUsuario(String usuario) throws NoResultException {
        TypedQuery<Usuario> query = manager.createQuery("SELECT user FROM Usuario user WHERE user.usuario = :parUser",Usuario.class);
        query.setParameter("parUser",usuario);
        return query.getSingleResult();
    }
    public List<Usuario> todas() {
        TypedQuery<Usuario> query = manager.createQuery(
                "from Usuario", Usuario.class);
        return query.getResultList();
    }

    public void adicionar(Usuario usuario) {
        EntityTransaction trx = this.manager.getTransaction();
        trx.begin();
        this.manager.persist(usuario);
        trx.commit();
    }
}

日志输出:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://xmlns.jcp.org/jsf/html"
      xmlns:p="http://primefaces.org/ui">
<h:head>
    <title>Login</title>
    <h:outputStylesheet library="css" name="estilo.css" />
</h:head>
<h:body>
    <div id="login-dialog">
        <h1>Login</h1>
        <h:form id="frm">
            <p:messages/>
            <p:autoUpdate/>
            <h:panelGrid columns="2" styleClass="grid-login">
                <p:outputLabel value="Usuário" for="usuario" />
                <p:inputText id="usuario" size="20"
                             value="#{loginBean.usuario}" />
                <p:outputLabel value="Senha" for="senha" />
                <p:password id="senha" size="20"
                            value="#{loginBean.password}" />
                <p:outputLabel />
                <p:commandButton value="Acessar"
                                 action="#{loginBean.login}" />
            </h:panelGrid>
        </h:form>
    </div>
</h:body>
</html>

0 个答案:

没有答案