使用ChatGPT生成登录产品代码

本文涉及的产品
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
云数据库 RDS MySQL,集群系列 2核4GB
推荐场景:
搭建个人博客
RDS MySQL Serverless 高可用系列,价值2615元额度,1个月
简介: 使用ChatGPT生成登录产品代码

9.1 前端代码

9.1.1 申请产生登录HTML代码

代码语言:javascript

复制

function validateForm() {    …}

代码语言:javascript

复制

<style>        body {            …        }</style>

产生登录的页面,包括用户名输入框。

为了与注册页面一致,申请产生登录页面的时候需要把密码输入框和登录按钮JavaScript与CSS文件给出。

9.1.2产生登录HTML代码回复

为了创建一个简单的登录页面,包括用户名输入框、密码输入框和登录按钮,我们可以在现有的代码基础上进行扩展。下面是一个完整的HTML示例,它包含了登录表单的结构以及相应的CSS样式。

1)HTML (login.html)

代码语言:javascript

复制

<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.0.0/crypto-js.min.js"></script>
    <title>登录页面</title>
    <link rel="stylesheet" href="css/index.css">
  <script src="js/index.js" type="text/javascript"></script>
</head>
<body>
    <div class="container">
        <h2>登录</h2>
        <form id="loginForm" onsubmit="return validateLoginForm()">
            <div>
                <label for="username">用户名:</label>
                <input type="text" id=“username” name=“username” placeholder=“输入账号”  required>
                <div id="usernameError" class="error"></div>
            </div>
            <div>
                <label for="password">密码:</label>
                <input type="password" id=“password” name=“password” placeholder=“输入密码” required>
                <div id="passwordError" class="error"></div>
            </div>
            <button type="submit">登录</button>
        </form>
    </div>
</body>
</html>

2)JavaScript (index.js)

在index.js中,我们可以添加一个validateLoginForm函数来验证登录表单。以下是一个简单的示例:

代码语言:javascript

复制

function validateLoginForm() {
    const username = document.getElementById('username').value;
    const password = document.getElementById('password').value;
 
    let isValid = true;
    clearErrorMessages(); // 清空所有错误信息
 
    // 用户名简单验证
    if (username.trim() === '') {
        showError('usernameError', '用户名不能为空');
        isValid = false;
    }
 
    // 密码简单验证
    if (password.trim() === '') {
        showError('passwordError', '密码不能为空');
        isValid = false;
    }
 
    if (isValid) {
        // 获取密码并进行SHA-256哈希
        let hashedPassword = CryptoJS.SHA256(password).toString(CryptoJS.enc.Base64);
        
        // 这里可以添加登录逻辑,比如发送请求到服务器
        console.log('加密后的密码:', hashedPassword);
        console.log('登录成功!');
    }
 
    return isValid;
}

3)CSS (index.css)

在现有的CSS中,可以保留相同的样式,确保输入框和按钮的外观一致。以下是完整的CSS样式:

与现有的index.css一致

9.1.3 调整登录HTML代码回复

1)调整login.html

① 修改HTML (login.html)头部

代码语言:javascript

复制

<!DOCTYPE html>
<link rel="stylesheet" href="css/index.css">
<script src="index.js" type="text/javascript"></script>
<form id="loginForm" onsubmit="return validateLoginForm()">

代码语言:javascript

复制

<!DOCTYPE html>
<link rel="stylesheet" href="css/index.css">
<script src="js/index.js" type="text/javascript"></script>
<form id="loginForm" name="loginForm" method="POST" action="jsp/login.jsp" onsubmit="return validateLoginForm();">

② 在<button type="submit">登录</button>后面加入

代码语言:javascript

复制

<div id="loginError" class="error"></div>

4. 注意事项

l请确保在使用前将数据库连接中的用户名和密码替换为实际的数据库凭据。

l该示例使用了简单的SQL查询,建议在实际应用中使用密码哈希存储和验证,以提高安全性。

l本示例没有包括错误处理和输入验证的最佳实践,实际开发中应加强这些措施。

9.2.3登录后端代码调整

1)User.java原先User已经包含,不进行调整。

2)DBUtil.java原先DBuse已经包含,不进行调整。

3)合并login.jsp对数据库的处理到DBuser.java中。修改login.jsp。

代码语言:javascript

复制

