How to show the person’s name on the welcome screen?

Asked

Viewed 39 times

-2

 <jsp:useBean id="calcula" class="br.com.projetojsp.bean.UsuarioBean"
    type="br.com.projetojsp.bean.UsuarioBean" scope="page" />

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
    <a href="index.jsp"><img alt="Sair" title="Sair"
        src="resources/img/exit.png" width="30px" height="30px"> </a>
    <div style="padding-top: 10%;">

        <h1 style="text-align: center;">Bem-vindo ao Sistema Administrativo NOMEDOUSUARIOAQUI!

</h1>

        <center>
            <table>
                <tr>
                    <td><a href="salvarUsuario?acao=listarTodos"> <img
                            src="resources/img/user.png" alt="Cadastrar Usuário"
                            title="Cadastrar Usuário" width="100px" height="100px">
                    </a></td>
                    <td><a href="salvarProduto?acao=listartodos"><img
                            width="100px" height="100px" title="Cadastro de Produto"
                            alt="Cadastro de Produto" src="resources/img/prod.png"> </a></td>

                </tr>
                <tr>
                    <td>Cad. Usuários</td>
                    <td>Cad. Produtos</td>
                </tr>
            </table>
        </center>
    </div>
</body>
</html>
package br.com.projetojsp.bean;

import java.io.Serializable;

public class UsuarioBean implements Serializable {


private static final long serialVersionUID = -2072984964113354533L;

private Long id;
private String login;
private String senha;
private String nome;    
private String cep;
private String rua;
private String bairro;
private String cidade;
private String estado;
private String ibge;
private boolean ativo;
private String sexo;
private String perfil;

private String fotoBase64;
private String fotoBase64Miniatura;
private String contentType;
private String tempFotoUser;

private String curriculoBase64;
private String contentTypeCurriculo;

private boolean atualizarImagem;
private boolean atualizarCurriculo;

public UsuarioBean() {
    this.atualizarImagem = true;
    this.atualizarCurriculo = true;
}

public String getTempFotoUser() {
    setTempFotoUser();
    return tempFotoUser;
}

public void setTempFotoUser() {
    tempFotoUser = "data:" + contentType + ";base64," + fotoBase64;
}

public String getLogin() {
    return login;
}

public void setLogin(String login) {
    this.login = login;
}

public String getSenha() {
    return senha;
}

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

public Long getId() {
    return id;
}

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

public String getNome() {
    return nome;
}

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

public String getCep() {
    return cep;
}

public void setCep(String cep) {
    this.cep = cep;
}

public String getRua() {
    return rua;
}

public void setRua(String rua) {
    this.rua = rua;
}

public String getBairro() {
    return bairro;
}

public void setBairro(String bairro) {
    this.bairro = bairro;
}

public String getCidade() {
    return cidade;
}

public void setCidade(String cidade) {
    this.cidade = cidade;
}

public String getEstado() {
    return estado;
}

public void setEstado(String estado) {
    this.estado = estado;
}

public String getIbge() {
    return ibge;
}

public void setIbge(String ibge) {
    this.ibge = ibge;
}

public String getFotoBase64() {
    return fotoBase64;
}

public void setFotoBase64(String fotoBase64) {
    this.fotoBase64 = fotoBase64;
}

public String getContentType() {
    return contentType;
}

public void setContentType(String contentType) {
    this.contentType = contentType;
}

public String getCurriculoBase64() {
    return curriculoBase64;
}

public void setCurriculoBase64(String curriculoBase64) {
    this.curriculoBase64 = curriculoBase64;
}

public String getContentTypeCurriculo() {
    return contentTypeCurriculo;
}

public void setContentTypeCurriculo(String contentTypeCurriculo) {
    this.contentTypeCurriculo = contentTypeCurriculo;
}

public String getFotoBase64Miniatura() {
    return fotoBase64Miniatura;
}

public void setFotoBase64Miniatura(String fotoBase64Miniatura) {
    this.fotoBase64Miniatura = fotoBase64Miniatura;
}

public boolean isAtualizarImagem() {
    return atualizarImagem;
}

public void setAtualizarImagem(boolean atualizarImagem) {
    this.atualizarImagem = atualizarImagem;
}

public boolean isAtualizarCurriculo() {
    return atualizarCurriculo;
}

public void setAtualizarCurriculo(boolean atualizarCurriculo) {
    this.atualizarCurriculo = atualizarCurriculo;
}

public boolean isAtivo() {
    return ativo;
}

public void setAtivo(boolean ativo) {
    this.ativo = ativo;
}

public String getSexo() {
    return sexo;
}

public void setSexo(String sexo) {
    this.sexo = sexo;
}

public String getPerfil() {
    return perfil;
}

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

@Override
public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + ((id == null) ? 0 : id.hashCode());
    return result;
}

