Projeto com JSF, Login, Patern, Filter, CRUD, Deposito, Conta Corrrente usando Oracle

O JSF é uma especificação JAVA baseada no modelo MVC (Model-View-Control) para aplicações WEB. É assim substituindo o antigo padrão JSP /Servelet. Junto do JSF sugiram vários framework para a camada de View. Nesse exemplo foi utilizado o Primefaces 4.0 e o acesso ao banco de dados é feito com Oracle.

As libs do Projeto são : JSF 2.0 , Primefaces 4.0 , Oracle necessárias são:

activation.jar asm-attrs.jar c3p0-0.9.0.jar
commons-codec-1.3.jar commons-el-1.0.jar commons-lang-2.1.jar
dom4j-1.6.1.jar hibernate-commons-annotations.jar javaee.jar
jstl.jar ojdbc14-10.2.0.3.jar primefaces-4.0.jar
all-themes-1.0.10.jar asm.jar cglib-2.1.3.jar
commons-collections-3.2.1.jar commons-email-1.2.jar commons-logging-1.1.1.jar
ejb3-persistence.jar hibernate3.jar javax.faces-2.0.11.jar
jta.jar oro-2.0.8.jar standard.jar
antlr-2.7.6.jar bean-validator.jar commons-beanutils-1.8.0.jar
commons-digester-2.0.jar commons-fileupload-1.0.jar commons-validator.jar
hibernate-annotations.jar jakarta-oro.jar jstl-1.1.0.jar
log4j-1.2.15.jar primefaces-4.0-sources.jar

Classe Usuario:

package entity;

import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class Usuario implements Serializable {
	private static final long serialVersionUID = 1L;
	@Id
	private Integer codigo;
	@Column(length=35)
	private String nome;
	@Column(length=35, unique=true)
	private String email;
	@Column(length=100)
	private String senha;
	@Column
	private Double saldo=0.;


	public Usuario() {
		// TODO Auto-generated constructor stub
	}

	public Usuario(Integer codigo, String nome, String email, String senha, Double saldo) {
		super();
		this.codigo = codigo;
		this.nome = nome;
		this.email = email;
		this.senha = senha;
		this.saldo = saldo;
	}
	
		@Override
	public String toString() {
		return "Usuario [codigo=" + codigo + ", nome=" + nome + ", email=" + email + ", 
                senha=" + senha + ", saldo=" + saldo + "]";
	}


	public Integer getCodigo() {
		return codigo;
	}
	public void setCodigo(Integer codigo) {
		this.codigo = codigo;
	}
	public String getNome() {
		return nome;
	}
	public void setNome(String nome) {
		this.nome = nome;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	public String getSenha() {
		return senha;
	}
	public void setSenha(String senha) {
		this.senha = senha;
	}
	public Double getSaldo() {
		return saldo;
	}
	public void setSaldo(Double saldo) {
		this.saldo = saldo;
	}
}    

Oracle_hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
  <session-factory>
    <property name="hibernate.dialect">org.hibernate.dialect.OracleDialect</property>
    <property name="hibernate.connection.driver_class">oracle.jdbc.OracleDriver</property>
    <property name="hibernate.connection.url">jdbc:oracle:thin:@127.0.0.1:1521:XE</property>
    <property name="hibernate.connection.username">system</property>
    <property name="hibernate.connection.password">0123</property>
     
     
       <property name="hibernate.show_sql">true</property>
       <property name="hibernate.format_sql">true</property>
    
    <mapping class="entity.Usuario" />
  </session-factory>
</hibernate-configuration>    

Main:

package config;

import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;
import org.hibernate.tool.hbm2ddl.SchemaExport;

public class Main {
	
	public static void main(String[] args) {
		Configuration cfg = new AnnotationConfiguration().
				 configure("config/oracle_hibernate.cfg.xml");
		
		 new SchemaExport(cfg).create(true,true);
		 System.out.println("Tabela Criada");
	}
}    