<%@ page contentType="text/html; charset=utf-8" %>
<%@ page import="java.sql.*, javax.sql.*" %>
<%@ page import="ebusiness.*" %>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="../css/index.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.0.0/crypto-js.min.js"></script>
 <script src="https://cdn.jsdelivr.net/npm/crypto-js@4.1.1/core.js"></script>
<script src="https://cdn.jsdelivr.net/npm/crypto-js@4.1.1/sha256.js"></script>
<title>登录页面</title>
<script src="../js/index.js" type="text/javascript"></script>
</head>
<body>
<div class="container">
<h2>登录</h2>
<form id="loginForm" method="POST" name="loginForm" action="login.jsp" onsubmit="return validateLoginForm();">
<div>
<label for="username">用户名:</label>
<input type="text" id=“username” name=“username” placeholder=“输入账号” required>
<div id="usernameError" class="error"></div>
</div>
<div>
<label for="password">密码:</label>
<input type="password" id=“password” name=“password” placeholder=“输入密码” required>
<div id="passwordError" class="error"></div>
</div>
<button type="submit">登录</button>
</form>
<div id="loginError" class="error">
<%
String username = request.getParameter("username");
String password = request.getParameter("password");
User user = new User();
user.setUsername(username);
user.setPassword(password);
if (username != null && password != null) {
try {
DBuser mysql = new DBuser();
Connection conn = mysql.connect();
if (mysql.login(conn, user).equals("0"))
out.println("用户名或密码错误");
else
response.sendRedirect("welcome.jsp");
} catch (SQLException e) {
e.printStackTrace();
} finally {
out.println("");
      }
}
%>
</div>
</div>
</body>
</html>

4)在DBuse.java中添加login()方法。

代码语言:javascript

复制

public String login(Connection conn, User user) throws SQLException {
           String username=user.getUsername();
           String password=user.getPassword();
        PreparedStatement stmt = null;
        ResultSet rs = null;
        try {
               String queryString = "SELECT * FROM user WHERE username=? AND password=?";
               stmt = conn.prepareStatement(queryString);
            stmt.setString(1, username);
            stmt.setString(2, password);
            rs = stmt.executeQuery();           
            if (!rs.next()) {
                return "0";
            } else {
                   return "1";
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                if (rs != null) rs.close();
                if (stmt != null) stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return "-1";
}

9.3.4 在登录代码中用cookies加入登录标记信息

1)修改login.jsp

代码语言:javascript

复制

}else{
       out.println(mysql.login(conn, user));
       Cookie myCookie = new Cookie("username", username);
       myCookie.setMaxAge(60 * 60 * 24); // 设置为1天,单位是秒
       myCookie.setPath("/");
       response.addCookie(myCookie);
       response.sendRedirect("welcome.jsp");
}

2)建立welcome.jsp初稿

代码语言:javascript

复制

<%@ page contentType="text/html; charset=utf-8" %>
<%@ page import="ebusiness.CookiesManager" %>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="../css/index.css">
<script src="../js/index.js" type="text/javascript"></script>
<title>系统欢迎您</title>
</head>
<body>
<%
CookiesManager myusername = new CookiesManager("username",response,request);
String currentusername=myusername.getCookie();
if (currentusername==null){
response.sendRedirect("login.jsp");
}else{
%>
<h1>系统欢迎您</h1>
欢迎<%=currentusername%>进入XXX系统
<a href="logout.jsp">登出</a>
<%
}
%>
</body>
</html>

3)建立logout.jsp

代码语言:javascript

复制

<%@ page contentType="text/html; charset=utf-8" %>
<!DOCTYPE html>
<html>
<head>
    <title>欢迎进入</title>
  <link rel="stylesheet" href="../css/index.css">
  <script src="../js/index.js" type="text/javascript"></script>
</head>
<body>
<%
boolean judeg=false;
String currentusername="";
Cookie[] cookies = request.getCookies(); // 获取所有的cookies
if (cookies != null) {
    for (Cookie cookie : cookies) {
        String name = cookie.getName(); // 获取cookie的名称
        String value = cookie.getValue(); // 获取cookie的值
    if (name.equals("username") &&(value!=null)||(value.equals(""))){
      judeg=true;
      currentusername=value;
    }
    }
}
if(judeg){
%>
欢迎<%=currentusername%>登录XXXX系统
<a href="logout.jsp">登出</a>
<%
}else{
  response.sendRedirect("../login.html");
} 
%>
</body>
</html>

