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 onSession
. That’s how I did in an application I needed to save the user in Session– R.Santos