HttpSession保存用户登录状态
-
登录
-
登录成功后将已登录状态保存到session中
-
当用户点击显示员工列表的时候,验证用户是否为登录成功状态,如果是显示员工列表,不是跳转到登录界面。
-
安全退出系统
* 代码 1 登录并获取Session,将用户登录信息封装进session中
```
import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.io.IOException;
import java.sql.*;
public class LoginServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//创建登录成功标识
boolean loginFlag = false;
//获取用户form表单提交数据
String userEmail = request.getParameter("email");
String userPwd = request.getParameter("password");
//创建用户对象
User user=null;
//创建数据库连接对象
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
//注册驱动
Class.forName("com.mysql.cj.jdbc.Driver");
// 获取连接
connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/mydb?useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai",
"root", "123456");
//创建预编译数据库操作对象
String sql = "select username,email,userpwd from t_userinfo where email=? and userpwd=?";
preparedStatement = connection.prepareStatement(sql);
//给预编译数据库操作对象传参
preparedStatement.setString(1, userEmail);
preparedStatement.setString(2, userPwd);
//执行sql语句
resultSet = preparedStatement.executeQuery();
//处理查询结果集
while (resultSet.next()) {
//登录成功将登录标识改为true
loginFlag = true;
//登录成功将用户信息包装到实体对象中
user=new User();
user.setUserName(resultSet.getString("username"));
user.setUserEmail(resultSet.getString("email"));
user.setUserPwd(resultSet.getString("userpwd"));
}
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
} finally {
//释放资源
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (preparedStatement != null) {
try {
preparedStatement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (loginFlag) {
//登录成功
/*
//登录成功后 查看用户是否选择了自动登录的按钮,如果选择了发送Cookie给浏览器
String tenDayAutoLogin = request.getParameter("tenDayAutoLogin");
System.out.println(tenDayAutoLogin);
if ("ok".equals(tenDayAutoLogin)) {
//说明用户勾选了十天内免登录的选项
//创建Cookie对象
Cookie cookie1 = new Cookie("userEmail", userEmail);
Cookie cookie2 = new Cookie("userPwd", userPwd);
//设置Cookie有效时间
cookie1.setMaxAge(60 * 60 * 24 * 10);
cookie2.setMaxAge(60 * 60 * 24 * 10);
//设置Cookie关联路径
cookie1.setPath(request.getContextPath());
cookie2.setPath(request.getContextPath());
//将Cookie对象发送给浏览器
response.addCookie(cookie1);
response.addCookie(cookie2);
//跳转
response.sendRedirect("/myWeb/LoginSuccess.html");
}else{
//跳转到显示员工列表页
response.sendRedirect("/myWeb/LoginSuccess.html");
}*/
//登录成功
if(user!=null){
//登录成功后 将登陆成功状态保存
HttpSession session=request.getSession(); //获取Session
//存储用户登录状态
session.setAttribute("user",user);
//跳转到显示员工列表页
response.sendRedirect("/myWeb/LoginSuccess.html");
}
}else{
//登录失败,跳转登录失败页面
response.sendRedirect("/myWeb/loginError.html");
}
}
}
}
* 代码 2 判断Session中是否存储了用户的登录信息,有的话显示员工列表 ,没有的话跳转登录页面
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
public class ShowEmployeeServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//通过Session判断用户登录状态
HttpSession session=request.getSession(false);
//获取Session范围内的数据,判断是否为空,不为空代码登陆了,就继续执行
if(session!=null && session.getAttribute("user")!=null){
//防止乱码
response.setContentType("text/html;charset=utf-8");
//创建字符输出流
PrintWriter printWriter=response.getWriter();
//HTML代码
printWriter.print(" <!DOCTYPE html>");
printWriter.print("<meta http-equiv=\"content-type\" content=\"text/html\" charset=\"utf-8\"/> ");
printWriter.print(" <head>");
printWriter.print(" <meta charset='UTF-8'>");
printWriter.print(" <title>员工信息</title>");
printWriter.print(" </head>");
printWriter.print(" <body>");
printWriter.print(" <h3 align='center'>员工信息表</h3>");
printWriter.print(" <hr width='60%'>");
printWriter.print(" <table border='1' align='center' width='50%'>");
printWriter.print(" <tr align='center'>");
printWriter.print(" <th>序号</th>");
printWriter.print(" <th>员工编号</th>");
printWriter.print(" <th>员工姓名</th>");
printWriter.print(" <th>员工薪酬</th>");
printWriter.print(" <th>员工岗位</th>");
printWriter.print(" </tr>");
//创建数据库连接对象
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet=null;
try {
//注册驱动
Class.forName("com.mysql.cj.jdbc.Driver");
// 获取连接
connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/employ?useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai",
"root", "123456");
//获取预编译对象
String sql="select empno,ename,sal,job from emp";
preparedStatement=connection.prepareStatement(sql);
//执行SQL语句
resultSet=preparedStatement.executeQuery();
//处理查询结果集
int i=1;
while(resultSet.next()){
String empno=resultSet.getString("empno");
String name=resultSet.getString("ename");
String sal=resultSet.getString("sal");
String job=resultSet.getString("job");
printWriter.print(" <tr align='center'>");
printWriter.print(" <th>"+(i++)+"</th>");
printWriter.print(" <th>"+empno+"</th>");
printWriter.print(" <th>"+name+"</th>");
printWriter.print(" <th>"+sal+"</th>");
printWriter.print(" <th>"+job+"</th>");
printWriter.print(" </tr>");
}
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
} finally {
//释放资源
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (preparedStatement != null) {
try {
preparedStatement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
printWriter.print(" </table>");
printWriter.print(" </body>");
printWriter.print(" </html>");
}
}else{
// session为空,不是登录状态,跳转到登录界面
response.sendRedirect("/myWeb/login.html");
}
}
}
* 代码3 用户点击安全退出 销毁Session,跳转登录页
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
public class LogoutServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获取Session
HttpSession session=request.getSession(false);
//销毁Session
if(session!=null){
session.invalidate();
response.sendRedirect("/myWeb/login.html");
}
}
}