9.3.5去除login.html

1)去除login.html,通过jsp/login.jsp登录。

2)使用已经存在的用户名/密码登录,登录成功。

3)使用不已经存在的用户名/密码登录,显示错误信息。

4)修改register.jsp

所有

代码语言:javascript

复制

response.sendRedirect("../login.html");

代码语言:javascript

复制

response.sendRedirect("login.jsp");

5)logout.jsp

代码语言:javascript

复制

response.sendRedirect("../login.html");

代码语言:javascript

复制

response.sendRedirect("login.jsp");

6)运行Test_register_GUI.py和TestEbuxiness.py,测试通过。

9.3.6 加入CSRF cookies

1)修改CsrfTokenManager.java为CookiesManager.java

代码语言:javascript

复制

package ebusiness;
 
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletRequest;
 
public class CookiesManager {
       private HttpServletResponse response;
       private HttpServletRequest request;
       private String cookies_name;
       private String cookies_value;
 
    // 构造函数,接受 cookies 和 response 对象
    public CookiesManager(String cookies_name,String cookies_value, HttpServletResponse response,HttpServletRequest request) {
           this.cookies_name = cookies_name;
        this.cookies_value = cookies_value;
        this.response = response;
        this.request = request;
    }
    
    public CookiesManager(String cookies_name, HttpServletResponse response,HttpServletRequest request) {
           this.cookies_name = cookies_name;
        this.response = response;
        this.request = request;
    }
 
    // 设置cookies的方法
    public void setCookie() {
        if (this.cookies_value != null && !this.cookies_value.isEmpty()) {
            // 创建一个新的 Cookie
            Cookie myCookie = new Cookie(this.cookies_name, this.cookies_value);
            // 设置 Cookie 的有效期为 1 天(单位是秒)
            myCookie.setMaxAge(60 * 60 * 24);
            // 设置 Cookie 的路径
            myCookie.setPath("/");
            // 如果使用 HTTPS,确保 Cookie 只通过安全连接发送
            myCookie.setSecure(true);
            // 防止客户端脚本访问 Cookie
            myCookie.setHttpOnly(true);
            // 将 Cookie 添加到响应中
            response.addCookie(myCookie);
        } else {
            // 处理cookies为空的情况
            System.out.println("cookie is null or empty.");
        }
    }
    
    // 获取cookies的方法
    public String getCookie() {
           Cookie[] cookies = this.request.getCookies(); // 获取所有的cookies
              if (cookies != null) {
                     for (Cookie cookie : cookies) {
                            String name = cookie.getName(); // 获取cookie的名称
                            String value = cookie.getValue(); // 获取cookie的值
                            if (name.equals(this.cookies_name) && (value != null)  && (!value.isEmpty())){
                                   this.cookies_value=value;
                            }
                     }                     
              }
              return this.cookies_value;
    }
}

2)修改register.jsp

代码语言:javascript

复制

<%@ page contentType="text/html; charset=utf-8" %>
<%@ page import="java.sql.*, ebusiness.DBuser, ebusiness.validateUser, ebusiness.Util, ebusiness.User,ebusiness.CookiesManager" %>
        CookiesManager ct = new CookiesManager("csrftoken",csrftoken, response,request);
                     String method = request.getMethod();
                     if ("get".equalsIgnoreCase(method)) {
                            ct.setCookie();
                     }else if("post".equalsIgnoreCase(method)){
                            ct.setCookie();
3)修改login.jsp
<%@ page contentType="text/html; charset=utf-8" %>
<%@ page import="java.sql.*, ebusiness.DBuser, ebusiness.validateUser, ebusiness.Util, ebusiness.User,ebusiness.CookiesManager" %>
<%
                     <%
                     CookiesManager ct = new CookiesManager("csrftoken",csrftoken, response,request);
                     String method = request.getMethod();
                     if ("get".equalsIgnoreCase(method)) {
                            ct.setCookie();
                     }else if("post".equalsIgnoreCase(method)){
ct.setCookie();
if((csrftoken_cookies.equals(csrftoken_post))&&(csrftoken_cookies!=null)&&(csrftoken_cookies.length() > 0)){
CookiesManager myusername = new CookiesManager("username",username, response,request);
myusername.setCookie();
response.sendRedirect("welcome.jsp");
}

9.3.7 根据login.jsp调整register.jsp

1)申请根据login.jsp,调整register.jsp

