Login with Java Mysql levels

Asked

Viewed 5,101 times

2

I’m making a login system, only I’m doubtful how I can leave it with levels/ types (admin, user, client).


IMPORTANT : I’m making a method that uses Taglib - "C:if", to make a Switch Case.

The idea is to write one to the admin and another to the user

Being:

Admin = 0

User = 1

Something like that:

if(user.getNivelAcesso()!=null){
                String nivel = user.getNivelAcesso();
                switch(nivel){
                    case "admin":
                        redir = "/admin/home.jsp";
                        break;
                    case "user":
                        redir = "/user/home.jsp";
                        break;
                    default:
                        redir = "login.jsp";
                        break;
                }       

So I don’t even need to use FK, and I simplify, because I don’t need that much security, I just need a basic control


Here is my Mysql code:

CREATE TABLE tb_usuario (
  id_usuario INT NOT NULL AUTO_INCREMENT,
  nome VARCHAR(20) NOT NULL,
  senha VARCHAR(10) NOT NULL,
  PRIMARY KEY (id_usuario));

Here is my java . model:

public class Usuario {

    private int id;
    private String nome;
    private String senha;


    public Usuario() {
        super();

    }

    public int getId() {
        return id;
    }

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

    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;
    }
}

My interface . dao User.DAO:

public interface UsuarioDAO {
    public Usuario buscarUsuario(Usuario usuario) throws SQLException;

    public List<Usuario> listaUsuario() throws SQLException;

    public List<Usuario> pesquisarUsuario(String nome) throws SQLException;

    public boolean adicionarUsuario (Usuario usuario) throws SQLException;

    public boolean alterarUsuario (Usuario usuario) throws SQLException;

    public Usuario buscarUsuarioPorId (int idUsuario) throws SQLException;

    public boolean excluirUsuario (int idUsuario) throws SQLException;
}

My Jdbc . dao class Jdbcusuariodao :

public class JdbcUsuarioDAO implements UsuarioDAO {

@SuppressWarnings("finally")
@Override
public Usuario buscarUsuario(Usuario usuario) throws SQLException {
    Connection con = null;
    PreparedStatement stmt = null;
    StringBuilder sql = new StringBuilder();
    Usuario usr = null;

    try {
        con = Conexao.getConnection();

        sql.append(" SELECT * FROM tb_usuario ");
        sql.append(" WHERE nome = ? and senha = ? ");
        stmt = con.prepareStatement(sql.toString());
        stmt.setString(1, usuario.getNome());
        stmt.setString(2, usuario.getSenha());

        ResultSet rs = stmt.executeQuery();

        while (rs.next()) {
            int id = rs.getInt("id_usuario");
            String nomeUsuario = rs.getString("nome");
            String senha = rs.getString("senha");

            usr = new Usuario();
            usr.setId(id);
            usr.setNome(nomeUsuario);
            usr.setSenha(senha);
        }

    } catch (Exception ex) {
        ex.printStackTrace();
        throw ex;
    } finally {
        stmt.close();
        con.close();
        return usr;
    }

}

My Servletlogin Servlet:

    @WebServlet("/login")
public class ServletLogin extends HttpServlet {
    private static final long serialVersionUID = 1L;

    private UsuarioDAO dao = new JdbcUsuarioDAO();

    public ServletLogin() {
        super();

    }

    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        String redir = "/login.jsp";
        String msg = "";
        Usuario usuarioLogado = null;
        try {
            String nome = request.getParameter("nome");
            String senha = request.getParameter("senha");

            if (nome != null && senha != null) {

                Usuario usuario = new Usuario();
                usuario.setNome(nome);
                usuario.setSenha(senha);

                usuarioLogado = dao.buscarUsuario(usuario);

                if (usuarioLogado != null) {
                    request.getSession().setAttribute("usuarioLogado",
                            usuarioLogado);
                    redir = "/index.jsp";
                } else {
                    msg = "Usuario Ou Senha Invalidos!";
                    redir = "/login.jsp";
                }
            } else {
                msg = "Informe O Usuario E Senha!";
                redir = "/login.jsp";
            }

        } catch (Exception ex) {
            ex.printStackTrace();
            msg = "Erro ao efetuar o login!";
            redir = "/erro.jsp";
        } finally {
            request.setAttribute("msg", msg);
            RequestDispatcher rd = request.getRequestDispatcher(redir);
            rd.forward(request, response);

        }
    }

    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }

}