Resultado do Console:

log4j:WARN No appenders could be found for logger (org.hibernate.cfg.annotations.Version).
log4j:WARN Please initialize the log4j system properly.

    drop table Usuario cascade constraints

    create table Usuario (
        codigo number(10,0) not null,
        email varchar2(35) unique,
        nome varchar2(35),
        saldo double precision,
        senha varchar2(100),
        primary key (codigo)
    )
Tabela Criada    

Classe Filter Usuario:

package filtro;

import entity.Usuario;

//designer Pattern Filter
public interface FilterUsuario {

	public void validaUsuario(Usuario u)  throws Exception;
	
}    

Classe Filtro Usuario:

package filtro;
 
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import entity.Usuario;

public class FiltroUsuario implements FilterUsuario {
	
	@Override
	public void validaUsuario(Usuario u) throws Exception {
		if (isCodigo(u)==false){
			throw new IllegalArgumentException("Codigo fora do Padrao, somente acima de zero ...");
		}
		if (isNome(u)==false){
		 throw new IllegalArgumentException("Nome fora do Padrão ...");
		}
		if (isEmail(u)==false){
			throw new IllegalArgumentException("Email fora do Padrão ...");
	    }
		if (isSenha(u)==false){
			throw new IllegalArgumentException("Senha fora do Padrão ...");
	    }
		if (isSaldo(u)==false){
			throw new IllegalArgumentException("Saldo fora do Padrão, maior que zero...");
	    }
	}

	
	public Boolean isCodigo(Usuario u){
		if (u.getCodigo()<=0){
			return false;
		}else{
			return true;
		}
	}

	 public Boolean isNome(Usuario u){
		Pattern p = Pattern.compile("[A-Z a-z]{3,35}");
		Matcher m = p.matcher(u.getNome());
		return m.matches();
	 }
	
	 
	 public Boolean isEmail(Usuario u){
		Pattern p = Pattern.compile(".+@.+\\.[a-z]+");
		Matcher m = p.matcher(u.getEmail());
		return  m.matches();
	 }
	
	 
	 public Boolean isSenha(Usuario u){
			Pattern p = Pattern.compile("[A-Za-z0-9]{3,9}");
			Matcher m = p.matcher(u.getSenha());
			return  m.matches();
		 }
	 
	 
	 public Boolean isSaldo(Usuario u){
		 if (u.getSaldo()<=0){
				return false;
			}else{
				return true;
			}
		 }
}    

Classe ManagerBean:

package manager;

import java.io.Serializable;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import persistence.UsuarioDao;
import entity.Usuario;
import filtro.FiltroUsuario;

@ManagedBean(name="mb")
@SessionScoped //sessão...
public class ManagerBean implements Serializable{
	private static final long serialVersionUID = 1L;
	
	private Usuario usuario;
	private Usuario logado;
	private List lista1;
	
        private Integer MBcodigo;
    	private String  MBsenha;
    	
    	private Double  MBdeposito=0.;
    	private Double  MBretirada=0.;
	
	private DataModel lista2; //jsf (Litsa do JSF)
	
    public ManagerBean() {
	   usuario = new Usuario();//alimentado
    }

    @PostConstruct
    public void init(){
    	usuario = new Usuario();
    	usuario.setSenha("");
    	usuario.setEmail("");
    }
	
        public Usuario getUsuario() {
		return usuario;
	}
	public void setUsuario(Usuario usuario) {
		this.usuario = usuario;
	}
	public Usuario getLogado() {
		return logado;
	}
	public void setLogado(Usuario logado) {
		this.logado = logado;
	}
	public static long getSerialversionuid() {
		return serialVersionUID;
	}
	
	
    private void filtro(){
    	FacesContext fc = FacesContext.getCurrentInstance();
    	 FiltroUsuario fu  = new FiltroUsuario();
    	 try{
    		    fu.validaUsuario(usuario);
    		 	fc.addMessage("form1", new FacesMessage("validacao Ok"));
    	 }catch(Exception ex){
    		 fc.addMessage("form1", new FacesMessage(ex.getMessage()));
    	 }
    }
   