根据login.jsp

调整register.jsp

2)根据login.jsp,调整register.jsp回复

为了调整 login.jsp 和 register.jsp 中的错误信息显示逻辑,我们可以确保在登录或注册失败时,错误信息能够正确地显示在指定的

元素中。下面是对两个页面的修改建议。

调整后的 login.jsp

调整后的 register.jsp

代码语言:javascript

复制

<%@ page contentType="text/html; charset=utf-8" %><%@ page import="java.sql.*, ebusiness.DBuser, ebusiness.validateUser, ebusiness.Util, ebusiness.User,ebusiness.CookiesManager" %>         <meta              </metacharset="UTF-8">         <meta              </metaname="viewport" content="width=device-width, initial-scale=1.0">             <link              </linkrel="stylesheet" type="text/css" href="../css/index.css"/>         <              </src="../js/index.js" type="text/javascript">         <              </src="../js/showerror.js" type="text/javascript">         <              </src="https://cdn.jsdelivr.net/npm/crypto-js@4.1.1/core.js">         <              </src="https://cdn.jsdelivr.net/npm/crypto-js@4.1.1/sha256.js"><%Util util = new Util();String csrftoken=util.generateRandomString(100);%>    用户注册          <form                </formname="myForm" method="POST" action="register.jsp" onsubmit="return validateForm();">                         <label                </labelfor="username">账号 (5-20位字母或数字):              <input                </inputtype="text" id="username" name="username" placeholder="输入账号" required>              <div                </divid="usernameError" class="error">              <label              </labelfor="password">密码 (5-30位,包含大小写字母、数字和特殊字符):             <input              </inputtype="password" id="password" name=“password” placeholder=“输入密码” required>             <div              </divid="passwordError" class="error">
 
            <label            </labelfor="confirmPassword">密码确认:
            <input            </inputtype="password" id="confirmPassword" name="confirmPassword"  placeholder="输入确认密码" required>
            <div            </divid="confirmPasswordError" class="error">
 
            <label            </labelfor="phone">手机号 (中国):
            <input            </inputtype="tel" id="phone" name="phone"  placeholder="输入手机号" required>
            <div            </divid="phoneError" class="error">
 
            <label            </labelfor="email">邮箱:
            <input            </inputtype="email" id="email" name="email"  placeholder="输入邮箱" required>
            <div            </divid="emailError" class="error">
 
            <button            </buttontype="submit">注册
    
 
        <div            </divid="registerError" class="error">
        <%
                     CookiesManager ct = new CookiesManager("csrftoken",csrftoken, response,request);
                     String method = request.getMethod();
                     if ("get".equalsIgnoreCase(method)) {
                            ct.setCookie();
                     }else if("post".equalsIgnoreCase(method)){
                            String csrftoken_post = request.getParameter("csrftoken");
                            String username = request.getParameter("username");
                            String password = request.getParameter("password");
                            String phone = request.getParameter("phone");
                            String email = request.getParameter("email");
                            String csrftoken_cookies = ct.getCookie();
                            ct.setCookie();
                            if((csrftoken_cookies.equals(csrftoken_post))&&(csrftoken_cookies!=null)&&(csrftoken_cookies.length() > 0)){                     
                                   User user = new User();
                                   user.setUsername(username);
                                   user.setPassword(password);
                                   user.setPhone(phone);
                                   user.setEmail(email);
                                   validateUser vu = new validateUser();
                                   String validationResult = vu.validate(user);
                                   if (!validationResult.equals("验证成功")) {
                                          out.print(validationResult);
                                   }else {
                                          try {
                                                 DBuser mysql = new DBuser();
                                                 Connection conn = mysql.connect();
                                                 String info = mysql.insert(conn, user);
                                                 if (info.equals("1")) {
                                                        response.sendRedirect("login.jsp");
                                                 } else {
                                                        out.println(info);
                                                 }
                                                 mysql.disconnect(conn);
                                          } catch (Exception e) {
                                                 out.println("数据库错误: " + e.getMessage());
                                          }
                                   }
                            }else{
                                   response.sendRedirect("login.jsp");
                            }
                     }
        %>

主要修改点

错误信息显示: 在login.jsp和register.jsp中,错误信息现在会显示在指定的

元素中。

输入验证: 在register.jsp中,如果用户输入的内容不符合要求,会立即显示验证结果。

代码清晰度: 通过将错误信息的逻辑集中在