My login.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Login</title>

<meta name="viewport" content="width=device-width">

<link rel="stylesheet" type="text/css" href="css/clockcss.css"
    charset="utf-8">
<script type="text/javascript">
function runScript(e) {

    if (e.keyCode == 13) {
         validate();

    }
</script>
</head>
<body>
    <form action="/Empresa/login" method="post">
    <input type="hidden" name="paginaLogin" value="s" /> 
        <div id="fundo_login">
            <div id="top_login">
                <div id="txt">Empresa</div>
            </div>
            <div id="alert">
                    <c:if test="${msg !=null}">
                        <font color="red">${msg}</font>
                    </c:if>
                </div>

            <div id="login">
                <div id="imguser"></div>
                <input type="text" maxlength="70" name="nome" placeholder="Nome"
                    required autofocus
                    style="width: 334px; height: 40px; margin-left: 30px; float: left; font-size: 20px; border-radius: 12px; outline: none; border: solid #fff" />
            </div>
            <div id="pass">
                <div id="imgpass"></div>
                <input type="password" maxlength="70" name="senha"
                    placeholder="Senha" required onkeypress="return runScript(event)"
                    style="width: 334px; height: 40px; margin-left: 29px; float: left; font-size: 20px; border-radius: 12px; outline: none; border: solid #fff" />
            </div>
            <div id="checkbox">
                <input type="checkbox" style="float: left; margin: 2px 5px;">
                <div id="txt1">Manter sessão</div>

            </div>
            <div id="botao_login">
                <input type="submit" value="Login"
                    style="width: 440px; height: 48px; background: #02a68b; cursor: pointer; border-radius: 8px; color: #fff; font-size: 18px; border: 1px solid #02a68b; margin: 20px 20px;" />

            </div>
        </div>
    </form>
</body>
</html>

Here’s what I’ve done, I’m thinking of creating a java class "Nviel" in . model com :

-int : Level; -String : Description;

So call this class in User.java, then do not know where to go. I do not know how to create Mysql, and do not know how to call for the other class and interface. I don’t know if I have to create a javascript or not.

  • Levels/roles will be fixed or your application will manage this as well?

  • If I remember correctly, the book’s recommendation Use Head! Servlets & JSP was not to do this manually but to let the container manage it. Then he gave an example using Tomcat. It’s Tomcat you’re using as an application server? P.S.: You can use Servlet Filters to intercept requests to restricted access Rvlets and request user login.

  • Dude, as @Piovezan mentioned, use j_security_check to authenticate users. Another interesting thing you can use is Realms. Jboss relays for example are very efficient for this kind of thing. Reinventing the wheel is never cool...

  • Miguel Cartagena - yes they will be fixed. Piovezan - Yes I’m using a filter, but my filter I only use so no one can access the other pages without being logged in.

  • @Wagner If you need to respond to comments, it’s best to do this as a new comment (starting with a reference to who you want to respond to, like I did here). That way, the person who commented knows that you responded to it.

  • Why are you writing an authorization and authentication layer on the nail? Java already has the JAAS, and several Frameworks as Apache Shiro, Spring Security and jGuard. All these options will allow the use of profiles and answer your authentication use case using the database.

Show 1 more comment

1 answer

1


You can set the attribute in the user class profile. When the user creates an account, they will choose between the admin profile, or employee, for example, so they will be registered with that profile. When he logs in, you save his profile in the session and display only the content that belongs to his profile by doing a jstl Choose :

    <c:choose>
    <c:when test="${sessionScope.perfil == 'Administrador' }">
     Parabéns,você é o administrador!

    </c:when>
    <c:otherwise>
    Que pena,você é apenas um usuario comun ç_ç!
    </c:otherwise>

    </c:choose>

maybe this post will help you...

  • 1

    Wow that’s right thanks man!

Browser other questions tagged

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