鱼C论坛

 找回密码
 立即注册
查看: 501|回复: 6

[已解决]用session实现免登录

[复制链接]
发表于 2023-4-30 12:06:27 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
本帖最后由 她与晚风 于 2023-4-30 12:11 编辑

代码如下:
二次免登录页面:

package bj;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.*;

import java.io.IOException;
import java.sql.*;

@WebServlet({"/welcome"})
public class welcomePage extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Cookie[] cookies = request.getCookies();
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        HttpSession session = request.getSession();
        String sql;
        String username = null;
        String password = null;
        if(cookies != null) {
            for (Cookie cookie : cookies) {
                if ("username".equals(cookie.getName())) {
                    username = cookie.getName();
                }
                if ("password".equals(cookie.getValue())) {
                    password = cookie.getValue();
                }
            }
            if(username !=null && password != null){
                sql = "select * from t_login where username = ? and password = ?";
                System.out.println(username + ":    " + password);
                try {
                    Class.forName("com.mysql.cj.jdbc.Driver");
                    connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/myemployees", "root", "123456");
                    preparedStatement = connection.prepareStatement(sql);
                    preparedStatement.setString(1,username);
                    preparedStatement.setInt(2, Integer.parseInt(password));
                    resultSet = preparedStatement.executeQuery();
                   if(resultSet.next()){
                        System.out.println("登录成功");
                        connection.setAutoCommit(true);
                        session.setAttribute("username",username);
                        response.sendRedirect(request.getContextPath() + "/dept/List");
                        //可以执行到这里,到好像跳转的不是List页面,又回到了/index.jsp页面
                    }
else {
                        System.out.println("登录失败");
                        response.sendRedirect(request.getContextPath() + "/index.jsp");
                    }
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                } catch (ClassNotFoundException e) {
                    throw new RuntimeException(e);
                }

            }else {
                response.sendRedirect(request.getContextPath() + "/index.jsp");
            }
        }

                /*
                */
    }
}
最佳答案
2023-4-30 12:10:26
您的代码已经实现了免登录功能,这里是通过使用Session和Cookie来实现的。当用户登录后,服务器会将用户名和密码存储在Cookie中,然后在需要进行身份验证的页面,通过读取Cookie中的信息来实现自动登录。

代码的逻辑如下:

1. 获取请求中的所有Cookie。
2. 遍历这些Cookie,找到名为"username"和"password"的Cookie。
3. 如果找到了这两个Cookie,从这些Cookie中获取用户名和密码。
4. 使用获取到的用户名和密码查询数据库以验证用户身份。
5. 如果用户身份验证成功,将用户名存储在Session中,并将用户重定向到部门列表页面。
6. 如果身份验证失败,将用户重定向到登录页面。

为了让您的代码更清晰,我对您的代码进行了一些重构和注释:

  1. package bj;

  2. import jakarta.servlet.ServletException;
  3. import jakarta.servlet.annotation.WebServlet;
  4. import jakarta.servlet.http.*;

  5. import java.io.IOException;
  6. import java.sql.*;

  7. @WebServlet({"/welcome"})
  8. public class welcomePage extends HttpServlet {
  9.     @Override
  10.     protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  11.         Cookie[] cookies = request.getCookies();
  12.         Connection connection = null;
  13.         PreparedStatement preparedStatement = null;
  14.         ResultSet resultSet = null;
  15.         HttpSession session = request.getSession();
  16.         String sql;
  17.         String username = null;
  18.         String password = null;

  19.         // 从Cookie中获取用户名和密码
  20.         if (cookies != null) {
  21.             for (Cookie cookie : cookies) {
  22.                 if ("username".equals(cookie.getName())) {
  23.                     username = cookie.getValue();
  24.                 }
  25.                 if ("password".equals(cookie.getName())) {
  26.                     password = cookie.getValue();
  27.                 }
  28.             }
  29.         }

  30.         // 如果找到了用户名和密码,验证用户身份
  31.         if (username != null && password != null) {
  32.             sql = "select * from t_login where username = ? and password = ?";
  33.             System.out.println(username + ":    " + password);
  34.             try {
  35.                 Class.forName("com.mysql.cj.jdbc.Driver");
  36.                 connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/myemployees", "root", "123456");
  37.                 preparedStatement = connection.prepareStatement(sql);
  38.                 preparedStatement.setString(1, username);
  39.                 preparedStatement.setInt(2, Integer.parseInt(password));
  40.                 resultSet = preparedStatement.executeQuery();

  41.                 // 如果身份验证成功,将用户名存储在Session中,并重定向到部门列表页面
  42.                 if (resultSet.next()) {
  43.                     System.out.println("登录成功");
  44.                     connection.setAutoCommit(true);
  45.                     session.setAttribute("username", username);
  46.                     response.sendRedirect(request.getContextPath() + "/dept/List");
  47.                 } else {
  48.                     // 身份验证失败,重定向到登录页面
  49.                     System.out.println("登录失败");
  50.                     response.sendRedirect(request.getContextPath() + "/index.jsp");
  51.                 }
  52.             } catch (SQLException e) {
  53.                 throw new RuntimeException(e);
  54.             } catch (ClassNotFoundException e) {
  55.                 throw new RuntimeException(e);
  56.             }
  57.         } else {
  58.             // 没有找到用户名和密码,重定向到登录页面
  59.             response.sendRedirect(request.getContextPath() + "/index.jsp");
  60.         }
  61.     }
  62. }
