Conteúdos abordados:
- JDBC;
- Banco de dados na linguagem java;
- Uso do NetBeans para gerência do banco;
- Servlet para listagem de dados.
Agora, colabore com a resolução do exemplo-código!
Assinar:
Postar comentários (Atom)
Inovação, Gestão, Tecnologia e muito código Java!
Classe responsável pela conexão ao banco:
ResponderExcluirimport java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DBConnection {
final private String driver = "com.mysql.jdbc.Driver";
final private String url = "jdbc:mysql://localhost:3306/bddsi";
final private String user = "root";
final private String password = "root";
public Connection getMyDBConnection() throws ClassNotFoundException, SQLException{
Class.forName(driver);
return DriverManager.getConnection(url, user, password);
}
}
JavaBeans referente a tabela USER:
public class User implements java.io.Serializable{
private int id_user;
private String login;
private String password;
private String address;
public int getId_user() {
return id_user;
}
public void setId_user(int id_user) {
this.id_user = id_user;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
Classe de persistência:
import Conector.DBConnection;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.LinkedList;
import java.util.List;
public class UsersDao extends DBConnection {
Connection cx;
public UsersDao() throws SQLException, ClassNotFoundException {
this.cx = getMyDBConnection();
}
public UsersDao(Connection cx) {
this.cx = cx;
}
public User getUser(String nome) throws SQLException {
PreparedStatement pst = null;
ResultSet rs = null;
try {
pst = cx.prepareStatement("select * from users where login = ?");
pst.setString(1, nome);
rs = pst.executeQuery();
if (rs.next()) {
User usr = getUserFromSQL(rs);
return usr;
}
} finally {
pst.close();
rs.close();
}
return null;
}
public boolean ehUserEPasswordValido(String username, String password) throws SQLException {
PreparedStatement pst = null;
ResultSet rs = null;
try {
pst = cx.prepareStatement("select * from users where login = ? and password = ?");
pst.setString(1, username);
pst.setString(2, password);
rs = pst.executeQuery();
if (rs.next()) {
return true;
}
} finally {
pst.close();
rs.close();
}
return false;
}
public List getListaDeUsers()throws SQLException{
List returned = new LinkedList();
Statement st = null;
ResultSet rs = null;
try{
st = cx.createStatement();
rs = st.executeQuery("select * from users");
while (rs.next()) {
returned.add(getUserFromSQL(rs));
}
}finally{
st.close();
rs.close();
}
return returned;
}
public User getUserFromSQL(ResultSet rs)throws SQLException{
User returned = new User();
returned.setId_user(rs.getInt("id_user"));
returned.setLogin(rs.getString("login"));
returned.setPassword(rs.getString("password"));
returned.setAddress(rs.getString("address"));
return returned;
}
}
Servlet:
ResponderExcluirprotected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
ClientesControl ctlClientes = new ClientesControl();
Clientes cliente = new Clientes();
cliente.setName(request.getParameter("name"));
cliente.setEndereco(request.getParameter("endereco"));
cliente.setEmail(request.getParameter("email"));
try {
if (!ctlClientes.addClientes(cliente)) {
response.sendRedirect("erro.jsp");
return;
}
} catch (SQLException ex) {
Logger.getLogger(AddClienteServlet.class.getName()).log(Level.SEVERE);
}
}
response.sendRedirect("clientes.jsp");
}
DBConnection.java
ResponderExcluirpackage projetoDSI.dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public abstract class DBConnection {
//Conexão MySQL
final private String driver = "com.mysql.jdbc.Driver";
final private String url = "jdbc:mysql://localhost:3306/dbDsi";
final private String user = "root";
final private String password = "root";
public Connection getMyDBConnection() throws ClassNotFoundException, SQLException{
Class.forName(driver);
return DriverManager.getConnection(url, user,password);
}
}
UsersDao.java
package projetoDSI.dao;
import java.sql.*;
import java.util.*;
public class UsersDao extends DBConnection {
Connection cx;
public UsersDao() throws SQLException, ClassNotFoundException{
this.cx = getMyDBConnection();
}
public UsersDao(Connection cx){
this.cx = cx;
}
public User getUser(String nome) throws SQLException{
PreparedStatement pst = null;
ResultSet rs = null;
try{
pst = cx.prepareStatement("select * from users where login = ?");
pst.setString(1,nome);
rs = pst.executeQuery();
if (rs.next()){
User usr = getUser(rs);
return usr;
}
}
finally{
pst.close();
rs.close();
}
return null;
}
public boolean isValidUserAndPassword (String username, String password) throws SQLException {
PreparedStatement pst = null;
ResultSet rs = null;
try{
pst = cx.prepareStatement("select * from users where login = ? and password = ?");
pst.setString(1,username);
pst.setString(1,password);
rs = pst.executeQuery();
if (rs.next()){
return true;
}
}
finally{
pst.close();
rs.close();
}
return false;
}
public List getListOfUsers() throws SQLException{
ResponderExcluirList returned = new LinkedList();
Statement st = null;
ResultSet rs = null;
try{
st = cx.createStatement();
rs = st.executeQuery("select * from users");
while (rs.next()){
returned.add(getUserFromSQL(rs));
}
}
finally {
st.close();
rs.close();
}
return returned;
}
private User getUserFromSQL (ResultSet rs) throws SQLException {
User returned = new User();
returned.setId_user (rs.getInt("iduser"));
returned.setLogin (rs.getString("login"));
returned.setPassword(rs.getString("password"));
returned.setAddress(rs.getString("address"));
return returned;
}
}
User.java
package projetoDSI.dao;
public class User implements java.io.Serializable{
private int iduser;
private String login;
private String password;
private String address;
public int getId_user() {
return iduser;
}
public void setId_user(int iduser) {
this.iduser = iduser;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
Servlet
package projetoDSI.dao;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
WebServlet(name = "cliServlet", urlPatterns = {"/cliServlet"})
public class cliServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
cliServlet ctlUser =new cliServlet();
User u = new User();
u.setLogin(request.getParameter("login"));
u.setPassword(request.getParameter("password"));
u.setAddress(request.getParameter("address"));
try {
if (!ctlUser.addUser (u)){
response.sendRedirect ("error.jsp");
return;
}
catch (SQLException ex){
Logger.getLogger(AddcliServlet.class).getName()).log(Level.SEVERE, null, ex));
}
response.sendRedirect("Usuarios.jsp");
}
}
}
Bom dia a todos, esta é uma alternativa mais fácil e funcional do problema.
ResponderExcluirEstrutura dos pacote:
pacotes de Códigos
--Servlet
--br.com.vander.modelo
--br.com.vander.bean
//Servlet
package ServletLogin;
import br.com.vander.model.bean.Usuario;
import br.com.vander.model.dao.DaoUsuario;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@WebServlet(name = "ControllerServlet", urlPatterns = {"/ControllerServlet"})
public class ControllerServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
HttpSession session = request.getSession(); //obtem a sessao do usuario, caso exista
Usuario user = null;
String loginForm = request.getParameter("usuario"); // Pega o Login vindo do formulario
String senhaForm = request.getParameter("senha"); //Pega a senha vinda do formulario
try {
DaoUsuario dao = new DaoUsuario(); //cria uma instancia do DAO usuario
user = dao.getUsuario(loginForm, senhaForm);
}
catch ( Exception e ){
}
//se nao encontrou usuario no banco, redireciona para a pagina de erro!
if ( user == null ) {
session.invalidate();
request.getRequestDispatcher("tela2.jsp" ).forward(request, response);
}
else{
//se o dao retornar um usuario, coloca o mesmo na sessao
session.setAttribute("user", user);
request.getRequestDispatcher("tela3.jsp").forward(request, response);
}
}
@Override
public String getServletInfo() {
return "Short description";
}//
}
O resto já esta no exemplo citado em aula vlw