老杜 JavaWeb 讲解(十六) ——oa项目的改造(cookie)

(十五)oa项目的改造(cookie)

相关视频:

48-Cookie实现十天内免登录

十天内免登录功能:

使用cookie实现一下十天内免登录功能。

  • 先实现登录功能

    • 登录成功
      • 跳转到部门列表页面
    • 登录失败
      • 跳转到登录失败页面
  • 修改前端页面

    • 在登录页面给一个复选框,复选框后面给一句话:十天内免登录。
    • 用户选择了复选框:表示要支持十天内免登录。
    • 用户没有选择复选框:表示用户不想使用十天内免登录功能。
    <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
    <!DOCTYPE html>
    <html>
    <head>
    	<title>登录页面</title>
    	<style>
    		body {
    			background-color: #f5f5f5;
    			font-family: Arial, sans-serif;
    		}
    
    		.container {
    			max-width: 400px;
    			margin: 0 auto;
    			padding: 20px;
    			background-color: #ffffff;
    			border-radius: 8px;
    			box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    		}
    
    		h2 {
    			text-align: center;
    			color: #333333;
    		}
    
    		.form-group {
    			margin-bottom: 15px;
    		}
    
    		label {
    			display: block;
    			margin-bottom: 5px;
    			color: #666666;
    		}
    
    		input[type="text"],
    		input[type="password"] {
    			width: 90%;
    			padding: 10px;
    			border: 1px solid #dddddd;
    			border-radius: 4px;
    		}
    
    		button[type="submit"] {
    			display: block;
    			width: 100%;
    			padding: 10px;
    			background-color: #333333;
    			color: #ffffff;
    			border: none;
    			border-radius: 4px;
    			cursor: pointer;
    		}
    
    		button[type="submit"]:hover {
    			background-color: #222222;
    		}
    	</style>
    </head>
    <body>
    <br>
    <br>
    <br>
    <div class="container">
    	<h2>用户登录</h2>
    	<form action="<%=request.getContextPath()%>/user/login" method="post">
    		<!-- 用户名字段 -->
    		<div class="form-group">
    			<label for="username">用户名:</label>
    			<input type="text" id="username" name="username" required/>
    		</div>
    
    		<!-- 密码字段 -->
    		<div class="form-group">
    			<label for="password">密码:</label>
    			<input type="password" id="password" name="password" required/>
    		</div>
    		<input type="checkbox" name="f" value="1">10天内免登录
    		<!-- 提交按钮 -->
    		<button type="submit" value="login">登录</button>
    	</form>
    </div>
    </body>
    </html>
    
    
  • 修改Servlet中的login方法

    • 如果用户登录成功了,并且用户登录时选择了十天内免登录功能,这个时候应该在Servlet的login方法中创建cookie,用来存储用户名和密码,并且设置路径,设置有效期,将cookie响应给浏览器。(浏览器将其自动保存在硬盘文件当中10天)

      protected void deLogin(HttpServletRequest request, HttpServletResponse response)
          throws ServletException, IOException {
      String username = request.getParameter("username");
      String password = request.getParameter("password");
      
      Connection connection = null;
      PreparedStatement preparedStatement = null;
      ResultSet resultSet = null;
      
      boolean success = false;
      
      try {
          connection = DBUtil.getConnection();
          String sql = "select * from t_user where username =?and password1 =? ";
          preparedStatement = connection.prepareStatement(sql);
          preparedStatement.setString(1, username);
          preparedStatement.setString(2, password);
      
          //这个结果集中只有一条数据,不需要循环。
          resultSet = preparedStatement.executeQuery();
          if (resultSet.next()) {
              success = true;
          }
      } catch (SQLException e) {
          throw new RuntimeException(e);
      } finally {
          DBUtil.close(connection, preparedStatement, resultSet);
      }
      
      if (success) {
          //登录成功,获取session对象(要求必须获取session对象。)
          HttpSession session = request.getSession();
          session.setAttribute("username",username);
      
          //登录成功,并且用户确实选了这十天免登录功能,则需要创建cookie
          String f = request.getParameter("f");
          if("1".equals(f)){
              Cookie cookie1 = new Cookie("username",username);
              Cookie cookie2 = new Cookie("password",password);  //真实情况下需要加密。
      
              cookie1.setMaxAge(60*60*24*10);
              cookie2.setMaxAge(60*60*24*10);
      
              cookie1.setPath(request.getContextPath());
              cookie2.setPath(request.getContextPath());
      
              response.addCookie(cookie1);
              response.addCookie(cookie2);
          }
      
          //跳转列表页面
          response.sendRedirect(request.getContextPath() + "/dept/list");
      } else {
          //跳转错误页面
          response.sendRedirect(request.getContextPath() + "/error.jsp");
      }
      
      }
      
  • 用户再次访问该网站的时候,访问这个网站的首页的时候,有两个走向:

    • 要么跳转到部门列表页面

    • 要么跳转到登录页面

    • 以上分别有两个走向,这显然是需要编写java程序进行控制的。

      <welcome-file-list>
          <welcome-file>welcome</welcome-file>
      </welcome-file-list>
      
      package com.zwm.oa.web.action;
      
      import com.zwm.oa.utils.DBUtil;
      import jakarta.servlet.ServletException;
      import jakarta.servlet.annotation.WebServlet;
      import jakarta.servlet.http.*;
      
      import java.io.IOException;
      import java.sql.Connection;
      import java.sql.PreparedStatement;
      import java.sql.ResultSet;
      import java.sql.SQLException;
      
      
      @WebServlet("/welcome")
      public class WelcomeServlet extends HttpServlet {
          @Override
          protected void doGet(HttpServletRequest request, HttpServletResponse response)
                  throws ServletException, IOException {
              //这个cookies数组,要么是null,要么不为空。
              Cookie[] cookies = request.getCookies();
              String username = null;
              String password = null;
      
              if(cookies != null){
                  for (Cookie cookie : cookies) {
                      String name = cookie.getName();
                      if("username".equals(name)){
                          username = cookie.getValue();
                      }else if("password".equals(name)){
                          password = cookie.getValue();
                      }
                  }
              }
      
              if(username !=null && password !=null){
                  //验证用户名和密码是否正确
                  //正确,登录成功。
                  //失败,返回登录。
                  Connection connection = null;
                  PreparedStatement preparedStatement = null;
                  ResultSet resultSet = null;
                  boolean success = false;
      
                  try {
                      connection = DBUtil.getConnection();
                      String sql = "select * from t_user where username = ? and password1 = ?";
                      preparedStatement = connection.prepareStatement(sql);
                      preparedStatement.setString(1,username);
                      preparedStatement.setString(2,password);
                      resultSet=preparedStatement.executeQuery();
                      if (resultSet.next()) {
                          success = true;
                      }
      
                  } catch (SQLException e) {
                      throw new RuntimeException(e);
                  }finally {
                      DBUtil.close(connection,preparedStatement,resultSet);
                  }
      
                  if(success){
                      //登录成功,获取session对象(要求必须获取session对象。)
                      HttpSession session = request.getSession();
                      session.setAttribute("username",username);
      
                      response.sendRedirect(request.getContextPath()+"/dept/list");
                  }else {
                      response.sendRedirect(request.getContextPath()+"/index.jsp");
                  }
              }else {
                  response.sendRedirect(request.getContextPath()+"/index.jsp");
              }
          }
      }
      
      
  • 修改退出功能

        private void doExit(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException{
    
            Cookie[] cookies = request.getCookies();
    
            if (cookies != null) {
                for (Cookie cookie : cookies) {
                    // 设置过期时间为0
                    cookie.setMaxAge(0);
                    // 设置路径,确保与设置 cookie 时相同
                    cookie.setPath(request.getContextPath());
                    // 将修改后的 cookie 添加到 response 中
                    response.addCookie(cookie);
                }
            }
    
            HttpSession session = request.getSession();
            if(session !=null){
                //手动销毁session
                session.invalidate();
            }
            response.sendRedirect(request.getContextPath());
        }
    
  • 将部分原来跳转到登陆页面的代码更改为跳转到 /welcome。

        @Override
        protected void service(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            //获取session对象,有就拿,没有不拿(只是做判断用的,不需要重新建)。
            HttpSession session = request.getSession(false);
    
            if(session != null && session.getAttribute("username") !=null){
                String servletPath = request.getServletPath();
                if("/dept/list".equals(servletPath)){
                    doList(request,response);
                }else if("/dept/delete".equals(servletPath)){
                    doDel(request,response);
                }else if("/dept/detail".equals(servletPath)){
                    doDetail(request,response);
                }else if("/dept/save".equals(servletPath)){
                    doSave(request,response);
                }else if("/dept/modify".equals(servletPath)){
                    doModify(request,response);
                }
            }else {
                //跳转到登录页面
                System.out.println("跳转失败");
                response.sendRedirect(request.getContextPath()+"/welcome");
            }
        }
    






posted @ 2023-07-28 04:48  猪无名  阅读(13)  评论(0编辑  收藏  举报