复制代码


这样,您的代码会更易于阅读和理解。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2023-4-30 12:07:21 | 显示全部楼层
本帖最后由 她与晚风 于 2023-4-30 12:08 编辑

//Servlet代码主体

package bj;

import MyUtil.DepartmentUser;
import MyUtil.EmoloyeeUser;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.*;

import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;

@WebServlet({"/dept/List","/dept/Delete","/dept/Detail","/dept/Update","/dept/login"})
public class ServletList extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        String sql;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/myemployees","root","123456");
            if("/dept/List".equals(request.getServletPath())){
                HttpSession session = request.getSession(false);
                ///
                System.out.println(session);
                System.out.println(session.getAttribute("username"));
                ///
                if(session == null || session.getAttribute("username") == null){
                    //
                    System.out.println("执行了吗");
                    //
                    response.sendRedirect(request.getContextPath() + "/index.jsp");
                }else {
                    connection.setAutoCommit(false);
                    ArrayList<DepartmentUser> arrayList = new ArrayList<>();
                    sql = "select department_id,department_name,manager_id,city from departments e left join locations l on e.location_id = l.location_id";
                    preparedStatement = connection.prepareStatement(sql);
                    resultSet = preparedStatement.executeQuery();
                    while (resultSet.next()){
                        String department_id = resultSet.getString("department_id");
                        String department_name = resultSet.getString("department_name");
                        String manager_id = resultSet.getString("manager_id");
                        String city = resultSet.getString("city");
                        DepartmentUser departmentUser = new DepartmentUser(department_id,department_name,manager_id,city);
                        arrayList.add(departmentUser);
                    }
                    request.setAttribute("list",arrayList);
                    connection.setAutoCommit(true);
                    System.out.println("没毛病");
                    request.getRequestDispatcher("/deptList.jsp").forward(request,response);
                }
            } else if ("/dept/Delete".equals(request.getServletPath())) {
                HttpSession session = request.getSession(false);
                if(session == null || session.getAttribute("username") == null){
                    response.sendRedirect(request.getContextPath() + "/index.jsp");
                }else {
                    connection.setAutoCommit(false);
                    String department_id = request.getParameter("department_id");
                    sql = "delete from departments where department_id = ?";
                    preparedStatement = connection.prepareStatement(sql);
                    preparedStatement.setInt(1, Integer.parseInt(department_id));
                    int i = preparedStatement.executeUpdate();

                    sql = "delete from employees where department_id = ?";
                    preparedStatement = connection.prepareStatement(sql);
                    preparedStatement.setInt(1, Integer.parseInt(department_id));
                    int j = preparedStatement.executeUpdate();
                    connection.setAutoCommit(true);
                    if(i !=0 || j != 0){
                        System.out.println("操作成功");
                    }
                    response.sendRedirect(request.getContextPath() + "/dept/List");
                }

            } else if ("/dept/Detail".equals(request.getServletPath())) {
                HttpSession session = request.getSession(false);
                if(session == null || session.getAttribute("username") == null){
                    response.sendRedirect(request.getContextPath() + "/dept/index.jsp");
                }else {
                    connection.setAutoCommit(false);
                    ArrayList arrayList = new ArrayList();
                    String department_id = request.getParameter("department_id");
                    sql = "select employee_id,last_name,job_id,manager_id,department_id,hiredate from employees where department_id = ?";
                    preparedStatement = connection.prepareStatement(sql);
                    preparedStatement.setInt(1, Integer.parseInt(department_id));
                    resultSet = preparedStatement.executeQuery();
                    while (resultSet.next()){
                        String employee_id= resultSet.getString("employee_id");
                        String last_name = resultSet.getString("last_name");
                        String job_id = resultSet.getString("job_id");
                        String manager_id = resultSet.getString("manager_id");
                        department_id = resultSet.getString("department_id");
                        String hiredate = resultSet.getString("hiredate");
                        EmoloyeeUser emoloyeeUser = new EmoloyeeUser(employee_id,last_name,job_id,manager_id,department_id,hiredate);
                        arrayList.add(emoloyeeUser);
                        }
                        connection.setAutoCommit(true);
                        request.setAttribute("detail",arrayList);
                        request.getRequestDispatcher("/deptDetail.jsp").forward(request,response);
                }

            } else if ("/dept/Update".equals(request.getServletPath())) {
                HttpSession session = request.getSession(false);
                if(session == null || session.getAttribute("username") == null){
                    response.sendRedirect(request.getContextPath() + "/dept/index.jsp");
                }else {
                    connection.setAutoCommit(false);
                    String department_id = request.getParameter("department_id");
                    System.out.println(department_id);
                    String department_name = request.getParameter("department_name");
                    String manager_id = request.getParameter("manager_id");
                    String city = request.getParameter("city");


                    sql = "update departments set department_name = ?,manager_id = ? where department_id = ?";
                    preparedStatement = connection.prepareStatement(sql);
                    preparedStatement.setString(1,department_name);
                    preparedStatement.setInt(2, Integer.parseInt(manager_id));
                    preparedStatement.setInt(3, Integer.parseInt(department_id));
                    int j = preparedStatement.executeUpdate();


                    sql = "update locations set city = ? where location_id = (select location_id from departments where department_id = ?)";
                    preparedStatement = connection.prepareStatement(sql);
                    preparedStatement.setString(1,city);
                    preparedStatement.setInt(2, Integer.parseInt(department_id));
                    int i = preparedStatement.executeUpdate();
                    if(i != 0 && j != 0){
                        System.out.println("修改成功");
                    }
                    connection.setAutoCommit(true);

                    response.sendRedirect(request.getContextPath() + "/dept/List");
                }

            } else if ("/dept/login".equals(request.getServletPath())) {
                HttpSession session = request.getSession();
                String username = request.getParameter("username");
                String password = request.getParameter("password");
                String flag = request.getParameter("flag");
                System.out.println(flag + "lll");
                if("1".equals(flag)){
                    Cookie cookie1 = new Cookie("username",username);
                    cookie1.setMaxAge(180);
                    cookie1.setPath(request.getContextPath());
                    response.addCookie(cookie1);
                    Cookie cookie2 = new Cookie("password",password);
                    cookie2.setMaxAge(180);
                    cookie2.setPath(request.getContextPath());
                    response.addCookie(cookie2);

                }

                sql = "select * from t_login where username = ? and password = ?";
                preparedStatement = connection.prepareStatement(sql);
                preparedStatement.setString(1,username);
                preparedStatement.setInt(2, Integer.parseInt(password));
                resultSet = preparedStatement.executeQuery();
                if(resultSet.next()){
                    System.out.println("登录成功");
                    connection.setAutoCommit(true);
                    session.setAttribute("username",username);
                    //aaaaaaaaaaaaaa
                    System.out.println("-----------------------------------");
                    response.sendRedirect(request.getContextPath() + "/dept/List");
                }else {
                    System.out.println("登录失败");
                }
            }
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (SQLException e) {
            try {
                connection.rollback();
            } catch (SQLException ex) {
                throw new RuntimeException(ex);
            }
            throw new RuntimeException(e);
        }finally {
            if(resultSet != null){
                try {
                    resultSet.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
            if(preparedStatement != null){
                try {
                    preparedStatement.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
            if(connection != null){
                try {
                    connection.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }
}
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2023-4-30 12:09:25 | 显示全部楼层
我的这个页面登录二次跳转有问题
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

匿名鱼油
匿名鱼油  发表于 2023-4-30 12:10:26    本楼为最佳答案   
您的代码已经实现了免登录功能,这里是通过使用Session和Cookie来实现的。当用户登录后,服务器会将用户名和密码存储在Cookie中,然后在需要进行身份验证的页面,通过读取Cookie中的信息来实现自动登录。

代码的逻辑如下:

1. 获取请求中的所有Cookie。
2. 遍历这些Cookie,找到名为"username"和"password"的Cookie。
3. 如果找到了这两个Cookie,从这些Cookie中获取用户名和密码。
4. 使用获取到的用户名和密码查询数据库以验证用户身份。
5. 如果用户身份验证成功,将用户名存储在Session中,并将用户重定向到部门列表页面。
6. 如果身份验证失败,将用户重定向到登录页面。

为了让您的代码更清晰,我对您的代码进行了一些重构和注释:

  1. package bj;

  2. import jakarta.servlet.ServletException;
  3. import jakarta.servlet.annotation.WebServlet;
  4. import jakarta.servlet.http.*;

  5. import java.io.IOException;
  6. import java.sql.*;

  7. @WebServlet({"/welcome"})
  8. public class welcomePage extends HttpServlet {
  9.     @Override
  10.     protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  11.         Cookie[] cookies = request.getCookies();
  12.         Connection connection = null;
  13.         PreparedStatement preparedStatement = null;
  14.         ResultSet resultSet = null;
  15.         HttpSession session = request.getSession();
  16.         String sql;
  17.         String username = null;
  18.         String password = null;

  19.         // 从Cookie中获取用户名和密码
  20.         if (cookies != null) {
  21.             for (Cookie cookie : cookies) {
  22.                 if ("username".equals(cookie.getName())) {
  23.                     username = cookie.getValue();
  24.                 }
  25.                 if ("password".equals(cookie.getName())) {
  26.                     password = cookie.getValue();
  27.                 }
  28.             }
  29.         }

  30.         // 如果找到了用户名和密码,验证用户身份
  31.         if (username != null && password != null) {
  32.             sql = "select * from t_login where username = ? and password = ?";
  33.             System.out.println(username + ":    " + password);
  34.             try {
  35.                 Class.forName("com.mysql.cj.jdbc.Driver");
  36.                 connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/myemployees", "root", "123456");
  37.                 preparedStatement = connection.prepareStatement(sql);
  38.                 preparedStatement.setString(1, username);
  39.                 preparedStatement.setInt(2, Integer.parseInt(password));
  40.                 resultSet = preparedStatement.executeQuery();

  41.                 // 如果身份验证成功,将用户名存储在Session中,并重定向到部门列表页面
  42.                 if (resultSet.next()) {
  43.                     System.out.println("登录成功");
  44.                     connection.setAutoCommit(true);
  45.                     session.setAttribute("username", username);
  46.                     response.sendRedirect(request.getContextPath() + "/dept/List");
  47.                 } else {
  48.                     // 身份验证失败,重定向到登录页面
  49.                     System.out.println("登录失败");
  50.                     response.sendRedirect(request.getContextPath() + "/index.jsp");
  51.                 }
  52.             } catch (SQLException e) {
  53.                 throw new RuntimeException(e);
  54.             } catch (ClassNotFoundException e) {
  55.                 throw new RuntimeException(e);
  56.             }
  57.         } else {
  58.             // 没有找到用户名和密码,重定向到登录页面
  59.             response.sendRedirect(request.getContextPath() + "/index.jsp");
  60.         }
  61.     }
  62. }
复制代码


这样,您的代码会更易于阅读和理解。
回复 支持 反对

使用道具 举报

发表于 2023-4-30 12:16:02 | 显示全部楼层
匿名者 发表于 2023-4-30 12:10
您的代码已经实现了免登录功能,这里是通过使用Session和Cookie来实现的。当用户登录后,服务器会将用户名 ...

iskdz
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 1 反对 0

使用道具 举报

 楼主| 发表于 2023-4-30 12:16:44 | 显示全部楼层
匿名者 发表于 2023-4-30 12:10
您的代码已经实现了免登录功能,这里是通过使用Session和Cookie来实现的。当用户登录后,服务器会将用户名 ...

厉害了哥,可以了,就是欢迎页面有问题
请问一下我写的那个有什么问题呢
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2023-4-30 12:30:35 | 显示全部楼层
匿名者 发表于 2023-4-30 12:10
您的代码已经实现了免登录功能,这里是通过使用Session和Cookie来实现的。当用户登录后,服务器会将用户名 ...

哦哦
username = cookie.getValue();
我这一步写错了
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-4-27 14:18

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表