中,使得代码的可读性更强,同时也更容易进行后续的调试和维护。

这样做确保了用户在登录或注册时能够看到清晰的反馈信息,提升了用户体验。

3)根据回复进行调整

在这里只考虑register.jsp。

① 修改DBuser类中的insert()函数。

代码语言:javascript

复制

public String userExists(Connection conn, String username, String email, String phone) throws SQLException {  
      if (!judgeInfo(conn,"username",username).equals("0"))
        return "注册用户的用户名必须唯一";
      else if(!judgeInfo(conn,"phone",phone).equals("0"))
        return "注册用户的手机必须唯一";
      else if(!judgeInfo(conn,"email",email).equals("0"))
          return "注册邮箱的手机必须唯一";
      else
        return "0";
    }

② 修改register.jsp中

代码语言:javascript

复制

try {
        DBuser mysql = new DBuser();
        Connection conn = mysql.connect();
        String info = mysql.insert(conn, user);
        if (info.equals("1")) {
                out.println("注册成功");
        } else {
                out.println(info);
        }

代码语言:javascript

复制

try {
        DBuser mysql = new DBuser();
        Connection conn = mysql.connect();
        String info = mysql.insert(conn, user);
        if (info.equals("1")) {
                response.sendRedirect("login.jsp");
        } else {
                out.println(info);
        }

另外去掉showerror.js文件。

③ 更新测试代码TestEbuxiness.py。

代码语言:javascript

复制

import requests
import unittest
import hashlib
import re
from Util import ClassDB
def hash_password(password):
    """对密码进行SHA256散列"""
    return hashlib.sha256(password.encode('utf-8')).hexdigest()
class TestUserRegistration(unittest.TestCase):
    # 注册接口的URL
    def setUp(self):
        self.REGISTER_URL = "http://127.0.0.1:8080/CharGPTEbusiness/jsp/register.jsp"
        # 注册接口的URL
        self.login_url ="http://127.0.0.1:8080/CharGPTEbusiness/register.jsp"
        self.session = requests.Session()
        response = self.session.get(self.login_url)
    def tearDown(self):
        ClassDB.init_db()
    def test_valid_username(self):
        """TC1: 测试有效的账号(5-20位字母或数字)"""
        self.assertIn("<form id=\"loginForm\"", response.text)
    def test_username_too_short(self):
        """TC2: 测试账号长度不足(少于5位)"""
        self.assertIn("账号必须是5-20位字母或数字", response.text)
    def test_username_too_long(self):
        """TC3: 测试账号长度超出(超过20位)"""
        self.assertIn("账号必须是5-20位字母或数字", response.text)
    def test_valid_password_registration(self):
        """TC4: 输入符合要求的密码,预期结果:注册成功"""
        self.assertIn("<form id=\"loginForm\"", response.text)
    def test_valid_mobile_number(self):
        """TC9: 输入有效的中国手机号码,预期结果:注册成功"""
        self.assertIn("<form id=\"loginForm\"", response.text)
    def test_invalid_mobile_number_format(self):
        """TC10: 输入非法的手机号码格式,预期结果:显示错误信息'手机号格式错误'"""
        self.assertIn("手机号必须符合中国手机号码格式", response.text)
    def test_valid_email(self):
        """TC11: 输入有效的邮箱地址,预期结果:注册成功"""
        self.assertIn("<form id=\"loginForm\"", response.text)
    def test_invalid_email_format(self):
        """TC12: 输入非法的邮箱格式,预期结果:显示错误信息'邮箱格式错误'"""
        self.assertIn("Email格式不正确", response.text)
    def test_duplicate_username_registration(self):
        """TC13: 同名用户注册测试"""
        self.assertIn("注册用户的用户名必须唯一",response2.text)
    def test_duplicate_email_registration(self):
        """TC14: 重复邮箱注册测试"""
        self.assertIn("注册用户的邮箱必须唯一",response.text)
    def test_duplicate_phone_registration(self):
        """TC15: 重复手机号注册测试"""
        self.assertIn("注册用户的手机必须唯一",response.text)
if __name__ == "__main__":
    unittest.main()

④ 修改Test_register_GUI.py

代码语言:javascript

复制

import pytestfrom playwright.sync_api import Pagefrom Util import ClassDBimport time REGISTER_URL = 'http://127.0.0.1:8080/CharGPTEbusiness/jsp/register.jsp'# 测试类class TestUserRegistration:       def teardown_class(self):        ClassDB.init_db()            def test_valid_username(self,page: Page):        '''GTC1-账号有效性测试'''        …        assert page.get_by_role("heading", name="登录")        …    def test_duplicate_registration(self,page: Page):        '''GTC6 – 一个用户重复注册两次:'''        …        assert page.get_by_role("heading", name="登录")        …    def test_duplicate_phone(self,page: Page):        '''GTC7 – – 不同用户注册,手机号重复:'''        …        assert page.get_by_role("heading", name="登录")     def test_duplicate_email(self,page: Page):        '''GTC7 – 不同用户注册,邮件重复:'''        …        assert page.get_by_role("heading", name="登录")        …if __name__ == '__main__':    pytest.main(["-sv", "Test_register_GUI.py"])运行TestEbuxiness.py与Test_register_GUI.py,测试通过。

9.3.8进一步优化jsp代码

由于jsp应该属于显示层,里面的逻辑代码太多。这里进行整理。

1)修改User.java

添加构造函数

代码语言:javascript

复制

public User(String username,String password) {
      this.username = username;
      this.password = password;
      this.phone = "13611112222";
      this.email = "jerry@126.com";
    }
    public User(String username,String password,String phone,String email) {
      this.username = username;
      this.password = password;
      this.phone = phone;
      this.email = email;
}

2)修改测试代码ValidateUserTest.java