@Override
public boolean equals(Object obj) {
    if (this == obj)
        return true;
    if (obj == null)
        return false;
    if (getClass() != obj.getClass())
        return false;
    UsuarioBean other = (UsuarioBean) obj;
    if (id == null) {
        if (other.id != null)
            return false;
    } else { 
        if (!id.equals(other.id))
            return false;
    }           
    return true;
}

@Override
public String toString() {
    return "UsuarioBean [id=" + id + ", login=" + login + ", senha=" + senha + ", nome=" + nome
            + ", cep=" + cep + ", rua=" + rua + ", bairro=" + bairro + ", cidade=" + cidade + ", estado=" + estado
            + ", ibge=" + ibge + ", ativo=" + ativo + ", sexo=" + sexo + ", perfil=" + perfil + "]";
}

}

package br.com.projetojsp.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import br.com.projetojsp.bean.UsuarioBean;
import br.com.projetojsp.connection.SingleConnection;
import br.com.projetojsp.exception.OrphanRemovalException;
import br.com.projetojsp.util.LogUtil;

public class UsuarioDAO {

    private Connection connection;

    public UsuarioDAO() {
        connection = SingleConnection.getConnection();
    }

    public void salvar(UsuarioBean usuario) throws SQLException {
        try {
            String sql = "INSERT INTO usuario (login, senha, nome, cep, rua, "
                    + "bairro, cidade, estado, ibge, fotoBase64, contentType, "
                    + "curriculoBase64, contentTypeCurriculo, fotoBase64Miniatura, "
                    + "ativo, sexo, perfil) "
                    + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
            try (PreparedStatement statement = connection.prepareStatement(sql)) {
                statement.setString(1, usuario.getLogin());
                statement.setString(2, usuario.getSenha());
                statement.setString(3, usuario.getNome());
                statement.setString(4, usuario.getCep());
                statement.setString(5, usuario.getRua());
                statement.setString(6, usuario.getBairro());
                statement.setString(7, usuario.getCidade());
                statement.setString(8, usuario.getEstado());
                statement.setString(9, usuario.getIbge());
                statement.setString(10, usuario.getFotoBase64());
                statement.setString(11, usuario.getContentType());
                statement.setString(12, usuario.getCurriculoBase64());
                statement.setString(13, usuario.getContentTypeCurriculo());
                statement.setString(14, usuario.getFotoBase64Miniatura());
                statement.setBoolean(15, usuario.isAtivo());
                statement.setString(16, usuario.getSexo());
                statement.setString(17, usuario.getPerfil());
                statement.execute();
            }
            connection.commit();
        } catch (Exception e) {
            LogUtil.getLogger(UsuarioDAO.class).error(e.getCause().toString());
            connection.rollback();
        }
    }
    
    public List<UsuarioBean> listarPorNome(String descricaoConsulta) throws SQLException {      
        String sql = "SELECT * FROM usuario WHERE login <> 'admin' AND LOWER(nome) "
                + "LIKE LOWER('%" + descricaoConsulta + "%') ORDER BY nome";        
        return listarUsuarios(sql);
        
    }

    public List<UsuarioBean> listarTodos() throws SQLException {
        String sql = "SELECT * FROM usuario WHERE login <> 'admin'";
        return listarUsuarios(sql);
    }

