How do I get user id in a session?

Asked

Viewed 2,531 times

0

I am doing a project using jsp and Servlet, I need that when a user logs in, his id is saved in the session, so that with this id, the system knows that this id user is making changes to his data (example, phone change). How could I do that?

Control:

public void login(HttpServletRequest request, HttpServletResponse response) throws IOException, ClassNotFoundException, SQLException, ServletException{
    String login = request.getParameter("usuario");
    String senha = request.getParameter("senha");

    Usuario usuario = new Usuario();
    usuario.setEmail(login);
    usuario.setSenha(senha);

    UsuarioDAO usuarioDAO = new UsuarioDAO();
    Usuario usuarioAutenticado = usuarioDAO.validar(usuario);

    if (usuarioAutenticado !=null){
        HttpSession sessaoUsuario = request.getSession();
        sessaoUsuario.setAttribute("usuario",usuarioAutenticado);
        sessaoUsuario.setMaxInactiveInterval(10);
        response.sendRedirect("home.html");
    }else{
        response.sendRedirect("erroLogin.html");
    }
}

DAO:

public Usuario validar(Usuario usuario) throws ClassNotFoundException, SQLException{

    Connection con = FabricaConexao.getConexao();

    Usuario us= null;

    PreparedStatement comando = con.prepareStatement("select * from usuario where email = ? and senha=?");
    comando.setString(1,usuario.getEmail());
    comando.setString(2,usuario.getSenha());

    ResultSet resultado = comando.executeQuery();

    if (resultado.next()){
        us=new Usuario();
        us.setEmail(resultado.getString("email"));
        us.setSenha(resultado.getString("senha"));
        //us.setPerfilAcesso(resultado.getString("perfil_acesso"));

    }

    con.close();
    return us;
}

HTML:

<form role="form" action="login" method="POST" >
            <label for="usuario">Usuario (e-mail): </label><br>
            <input type="text" name="usuario" id=usuario required><br>
            <label for="senha">Senha </label><br>
            <input type="password" name="senha" id=senha required><br>

            <br><input type="submit" class="btn btn-login" value="Login">
            <br><a href=cadastroConta.html>Nao possui conta? Click aqui</a>
        </form>
  • session.setAttribute("usuario", id); where the "user" is the attribute you call when checking which user is on Session. That’s how I did in an application I needed to save the user in Session

1 answer

1


Celina, you already have the user ID saved in the session.

You see, when you put:

sessaoUsuario.setAttribute("usuario",usuarioAutenticado);

Hence, from this, you can recover the user ID at any time, either in Servlets or in JSP. You can do so:

Servlets

Usuario usuario = (Usuario)request.getAttribute("usuario");
Long id = usuario.getId(); //Aqui você ja tem o id do usuário

JSP (Using JSTL)

${sessionScope.usuario.id}

For security reasons, you can only post the ID, as @R.Santos suggested:

request.getSession().setAttribute("idUsuario", usuarioAutenticado.getId());

Since it is common for the user object to contain an attribute senha for example.

I hope I’ve helped.

  • I tested it here and it worked. The idea is to get jsp to retrieve the user id. This I did. Thank you! But just one more question, I used ${sessionScope.usuario.id} in jsp, now how can I send this id so that I can retrieve it in a Servlet (for example, this id user will register an address)?

  • The coolest thing about using you is that you don’t have to "send" a Servlet. What you can do is retrieve it in Servlet directly. (Remember that the Session scope is for all pages of a single session). Looks something like this: Usuario u = (Usuario) request.getSession().getAttribute("usuario");&#xA;u.getId(); //aqui voce tem o ID, faça o que quiser com ele.

  • worked here. Thank you!

Browser other questions tagged

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