代码语言:javascript

复制

@Test
public void testValidate_Success() {
      String username = "validUser";
      String phone = "13812345678";
      String email = "validuser@example.com";
      String password = "751a0f268bba70d0fe70372692d4cd61f11c60183b920857597a103b394ef3eb";
      User user = new User(username,password,phone,email);
        assertEquals("验证成功", validator.validate(user));
    }
    @Test
    public void testValidate_InvalidUsername() {
      String username = "invalid_user@123";
      String phone = "13812345678";
      String email = "validuser@example.com";
      String password = "d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2";
        User user = new User(username,password,phone,email);
        assertEquals("账号必须是5-20位字母或数字", validator.validate(user));
    }
    @Test
    public void testValidate_InvalidPhone() {
      String username = "validUser";
      String phone = "123";
      String email = "validuser@example.com";
      String password = "d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2";
        User user = new User(username,password,phone,email);
        assertEquals("手机号必须符合中国手机号码格式", validator.validate(user));
    }
    @Test
    public void testValidate_InvalidEmail() {
      String username = "validUser";
      String phone = "13812345678";
      String email = "invalidemail.com";
      String password = "d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2";
        User user = new User(username,password,phone,email);
        assertEquals("Email格式不正确", validator.validate(user));
    }
    @Test
    public void testValidate_InvalidPasswordHash() {
      String username = "validUser";
      String phone = "13812345678";
      String email = "validuser@example.com";
      String password = "plainpassword";
        User user = new User(username,password,phone,email);
        assertEquals("密码应该哈希进行存储", validator.validate(user));
    }

3)修改测试代码DBuserTest.java

代码语言:javascript

复制

@Test
public void testInsert_UserExists() {
        try {
            Connection conn = dbUser.connect();
            String username="existingUser";
            String password="password";
            String phone="13812345678";
            String email="existinguser@example.com";
            User user = new User(username,password,phone,email);
            String result = dbUser.insert(conn, user);
            assertEquals("1", result); 
            result = dbUser.insert(conn, user);
            if (!deleteUser(user,conn)) {
              System.out.print("删除失败");
            }
            dbUser.disconnect(conn);
            assertEquals("注册用户的用户名必须唯一", result); 
        } catch (SQLException e) {
            e.printStackTrace();
            fail("Insert failed");
        }
    }
    @Test
    public void testInsert_Success() {
        try {
            Connection conn = dbUser.connect();
            String username="newUser";
            String password="password";
            String phone="13812345678";
            String email="newuser@example.com";
            User user = new User(username,password,phone,email);
            String result = dbUser.insert(conn, user);         
            if (!deleteUser(user,conn)) {
              System.out.print("删除失败");
            }
            dbUser.disconnect(conn);
            assertEquals("1", result); 
        } catch (SQLException e) {
            e.printStackTrace();
            fail("Insert failed");
        }
    }

4)建立register.java文件

代码语言:javascript

复制