    private List<UsuarioBean> listarUsuarios(String sql) throws SQLException {
        List<UsuarioBean> usuarios = new ArrayList<>();
        try (PreparedStatement statement = connection.prepareStatement(sql)) {
            try (ResultSet result = statement.executeQuery()) {
                while (result.next()) {
                    UsuarioBean usuario = new UsuarioBean();
                    usuario.setId(result.getLong("id"));
                    usuario.setLogin(result.getString("login"));
                    usuario.setSenha(result.getString("senha"));
                    usuario.setNome(result.getString("nome"));
                    usuario.setCep(result.getString("cep"));
                    usuario.setRua(result.getString("rua"));
                    usuario.setBairro(result.getString("bairro"));
                    usuario.setCidade(result.getString("cidade"));
                    usuario.setEstado(result.getString("estado"));
                    usuario.setIbge(result.getString("ibge"));
                    usuario.setFotoBase64Miniatura(result.getString("fotoBase64Miniatura"));
                    usuario.setContentType(result.getString("contentType"));
                    usuario.setCurriculoBase64(result.getString("curriculoBase64"));
                    usuario.setContentTypeCurriculo(result.getString("contentTypeCurriculo"));
                    usuario.setAtivo(result.getBoolean("ativo"));
                    usuario.setSexo(result.getString("sexo"));
                    usuario.setPerfil(result.getString("perfil"));
                    usuarios.add(usuario);
                }
            }
        }
        return usuarios;
    }

    public Boolean deletar(String id) throws OrphanRemovalException, SQLException {
        try {
            String sql = "DELETE FROM usuario WHERE id = '" + id + "' AND login <> 'admin'";
            try (PreparedStatement statement = connection.prepareStatement(sql)) {
                statement.execute();
            }
            connection.commit();
            return Boolean.TRUE;
        } catch (SQLException e) {
            connection.rollback();          
            throw new OrphanRemovalException("Existe telefones cadastrados para o Usuário!");
        }
    }

    public UsuarioBean consultarPorId(String id) throws SQLException {
        UsuarioBean usuario = null;     
        String sql = "SELECT * FROM usuario WHERE id = '" + id + "' AND login <> 'admin'";
        try (PreparedStatement statement = connection.prepareStatement(sql)) {
            try (ResultSet result = statement.executeQuery()) {
                if (result.next()) {
                    usuario = new UsuarioBean();
                    usuario.setId(result.getLong("id"));
                    usuario.setLogin(result.getString("login"));
                    usuario.setSenha(result.getString("senha"));
                    usuario.setNome(result.getString("nome"));
                    usuario.setCep(result.getString("cep"));
                    usuario.setRua(result.getString("rua"));
                    usuario.setBairro(result.getString("bairro"));
                    usuario.setCidade(result.getString("cidade"));
                    usuario.setEstado(result.getString("estado"));
                    usuario.setIbge(result.getString("ibge"));
                    usuario.setFotoBase64(result.getString("fotoBase64"));
                    usuario.setFotoBase64Miniatura(result.getString("fotoBase64Miniatura"));
                    usuario.setContentType(result.getString("contentType"));
                    usuario.setCurriculoBase64(result.getString("curriculoBase64"));
                    usuario.setContentTypeCurriculo(result.getString("contentTypeCurriculo"));
                    usuario.setAtivo(result.getBoolean("ativo"));
                    usuario.setSexo(result.getString("sexo"));
                    usuario.setPerfil(result.getString("perfil"));
                }
            }
        }       
        return usuario;
    }

    public boolean validarLoginInsert(String login) throws SQLException {       
        String sql = "SELECT COUNT(1) AS qtde FROM usuario WHERE login = '" + login + "'";
        try (PreparedStatement statement = connection.prepareStatement(sql)) {
            try (ResultSet result = statement.executeQuery()) {
                if (result.next()) {
                    return result.getInt("qtde") <= 0;
                }
            }
        }   
        return false;
    }

    public boolean validarSenhaInsert(String senha) throws SQLException {       
        String sql = "SELECT COUNT(1) AS qtde FROM usuario WHERE senha = '" + senha + "'";
        try (PreparedStatement statement = connection.prepareStatement(sql)) {
            try (ResultSet result = statement.executeQuery()) {
                if (result.next()) {
                    return result.getInt("qtde") <= 0;
                }
            }
        }   
        return false;
    }

    public boolean validarLoginUpdate(String login, String id) throws SQLException {        
        String sql = "SELECT COUNT(1) AS qtde FROM usuario WHERE login = '" + login + "' AND id <> '" + id + "'";
        try (PreparedStatement statement = connection.prepareStatement(sql)) {
            try (ResultSet result = statement.executeQuery()) {
                if (result.next()) {
                    return result.getInt("qtde") <= 0;
                }
            }
        }   
        return false;
    }

    public boolean validarSenhaUpdate(String senha, String id) throws SQLException {        
        String sql = "SELECT COUNT(1) AS qtde FROM usuario WHERE senha = '" + senha + "' AND id <> '" + id + "'";
        try (PreparedStatement statement = connection.prepareStatement(sql)) {
            try (ResultSet result = statement.executeQuery()) {
                if (result.next()) {
                    return result.getInt("qtde") <= 0;
                }
            }
        }       
        return false;
    }

