CCT0051 Código Usuário

Arquivo index.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>


    
        
        JSP Page
    
    
        

Login do Sistema

Usuario: Senha:
<% String msg = (String) request.getAttribute("msg"); if (msg != null) { out.println(msg); // exibe a mensagem caso exista } %>
Arquivo Conexao.java
package Fontes;

import java.sql.*;

public abstract class Conexao {
    
    final private String driver = "com.mysql.jdbc.Driver";
    final private String url = "jdbc:mysql://localhost:3306/estacio";
    final private String user = "root";
    final private String password = "";
    
    public Connection getConexao() throws ClassNotFoundException, SQLException {
        
        Class.forName(driver);
        return DriverManager.getConnection(url, user, password);
    }
    
}

Arquivo Usuario.java
package Fontes;

import java.sql.*;

public class Usuario extends Conexao{
    private String nome;
    private String senha;

    Connection cx;
    
    public Usuario() throws ClassNotFoundException, SQLException {
        this.cx = getConexao();
    }
    
    public Usuario(Connection cx) {
                this.cx = cx;
    }
    
    public boolean verificarUsuarios() throws SQLException {
        PreparedStatement pst = null;
        ResultSet rs = null;
        try{
            pst = cx.prepareStatement("select * from usuarios where nome = ? and senha = ?");
            pst.setString(1, this.nome);
            pst.setString(2, this.senha);
            rs = pst.executeQuery();
            if(rs.next()){
                return true;
            }
        }
        finally{
            pst.close();
            rs.close();
        }
        return false;
    }

    public String getNome() {
        return nome;
    }

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

    public String getSenha() {
        return senha;
    }

    public void setSenha(String senha) {
        this.senha = senha;
    }
    
    
}

Arquivo (Servlet) Login.java
public class Login extends HttpServlet {

 protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, ClassNotFoundException, SQLException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            /*
             * TODO output your page here. You may use following sample code.
             */
            String fnome = request.getParameter("usuario");
            String fsenha = request.getParameter("senha");
            RequestDispatcher rd = null;
            Usuario usua = new Usuario();

            usua.setNome(fnome);
            usua.setSenha(fsenha);

            if (usua.verificarUsuarios()) {
                HttpSession sessao = request.getSession();
                sessao.setAttribute("USER", fnome);
                rd = request.getRequestDispatcher("/logado.jsp");
                rd.forward(request, response);
            } else {
                request.setAttribute("msg", "Usuário ou Senha inválidos");
                rd = request.getRequestDispatcher("/index.jsp");
                rd.forward(request, response);
            }


        } finally {
            out.close();
        }
    }
}

Baixe aqui o projeto código completo

Comentários

Postagens mais visitadas deste blog

Classes(abstratas e concretas), Objetos, Métodos, Construtores, Vetor de Objetos e trabalhar o conceito de interface.

Questão Comentada - Prof Nelson Lage

GST0070 - Estudo de Caso - Tomada de decisões: de volta ao básico - Aula 3