package ebusiness;
import java.sql.Connection;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletRequest;
public class register {
  private HttpServletResponse response;
  private HttpServletRequest request;
  public register(HttpServletResponse response,HttpServletRequest request) {
        this.response = response;
        this.request = request;
    }
  public String myRegister() {
    String username = this.request.getParameter("username");
    String password = this.request.getParameter("password");
    String phone = this.request.getParameter("phone");
    String email = this.request.getParameter("email");
    User user = new User(username,password,phone,email);
    validateUser ValidateUser = new validateUser();
    String validationResult = ValidateUser.validate(user);
    if (!validationResult.equals("验证成功")) {
      return validationResult;
    }else {
      try {
        DBuser mysql = new DBuser();
        Connection conn = mysql.connect();
        String info = mysql.insert(conn, user);
        if (info.equals("1")) {
          this.response.sendRedirect("login.jsp");
        } else {
          return info;
        }
        mysql.disconnect(conn);
      } catch (Exception e) {
        return "数据库错误: " + e.getMessage();
      }
    }
    return "0";
  }
}

5)修改register.jsp

代码语言:javascript

复制

<%@ page contentType="text/html; charset=utf-8" %>
<%@ page import="java.sql.*, ebusiness.DBuser, ebusiness.validateUser, ebusiness.Util, ebusiness.User,ebusiness.CookiesManager,ebusiness.register" %>
<!DOCTYPE html>
<html lang="zh-CN">
<body>
<%
Util util = new Util();
String csrftoken=util.generateRandomString(100);
%>
    </form>
    <div id="registerError" class="error">
        <%
      CookiesManager ct = new CookiesManager("csrftoken",csrftoken, response,request);
      String method = request.getMethod();
      if ("get".equalsIgnoreCase(method)) {
        ct.setCookie();
      }else if("post".equalsIgnoreCase(method)){
        String csrftoken_post = request.getParameter("csrftoken");
        String csrftoken_cookies = ct.getCookie();
        ct.setCookie();
        if((csrftoken_cookies.equals(csrftoken_post))&&(csrftoken_cookies!=null)&&(csrftoken_cookies.length() > 0)){
          register myregister = new register(response,request);
    %>
    <%= myregister.myRegister()%>
    <%
        }
    }
    %>
    </div>
</div>
</body>
</html>

6)建立login.java文件

代码语言:javascript

复制

package ebusiness;
 
import java.sql.Connection;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletRequest;
 
public class login {
       private HttpServletResponse response;
       private HttpServletRequest request;
       
       public login(HttpServletResponse response,HttpServletRequest request) {
        this.response = response;
        this.request = request;
    }
       
       public String myLogin() {
              String username = request.getParameter("username");
              String password = request.getParameter("password");              
              User user = new User(username, password);
              validateUser ValidateUser = new validateUser();
              String validationResult = ValidateUser.validate(user);
              if (validationResult.equals("验证成功"))  {
                     try {
                            DBuser mysql = new DBuser();
                            Connection conn = mysql.connect();
                            if (mysql.login(conn, user).equals("0")){
                                   return "用户名或密码错误";
                            }else{
                                   CookiesManager myusername = new CookiesManager("username",username, response,request);
                                   myusername.setCookie();
                                   response.sendRedirect("welcome.jsp");
                            }
                            mysql.disconnect(conn);
                     } catch (Exception e) {
                            e.printStackTrace();
                     }
              }else{
                     return validationResult;
              }
              return "0";
       }
}

7)修改login.jsp

代码语言:javascript

复制

<%@ page contentType="text/html; charset=utf-8" %>
<%@ page import="java.sql.*, ebusiness.DBuser, ebusiness.validateUser, ebusiness.Util, ebusiness.User,ebusiness.CookiesManager,ebusiness.login" %>
    </form>
  <div id="loginError" class="error">
        <%
      CookiesManager ct = new CookiesManager("csrftoken",csrftoken, response,request);
      String method = request.getMethod();
      if ("get".equalsIgnoreCase(method)) {
        ct.setCookie();
      }else if("post".equalsIgnoreCase(method)){
        String csrftoken_post = request.getParameter("csrftoken");
        String csrftoken_cookies = ct.getCookie();
        ct.setCookie(); 
        if((csrftoken_cookies.equals(csrftoken_post))&&(csrftoken_cookies!=null)&&(csrftoken_cookies.length() > 0)){
        login mylogin = new login(response,request);
    %>
    <%= mylogin.myLogin()%>
    <%
        }
    }
    %>
    </div>
  </div>