    public void atualizar(UsuarioBean usuario) throws SQLException {
        try {
            StringBuilder sql = new StringBuilder();

            sql
            .append("UPDATE usuario SET login = ?, senha = ?, nome = ?, ")
            .append("cep = ?, rua = ?, bairro = ?, cidade = ?, estado = ?, ibge = ?");

            if (usuario.isAtualizarImagem()) {
                sql.append(", fotoBase64 = ?, contentType = ?, fotoBase64Miniatura = ?");
            }

            if (usuario.isAtualizarCurriculo()) {
                sql.append(", curriculoBase64 = ?, contentTypeCurriculo = ?");
            }
            
            sql
            .append(", ativo = ?, sexo = ?, perfil = ?")
            .append(" WHERE id = " + usuario.getId());

            try (PreparedStatement statement = connection.prepareStatement(sql.toString())) {

                int index = 1;

                statement.setString(index ++, usuario.getLogin());
                statement.setString(index ++, usuario.getSenha());
                statement.setString(index ++, usuario.getNome());
                statement.setString(index ++, usuario.getCep());
                statement.setString(index ++, usuario.getRua());
                statement.setString(index ++, usuario.getBairro());
                statement.setString(index ++, usuario.getCidade());
                statement.setString(index ++, usuario.getEstado());
                statement.setString(index ++, usuario.getIbge());

                if (usuario.isAtualizarImagem()) {
                    statement.setString(index ++, usuario.getFotoBase64());
                    statement.setString(index ++, usuario.getContentType());
                    statement.setString(index ++, usuario.getFotoBase64Miniatura());
                }

                if (usuario.isAtualizarCurriculo()) {
                    statement.setString(index ++, usuario.getCurriculoBase64());
                    statement.setString(index ++, usuario.getContentTypeCurriculo());
                }
                
                statement.setBoolean(index ++, usuario.isAtivo());
                statement.setString(index ++, usuario.getSexo());
                statement.setString(index ++, usuario.getPerfil());
                statement.executeUpdate();
            }
            connection.commit();
        } catch (Exception e) {
            LogUtil.getLogger(UsuarioDAO.class).error(e.getCause().toString());
            connection.rollback();
        }
    }

}

package br.com.projetojsp.Servlet;

import java.io.IOException;
import javax.servlet.RequestDispatcher;
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 br.com.projetojsp.bean.UsuarioBean;
import br.com.projetojsp.dao.LoginDAO;
import br.com.projetojsp.util.LogUtil;

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    private final LoginDAO loginDAO = new LoginDAO();

    public LoginServlet() {
        super();
    }
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        try {
            String login = request.getParameter("login");
            String senha = request.getParameter("senha");

            if (login != null && !login.isEmpty() && senha != null && !senha.isEmpty()) {
                String LoginAdm = "admin";
                 if(login.equals(LoginAdm) && senha != null && !senha.isEmpty()) {
                    RequestDispatcher requestDispatcher = request.getRequestDispatcher("WEB-INF/indexAdmin.jsp");
                    requestDispatcher.forward(request, response);
                }
                 else if (loginDAO.validarLogin(login, senha)) {
                    RequestDispatcher requestDispatcher = request.getRequestDispatcher("acessoliberado.jsp");
                    requestDispatcher.forward(request, response);
                }
                else {
                    RequestDispatcher requestDispatcher = request.getRequestDispatcher("acessonegado.jsp");
                    requestDispatcher.forward(request, response);
                    
                }
            } else {
                RequestDispatcher requestDispatcher = request.getRequestDispatcher("index.jsp");
                requestDispatcher.forward(request, response);
            }
        } catch (Exception e) {
            LogUtil.getLogger(LoginServlet.class).error(e.getCause().toString());
        }
    }
}

1 answer

1

Hello,

In your Log(Loginservlet) you must obtain the user and send by request the populated user object of the database. ex.

    UsuarioBean usuarioBean = UsuarioDAO.obterDadosUsuario(codigoUsuario);

to send by request

    request.setAttribute("usuarioBean ", usuarioBean );

In your JSP you will access the object and attribute you want ex.

     <p>Olá ${usuarioBean.nome}, seja bem vindo</p>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.