Sim, mas normalmente é um servlet, em todos os livros e referencias q li, é um servlet direto, até já vi implementações em jsp…
E sobre o DAO, olha só, vou te colocar um exemplo de fábrica de DAOs, vai sair comprido, mas, espero q ajude… ehhehe
A Factory abstrata, no caso, esse DAO esta usando o padrão abstract factory, cujo usa um DAO pra cada tipo de banco… tb pode-se usar o factory method, q usa uma só implementação pra todos os bancos, usando SQL padrão (javateco q adora essa heheh), eu fiz em abstract factory (confesso, é muito maior, por ter uma implementação pra cada tipo de banco) pq se ficar td em SQL padrão, há instruções nativas do Oracle q são muito mais rapidas do q o SQL padrão, quero dizer, tem bancos q se saem mais rapidos usando os recursos q só os mesmos oferecem, então, pra ter acesso a isso, fiz em abstract factory
[code]
package com.portaljava.dao;
import com.portaljava.dao.postgres.PostgresDAOFactory;
import com.portaljava.dao.oracle.OracleDAOFactory;
// DAO Factory de classe abstrata
public abstract class DAOFactory {
// tipos de DAO suportados pela factory
public static final int POSTGRES = 1;
public static final int ORACLE = 2;
// haverá um método para cada DAO que pode ser
// criado. As factories concretas terão de
// implementar esses métodos.
public abstract AlunoDAO getAlunoDAO();
public abstract ProfessorDAO getProfessorDAO();
public static DAOFactory getDAOFactory( int factory ) {
switch( factory ) {
case POSTGRES: return new PostgresDAOFactory();
case ORACLE: return new OracleDAOFactory();
default: return null;
}
}
}[/code]
A Factory do Postgres
[code]
package com.portaljava.dao.postgres;
import java.sql.Connection;
import java.sql.SQLException;
import javax.sql.DataSource;
import com.portaljava.dao.*;
import com.portaljava.locator.ServiceLocator;
import com.portaljava.locator.ServiceLocatorException;
public class PostgresDAOFactory extends DAOFactory {
private static DataSource dataSource;
public static Connection createConnection() {
Connection connection = null;
if ( dataSource == null )
try {
dataSource =
ServiceLocator.getInstance().getDataSource( "java:jdbc/PostgresDS" );
} catch ( ServiceLocatorException e ) {
System.out.println( e.getMessage() );
}
try {
connection = dataSource.getConnection();
} catch ( SQLException e ) {
System.out.println( e );
}
return connection;
}
public AlunoDAO getAlunoDAO() {
return new PostgresAlunoDAO();
}
public ProfessorDAO getProfessorDAO() {
return new PostgresProfessorDAO();
}
}[/code]
A interface AlunoDAO, essa é a interface cujo as implementações concretas de postgress e outros bancos devem usar, essas implementações são os SQLs (tb tem a interface do ProfessorDAO, q é praticamente igual, só muda o tipo de Aluno pra Professor nos métodos…)
[code]
package com.portaljava.dao;
import java.util.ArrayList;
import com.portaljava.valueobject.Aluno;
public interface AlunoDAO {
public void insertAluno( Aluno aluno );
public Aluno findAlunoById( int id );
public Aluno findAlunoById( Aluno aluno );
public Aluno findAlunoByMatricula( int matricula );
public Aluno findAlunoByMatricula( Aluno aluno );
public Aluno findAlunoByNome( String nome );
public Aluno findAlunoByNome( Aluno aluno );
public boolean updateAluno( Aluno aluno );
public boolean removeAluno( int id );
public boolean removeAluno( Aluno aluno );
public ArrayList findAll();
}[/code]
A classe concreta q implementa AlunoDAO, é ela q contém obtém a referencia de uma conexão no pool, e executa os SQLs específicos de Aluno…, só nunca se esqueça de fechar essas conexões, digo, de devolver as referencias pro pool!! se não, não vai ter sentido o pool… hehehe
[code]
package com.portaljava.dao.postgres;
import java.util.ArrayList;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.portaljava.valueobject.Aluno;
import com.portaljava.dao.AlunoDAO;
public class PostgresAlunoDAO implements AlunoDAO {
// os metodos seguintes usam
// PostgreDAOFactory.createConnection()
// para obter uma conexao conforme exigido
public void insertAluno( Aluno aluno ) {
Connection connection = PostgresDAOFactory.createConnection();
PreparedStatement statement = null;
try {
statement = connection.prepareStatement(
"INSERT INTO tabela (id, login, senha, nome, sobrenome) " +
"VALUES (\'" + aluno.getNome() + "\')"
);
statement.execute();
} catch( SQLException e ) {
System.out.println( e );
} finally {
close( statement, connection );
}
}
public Aluno findAlunoById( int id ) {
Connection connection = PostgresDAOFactory.createConnection();
PreparedStatement statement = null;
ResultSet resultSet = null;
Aluno aluno = null;
try {
statement = connection.prepareStatement( "SELECT * FROM aluno WHERE nome=" + id );
resultSet = statement.executeQuery();
if ( !resultSet.next() )
return null;
aluno = new Aluno();
aluno.setId( resultSet.getInt( "id" ) );
aluno.setMatricula( resultSet.getInt( "login" ) );
aluno.setSenha( resultSet.getString( "senha" ) );
aluno.setNome( resultSet.getString( "nome" ) );
aluno.setSobrenome( resultSet.getString( "sobrenome" ) );
aluno.setFoto( resultSet.getString( "foto" ) );
aluno.setEndereco( resultSet.getString( "endereco" ) );
aluno.setCep( resultSet.getLong( "cep" ) );
aluno.setCaixaPostal( resultSet.getInt( "caixaPostal" ) );
aluno.setTelefoneResidencial( resultSet.getLong( "telefoneResidencial" ) );
aluno.setTelefoneComercial( resultSet.getLong( "telefoneComercial" ) );
aluno.setCelular( resultSet.getLong( "celular" ) );
aluno.setDataDeIngresso( resultSet.getDate( "dataDeIngresso" ) );
} catch( SQLException e ) {
System.out.println( e );
} finally {
close( statement, connection );
}
return aluno;
}
public Aluno findAlunoById( Aluno aluno ) {
return findAlunoById( aluno.getId() );
}
public Aluno findAlunoByMatricula( int matricula ) {
Connection connection = PostgresDAOFactory.createConnection();
PreparedStatement statement = null;
ResultSet resultSet = null;
Aluno aluno = null;
try {
statement = connection.prepareStatement(
"SELECT * FROM aluno WHERE matricula=" + matricula
);
resultSet = statement.executeQuery();
if ( !resultSet.next() )
return null;
aluno = new Aluno();
aluno.setId( resultSet.getInt( "id" ) );
aluno.setMatricula( resultSet.getInt( "login" ) );
aluno.setSenha( resultSet.getString( "senha" ) );
aluno.setNome( resultSet.getString( "nome" ) );
aluno.setSobrenome( resultSet.getString( "sobrenome" ) );
aluno.setFoto( resultSet.getString( "foto" ) );
aluno.setEndereco( resultSet.getString( "endereco" ) );
aluno.setCep( resultSet.getLong( "cep" ) );
aluno.setCaixaPostal( resultSet.getInt( "caixaPostal" ) );
aluno.setTelefoneResidencial( resultSet.getLong( "telefoneResidencial" ) );
aluno.setTelefoneComercial( resultSet.getLong( "telefoneComercial" ) );
aluno.setCelular( resultSet.getLong( "celular" ) );
aluno.setDataDeIngresso( resultSet.getDate( "dataDeIngresso" ) );
} catch( SQLException e ) {
System.out.println( e );
} finally {
close( statement, connection );
}
return aluno;
}
public Aluno findAlunoByMatricula( Aluno aluno ) {
return findAlunoByMatricula( aluno.getMatricula() );
}
public Aluno findAlunoByNome( String nome ) {
Connection connection = PostgresDAOFactory.createConnection();
PreparedStatement statement = null;
ResultSet resultSet = null;
Aluno aluno = null;
try {
statement = connection.prepareStatement(
"SELECT * FROM aluno WHERE matricula=" + nome
);
resultSet = statement.executeQuery();
if ( !resultSet.next() )
return null;
aluno = new Aluno();
aluno.setId( resultSet.getInt( "id" ) );
aluno.setMatricula( resultSet.getInt( "login" ) );
aluno.setSenha( resultSet.getString( "senha" ) );
aluno.setNome( resultSet.getString( "nome" ) );
aluno.setSobrenome( resultSet.getString( "sobrenome" ) );
aluno.setFoto( resultSet.getString( "foto" ) );
aluno.setEndereco( resultSet.getString( "endereco" ) );
aluno.setCep( resultSet.getLong( "cep" ) );
aluno.setCaixaPostal( resultSet.getInt( "caixaPostal" ) );
aluno.setTelefoneResidencial( resultSet.getLong( "telefoneResidencial" ) );
aluno.setTelefoneComercial( resultSet.getLong( "telefoneComercial" ) );
aluno.setCelular( resultSet.getLong( "celular" ) );
aluno.setDataDeIngresso( resultSet.getDate( "dataDeIngresso" ) );
} catch( SQLException e ) {
System.out.println( e );
} finally {
close( statement, connection );
}
return aluno;
}
public Aluno findAlunoByNome( Aluno aluno ) {
return findAlunoByNome( aluno.getNome() );
}
public boolean updateAluno( Aluno aluno ) {
Connection connection = PostgresDAOFactory.createConnection();
PreparedStatement statement = null;
try {
statement = connection.prepareStatement( "UPDATE * FROM tabela WHERE id=" + aluno.getId() );
statement.executeQuery();
} catch ( SQLException e ) {
System.out.println( e );
return false;
} finally {
close( statement, connection );
}
return true;
}
public boolean removeAluno( int id ) {
Connection connection = PostgresDAOFactory.createConnection();
PreparedStatement statement = null;
try {
statement = connection.prepareStatement( "DELETE * FROM tabela WHERE id=" + id );
statement.executeQuery();
} catch ( SQLException e ) {
System.out.println( e );
return false;
} finally {
close( statement, connection );
}
return true;
}
public boolean removeAluno( Aluno aluno ) {
return removeAluno( aluno.getId() );
}
public ArrayList findAll() {
Connection connection = PostgresDAOFactory.createConnection();
PreparedStatement statement = null;
ResultSet resultSet = null;
ArrayList list = null;
try {
statement = connection.prepareStatement( "SELECT * FROM aluno" );
resultSet = statement.executeQuery();
if ( !resultSet.next() )
return null;
list = new ArrayList();
do {
list.add(
new Aluno(
resultSet.getInt( "id" ),
resultSet.getInt( "matricula" ),
resultSet.getString( "senha" ),
resultSet.getString( "nome" ),
resultSet.getString( "sobrenome" ),
resultSet.getString( "foto" ),
resultSet.getString( "endereco" ),
resultSet.getLong( "cep" ),
resultSet.getInt( "caixaPostal" ),
resultSet.getLong( "telefoneResidencial" ),
resultSet.getLong( "telefoneComercial" ),
resultSet.getLong( "celular" ),
resultSet.getDate( "dataDeIngresso" )
)
);
} while( !resultSet.next() );
} catch( SQLException e ) {
System.out.println( e );
} finally {
close( statement, connection );
}
return list;
}
public void close( PreparedStatement statement, Connection connection ) {
try {
statement.close();
connection.close();
} catch( SQLException e ) {
e.printStackTrace();
}
}
}[/code]
e um exemplo do q o cliente da aplicação faria pra digamos, inserir um aluno no banco:
DAOFactory factory =
DAOFactory.getDAOFactory( DAOFactory.POSTGRES );
AlunoDAO alunoDAO =
factory.getAlunoDAO();
alunoDAO.insertAluno( new Aluno( ... ) );