    public void gravar(){
    	FacesContext fc = FacesContext.getCurrentInstance();
    	 try{
    		filtro(); //valida 
    		new UsuarioDao().create(usuario); //grava
    		//Envio de email está Funcionando 
    		// Mensagem m = new Mensagem();     //chama a Mensagem do Email
     		// m.setPara(usuario.getEmail()); //busco email da Pessoa
  		//  String msg = new EmailUtil().enviarEmail(m); //dispara o email
   		     
    		usuario = new Usuario(); //limpa
   fc.addMessage("form1", new FacesMessage("gravacao realizada com Sucesso ...")); //passa as msg
    	 }catch(Exception ex){
    		 fc.addMessage("form1", new FacesMessage(ex.getMessage()));
    	 }
    }


	public List getLista1() {
		return lista1;
	}
	public void setLista1(List lista1) {
		this.lista1 = lista1;
	}


	public DataModel getLista2() {
		try{
			lista2 = new ListDataModel(    new UsuarioDao().findAll()    );
			//consulta no DataModel
		}catch(Exception ex){
		}
		return lista2;
	}


	public void setLista2(DataModel lista2) {
		this.lista2 = lista2;
	}
    
        public void excluir(){
    	FacesContext fc = FacesContext.getCurrentInstance();
    	try{
    		//imprimindo o nome
    		fc.addMessage("form2", new FacesMessage("Usuario Excluido :" + usuario.getNome()));
   		new UsuarioDao().delete(usuario); //excluindo o USUARIO ...
    		//vou excluir
    	}catch(Exception ex){
    		 fc.addMessage("form2", new FacesMessage("Error :" + ex.getMessage()));
    	}
    }
    
 
    public void atualizar(){
    	FacesContext fc = FacesContext.getCurrentInstance();
    	try{
    		 fc.addMessage("form2", new FacesMessage("Usuario Alterado :" + usuario.getNome()));
    		    new UsuarioDao().update(usuario); 
    	}catch(Exception ex){
    		 fc.addMessage("form2", new FacesMessage("Error :" + ex.getMessage()));
    	}
    }


	public Integer getMBcodigo() {
		return MBcodigo;
	}
	public void setMBcodigo(Integer mBcodigo) {
		MBcodigo = mBcodigo;
	}
	public String getMBsenha() {
		return MBsenha;
	}
	public void setMBsenha(String mBsenha) {
		MBsenha = mBsenha;
	}

	////mudar de Página ...
        public String logar(){
    	FacesContext fc = FacesContext.getCurrentInstance();
    	try{
    		usuario = new Usuario();
    		    usuario.setCodigo(MBcodigo);
    		    usuario.setSenha(MBsenha);
    		    logado = new UsuarioDao().isLogin(usuario); //null ou cheio
    		    if (logado !=null){
    		      fc.addMessage("form5", new FacesMessage("Seja Bem Vindo Usuario :" + logado.getNome()));
      		      return "logado.jsf"; //entra no Logado -> redirect
      		      //indo para a outra página
    		    }else{
    		    	logado = null;
    		    	MBcodigo=0;
    		    	MBsenha="";
    		    }
    		    fc.addMessage("form4", new FacesMessage("deu ruim ... Nao Logou !!!"));
    	}catch(Exception ex){
    		    fc.addMessage("form4", new FacesMessage("Error ..." + ex.getMessage()));
    	}
    	return null; //parado
    }