</body>
</html>
目录
相关文章
|
15天前
|
前端开发 JavaScript 测试技术
使用ChatGPT生成登录产品代码的测试用例和测试脚本
使用ChatGPT生成登录产品代码的测试用例和测试脚本
67 35
|
15天前
|
JavaScript 前端开发 Java
使用ChatGPT生成关于登录产品代码的单元测试代码
使用ChatGPT生成关于登录产品代码的单元测试代码
39 16
|
15天前
|
前端开发 JavaScript Java
使用ChatGPT关于登录产品代码的代码评审
整体来看,您的测试代码结构清晰,覆盖面广,关注了安全性测试。通过一些小的改进,可以提高代码的可维护性和安全性。继续保持良好的测试习惯,并考虑使用一些现代化的工具和库来简化测试工作。
36 13
|
1月前
|
机器学习/深度学习 人工智能 搜索推荐
哈佛推出全新类ChatGPT癌症诊断AI,登上Nature!准确率高达96%
哈佛大学研究团队开发的新型AI模型CHIEF,在《自然》期刊发表,癌症诊断准确率达96%。CHIEF基于深度学习,能自动识别、分类癌症并预测生存期,具高准确性、多任务能力和泛化性。它结合病理图像与基因组学等数据,显著提升诊断效率和个性化治疗水平,有望改善医疗资源不平等。但数据隐私和临床效果验证仍是挑战。论文见:https://www.nature.com/articles/s41586-024-07894-z
164 101
|
2月前
|
人工智能 搜索推荐 iOS开发
OpenAI推出适用于iPhone的ChatGPT,与Apple实现具有里程碑意义的AI整合
OpenAI推出适用于iPhone的ChatGPT,与Apple实现具有里程碑意义的AI整合
|
6月前
|
人工智能 自然语言处理 搜索推荐
chatgpt这么火,现在AI搜索引擎有哪些呢?
国外AI搜索引擎包括ChatGPT,擅长自然语言处理与内容生成;Google Bard,提供智能个性化搜索体验;Microsoft Bing集成GPT模型增强智能检索;Perplexity AI以简洁答案及文献引用著称;Neeva强调隐私保护与无广告服务。国内方面,天工AI支持多种功能如知识问答与代码编程;腾讯元宝基于混元模型助力内容创造与学习;360AI搜索以精准全面的信息搜索见长;秘塔AI专注提升写作质量和效率;开搜AI搜索提供个性化智能搜索服务。以上引擎均利用先进AI技术提升用户体验。更多详情参阅[AI搜索合集](zhangfeidezhu.com/?page_id=651)。
167 8
chatgpt这么火,现在AI搜索引擎有哪些呢?
|
6月前
|
机器学习/深度学习 人工智能 自然语言处理
HuggingGPT解析:使用 ChatGPT及HuggingFace上的族系解决AI问题
HuggingGPT是一个框架,它使用大型语言模型(如ChatGPT)作为控制器来管理和协调Hugging Face上的AI模型,以语言作为通用接口解决多模态和领域的复杂AI任务。
109 0
HuggingGPT解析:使用 ChatGPT及HuggingFace上的族系解决AI问题
|
6月前
|
机器学习/深度学习 人工智能 算法
为什么ChatGPT等AI大模型都是基于Python开发?
为什么ChatGPT等AI大模型都是基于Python开发?
130 0
|
6月前
|
人工智能 自然语言处理 Linux
免费ChatGPT4o灵办AI可体验浏览器插件
灵办AI就是您所需的最佳助手!我们为您带来了一款多功能AI工具,ChatGPT4o不仅能为您提供精准翻译,还能满足您的对话需求、智能续写、AI搜索、文档阅读、代码生成与修正等多种需求。灵办 AI,真正让工作和学习变得轻松高效!一款多功能智能助手,旨在提升工作和学习效率。它提供实时翻译、对话问答、搜索、写作和网页阅读等服务,支持多种浏览器和操作系统,帮助用户随时获取信息,打破语言障碍,优化内容创作和信息处理。
165 0
|
6月前
|
Web App开发 人工智能 安全
Gemini vs ChatGPT:谷歌最新的AI和ChatGPT相比,谁更强?
Gemini vs ChatGPT:谷歌最新的AI和ChatGPT相比,谁更强?