	public Double getMBdeposito() {
		return MBdeposito;
	}
	public void setMBdeposito(Double mBdeposito) {
		 MBdeposito = mBdeposito;
	}
	public Double getMBretirada() {
		return MBretirada;
	}
	public void setMBretirada(Double mBretirada) {
		MBretirada = mBretirada;
	}
    
    
        public void depositar(){
	   FacesContext fc = FacesContext.getCurrentInstance();
	   try{
		   logado = new UsuarioDao().findByCode(logado.getCodigo());
		   logado.setSaldo(logado.getSaldo() + getMBdeposito());
		   new UsuarioDao().update(logado);
           fc.addMessage("form5", new FacesMessage("Deposito Realizado com Sucesso: " +logado.getNome()));
	   }catch(Exception ex){
           fc.addMessage("form5", new FacesMessage("Error Deposito :" + ex.getMessage()));
	   }
   }
}    

HibernateUtil:

package persistence;

import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.SessionFactory;

//designer Singleton
public class HibernateUtil {
    private static final SessionFactory sessionFactory;

    static {
        try {
            sessionFactory = new AnnotationConfiguration().
            configure("config/oracle_hibernate.cfg.xml").buildSessionFactory();
        } catch (Throwable ex) {
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
}    

Classe UsuarioDao:

package persistence;

import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import entity.Usuario;

public class UsuarioDao {
	Session session;
	Transaction transaction;
	Query query;
	Criteria criteria;
	
	public void create(Usuario u)throws Exception{
		session = HibernateUtil.getSessionFactory().openSession();
	        transaction = session.beginTransaction();
	           session.save(u);
 	        transaction.commit();
  	    session.close();
	}

	public List findAll(){
		session = HibernateUtil.getSessionFactory().openSession();
	       List lista = session.createQuery("from Usuario").list();	
		 session.close();
		return lista;
	}

	public Usuario isLogin(Usuario u){
		session = HibernateUtil.getSessionFactory().openSession();
		 query = session.createQuery("from Usuario u where u.codigo=:param1 and u.senha=:param2"); 
//hibernate...
		     query.setInteger("param1",u.getCodigo());
		     query.setString("param2",u.getSenha());
        Usuario resp =(Usuario) query.uniqueResult();  
		 session.close();
		 return resp;
	}
	
	public void delete(Usuario u)throws Exception{
		session = HibernateUtil.getSessionFactory().openSession();
	        transaction = session.beginTransaction();
	           session.delete(u);
 	        transaction.commit();
  	    session.close();
	}

	public void update(Usuario u)throws Exception{
		session = HibernateUtil.getSessionFactory().openSession();
	        transaction = session.beginTransaction();
	           session.update(u);
 	        transaction.commit();
  	    session.close();
	}
	
        public Usuario findByCode(Integer cod)throws Exception{
	   session = HibernateUtil.getSessionFactory().openSession();
	      Usuario usuario = (Usuario) session.get(Usuario.class,cod);
	   session.close();
	   return usuario;
   }
}    

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
         xmlns="http://java.sun.com/xml/ns/javaee" 
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
         http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
  <display-name>jsfConta3</display-name>
  
  <servlet>
    <servlet-name>Faces Servlet</servlet-name>
    <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  
  <servlet-mapping>
    <servlet-name>Faces Servlet</servlet-name>
    <url-pattern>*.jsf</url-pattern>
  </servlet-mapping>
  
  <context-param>
  	<param-name>primefaces.THEME</param-name>
  	<param-value>cupertino</param-value>
  </context-param>
  
</web-app>    

index.jsp

<%
 response.sendRedirect("sistema.jsf");
%>    

sistema.xhtml

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml"
	xmlns:p="http://primefaces.org/ui"
	xmlns:h="http://java.sun.com/jsf/html"
	xmlns:f="http://java.sun.com/jsf/core">
<h:head>
</h:head>

<h:body>
  <p:panel header="Validação dos Dados Pattern Filter">
    <h:form id="form1">
       <p:panelGrid columns="2">
          <h:outputText value="Codigo" />
          <p:inputText value="#{mb.usuario.codigo}" required="true" size="35" />   

          <h:outputText value="Nome" />
          <p:inputText value="#{mb.usuario.nome}"  required="true" size="35" />   

          <h:outputText value="Email" />
          <p:inputText value="#{mb.usuario.email}"  required="true" size="35" />

          <h:outputText value="Senha" />
          <p:password value="#{mb.usuario.senha}"  required="true" size="15" />

          <h:outputText value="Saldo" />
          <p:inputText  value="#{mb.usuario.saldo}"  required="true" size="15" />

            <p:commandButton value="Valida os Dados" 
                             action="#{mb.gravar}"
                             ajax="true"
                update=":form1,:form2">                                 
            </p:commandButton>
                             
         <p:messages></p:messages>                       
      </p:panelGrid>
     </h:form>
   </p:panel>
    
    
   <p:panel header="Consulta dos Dados - #Caveira" >
     <h:form id="form2">
      <p:dataTable value="#{mb.lista2}" var="linha"  paginator="true" rows="3" >
         <p:column headerText="Codigo">
           <p:outputLabel value="#{linha.codigo}"></p:outputLabel>
         </p:column>
      
        <p:column headerText="Nome">
           <p:outputLabel value="#{linha.nome}"></p:outputLabel>
         </p:column>
         
        <p:column headerText="Email">
           <p:outputLabel value="#{linha.email}"></p:outputLabel>
         </p:column>
        
         <p:column headerText="Senha">
           <p:outputLabel value="#{linha.senha}"></p:outputLabel>
         </p:column>
          
        <p:column headerText="Saldo">
           <p:outputLabel value="#{linha.saldo}"></p:outputLabel>
         </p:column>
         
   <p:column headerText="Excluir">
     <p:commandButton ajax="true" value="Excluir" update=":form2" action="#{mb.excluir}">
         <f:setPropertyActionListener target="#{mb.usuario}" value="#{linha}">             
         </f:setPropertyActionListener>
    </p:commandButton>
         </p:column>
        
        <p:column headerText="Alterar">
          <p:commandButton ajax="true" value="Alterar" update=":form3" onclick="janela.show()">
              <f:setPropertyActionListener target="#{mb.usuario}" value="#{linha}">                  
              </f:setPropertyActionListener>
        </p:commandButton>  
         </p:column>
        
              </p:dataTable>
               <p/>
               <p:message for="form2"></p:message>
     </h:form>
   </p:panel>

    
   <p:dialog modal="true" widgetVar="janela" header="Alteracao dos Dados">
    <h:form id="form3">
         <h:inputHidden value="#{mb.usuario.codigo}"></h:inputHidden>
         <p:panelGrid columns="2">
           <h:outputText value="Nome" />
           <p:inputText value="#{mb.usuario.nome}"></p:inputText>
             <h:outputText value="Email" />
            <p:inputText value="#{mb.usuario.email}"></p:inputText>
             <h:outputText value="Senha" />
             <p:inputText value="#{mb.usuario.senha}"></p:inputText>
             <h:outputText value="Saldo" />
             <p:inputText value="#{mb.usuario.saldo}"></p:inputText>
         </p:panelGrid>
         <p:commandButton value="Atualizar" action="#{mb.atualizar}" update=":form1,:form2"
             onclick="janela.hidden()" />
          </h:form>
   </p:dialog>
   
   
    <p:panel header="Logar No Sistema">
    <h:form id="form4">
       <p:panelGrid columns="2">
          <h:outputText value="Codigo" />
          <p:inputText value="#{mb.MBcodigo}"   required="true" size="10" />   

          <h:outputText value="Senha" />
          <p:password value="#{mb.MBsenha}"     required="true" size="35" />   
   
            <p:commandButton value="Logar no Sistema" 
                             action="#{mb.logar}"
                             update=""
                             ajax="false">
            </p:commandButton>
        </p:panelGrid>
        <p/>
       <p:message for="form4"></p:message>    
    </h:form>
   </p:panel>
</h:body>
</html>    

Resultado depois de gravar Usuário...

Resultado quando clicar em Alterar...

Resultado Depois de alterado...

Resultado de Logado...