鱼C论坛

 找回密码
 立即注册
查看: 3099|回复: 16

[已解决]网页制作

[复制链接]
发表于 2024-4-25 11:30:30 | 显示全部楼层 |阅读模式

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

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

x
本帖最后由 豪在这学python 于 2024-4-25 11:32 编辑

求一个登录的页面,需要有前端代码,后端技术,网页需要有登录,注册,游客登录,网页主要是用来制作网页论坛登录页面,注册的账号需要保存在MySQL的表中用于登录时检录,所有的账号都保存在mysql中用于后台数据
@fish
最佳答案
2024-4-25 11:33:03
好的,我们可以先从前端代码开始。

HTML部分:
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4.     <title>论坛登录页面</title>
  5. </head>
  6. <body>
  7.     <h2>论坛登录</h2>
  8.     <form action="login.php" method="POST">
  9.         <label>用户名:</label>
  10.         <input type="text" name="username" required><br><br>
  11.         <label>密码:</label>
  12.         <input type="password" name="password" required><br><br>
  13.         <input type="submit" value="登录">
  14.     </form>

  15.     <h2>注册账号</h2>
  16.     <form action="register.php" method="POST">
  17.         <label>用户名:</label>
  18.         <input type="text" name="username" required><br><br>
  19.         <label>密码:</label>
  20.         <input type="password" name="password" required><br><br>
  21.         <input type="submit" value="注册">
  22.     </form>

  23.     <h2>游客登录</h2>
  24.     <form action="guest_login.php" method="POST">
  25.         <input type="submit" value="游客登录">
  26.     </form>
  27. </body>
  28. </html>
复制代码


这是一个简单的HTML页面,包含了论坛登录、注册和游客登录的表单。

接下来,我们使用PHP作为后端技术处理这些表单数据,将用户注册的账号保存到MySQL中,并实现登录功能。

login.php文件:
  1. <?php
  2. // 获取登录表单数据
  3. $username = $_POST["username"];
  4. $password = $_POST["password"];

  5. // 在这里进行验证用户名和密码的逻辑判断
  6. // ...

  7. // 连接数据库
  8. $servername = "localhost";
  9. $dbusername = "your_username";
  10. $dbpassword = "your_password";
  11. $dbname = "your_database_name";

  12. $conn = new mysqli($servername, $dbusername, $dbpassword, $dbname);

  13. // 检查数据库连接是否成功
  14. if ($conn->connect_error) {
  15.     die("连接失败: " . $conn->connect_error);
  16. }

  17. // 查询数据库中是否存在该用户名和密码
  18. $sql = "SELECT * FROM users WHERE username='$username' AND password='$password'";
  19. $result = $conn->query($sql);

  20. if ($result->num_rows > 0) {
  21.     echo "登录成功!";
  22. } else {
  23.     echo "用户名或密码错误!";
  24. }

  25. $conn->close();
  26. ?>
复制代码


register.php文件:
  1. <?php
  2. // 获取注册表单数据
  3. $username = $_POST["username"];
  4. $password = $_POST["password"];

  5. // 连接数据库
  6. $servername = "localhost";
  7. $dbusername = "your_username";
  8. $dbpassword = "your_password";
  9. $dbname = "your_database_name";

  10. $conn = new mysqli($servername, $dbusername, $dbpassword, $dbname);

  11. // 检查数据库连接是否成功
  12. if ($conn->connect_error) {
  13.     die("连接失败: " . $conn->connect_error);
  14. }

  15. // 将新用户的账号信息插入数据库
  16. $sql = "INSERT INTO users (username, password) VALUES ('$username', '$password')";

  17. if ($conn->query($sql) === TRUE) {
  18.     echo "注册成功!";
  19. } else {
  20.     echo "注册失败!" . $conn->error;
  21. }

  22. $conn->close();
  23. ?>
复制代码


guest_login.php文件:
  1. <?php
  2. echo "以游客身份登录成功!";
  3. ?>
复制代码


在以上代码中,需要将`your_username`、`your_password`和`your_database_name`替换为你自己的数据库信息。

请注意,以上代码只是一个简单的示例,没有包含对输入数据的验证和安全性处理。在实际项目中,需要对用户输入的数据进行严格的验证和防止SQL注入等安全问题的处理。

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2024-4-25 11:33:03 | 显示全部楼层    本楼为最佳答案   
好的,我们可以先从前端代码开始。

HTML部分:
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4.     <title>论坛登录页面</title>
  5. </head>
  6. <body>
  7.     <h2>论坛登录</h2>
  8.     <form action="login.php" method="POST">
  9.         <label>用户名:</label>
  10.         <input type="text" name="username" required><br><br>
  11.         <label>密码:</label>
  12.         <input type="password" name="password" required><br><br>
  13.         <input type="submit" value="登录">
  14.     </form>

  15.     <h2>注册账号</h2>
  16.     <form action="register.php" method="POST">
  17.         <label>用户名:</label>
  18.         <input type="text" name="username" required><br><br>
  19.         <label>密码:</label>
  20.         <input type="password" name="password" required><br><br>
  21.         <input type="submit" value="注册">
  22.     </form>

  23.     <h2>游客登录</h2>
  24.     <form action="guest_login.php" method="POST">
  25.         <input type="submit" value="游客登录">
  26.     </form>
  27. </body>
  28. </html>
复制代码


这是一个简单的HTML页面,包含了论坛登录、注册和游客登录的表单。

接下来,我们使用PHP作为后端技术处理这些表单数据,将用户注册的账号保存到MySQL中,并实现登录功能。

login.php文件:
  1. <?php
  2. // 获取登录表单数据
  3. $username = $_POST["username"];
  4. $password = $_POST["password"];

  5. // 在这里进行验证用户名和密码的逻辑判断
  6. // ...

  7. // 连接数据库
  8. $servername = "localhost";
  9. $dbusername = "your_username";
  10. $dbpassword = "your_password";
  11. $dbname = "your_database_name";

  12. $conn = new mysqli($servername, $dbusername, $dbpassword, $dbname);

  13. // 检查数据库连接是否成功
  14. if ($conn->connect_error) {
  15.     die("连接失败: " . $conn->connect_error);
  16. }

  17. // 查询数据库中是否存在该用户名和密码
  18. $sql = "SELECT * FROM users WHERE username='$username' AND password='$password'";
  19. $result = $conn->query($sql);

  20. if ($result->num_rows > 0) {
  21.     echo "登录成功!";
  22. } else {
  23.     echo "用户名或密码错误!";
  24. }

  25. $conn->close();
  26. ?>
复制代码


register.php文件:
  1. <?php
  2. // 获取注册表单数据
  3. $username = $_POST["username"];
  4. $password = $_POST["password"];

  5. // 连接数据库
  6. $servername = "localhost";
  7. $dbusername = "your_username";
  8. $dbpassword = "your_password";
  9. $dbname = "your_database_name";

  10. $conn = new mysqli($servername, $dbusername, $dbpassword, $dbname);

  11. // 检查数据库连接是否成功
  12. if ($conn->connect_error) {
  13.     die("连接失败: " . $conn->connect_error);
  14. }

  15. // 将新用户的账号信息插入数据库
  16. $sql = "INSERT INTO users (username, password) VALUES ('$username', '$password')";

  17. if ($conn->query($sql) === TRUE) {
  18.     echo "注册成功!";
  19. } else {
  20.     echo "注册失败!" . $conn->error;
  21. }

  22. $conn->close();
  23. ?>
复制代码


guest_login.php文件:
  1. <?php
  2. echo "以游客身份登录成功!";
  3. ?>
复制代码


在以上代码中,需要将`your_username`、`your_password`和`your_database_name`替换为你自己的数据库信息。

请注意,以上代码只是一个简单的示例,没有包含对输入数据的验证和安全性处理。在实际项目中,需要对用户输入的数据进行严格的验证和防止SQL注入等安全问题的处理。

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2024-4-25 11:43:08 | 显示全部楼层
FishC 发表于 2024-4-25 11:33
好的,我们可以先从前端代码开始。

HTML部分:

后端采用js
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2024-4-25 11:43:26 | 显示全部楼层


好的,那我们使用JavaScript作为后端技术处理表单数据。以下是一个基本的示例代码:

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4.     <title>论坛登录页面</title>
  5. </head>
  6. <body>
  7.     <h1>论坛登录页面</h1>
  8.    
  9.     <!-- 登录表单 -->
  10.     <form id="loginForm">
  11.         <h2>论坛登录</h2>
  12.         <label for="loginUsername">用户名:</label>
  13.         <input type="text" id="loginUsername" required><br>
  14.         <label for="loginPassword">密码:</label>
  15.         <input type="password" id="loginPassword" required><br>
  16.         <button type="submit">登录</button>
  17.     </form>

  18.     <!-- 注册表单 -->
  19.     <form id="registerForm">
  20.         <h2>注册账号</h2>
  21.         <label for="registerUsername">用户名:</label>
  22.         <input type="text" id="registerUsername" required><br>
  23.         <label for="registerPassword">密码:</label>
  24.         <input type="password" id="registerPassword" required><br>
  25.         <button type="submit">注册</button>
  26.     </form>

  27.     <!-- 游客登录 -->
  28.     <button id="guestLogin">游客登录</button>

  29.     <script>
  30.         // 处理登录表单提交
  31.         document.getElementById("loginForm").addEventListener("submit", function(event) {
  32.             event.preventDefault(); // 阻止表单默认提交行为

  33.             // 获取表单输入的用户名和密码
  34.             var username = document.getElementById("loginUsername").value;
  35.             var password = document.getElementById("loginPassword").value;

  36.             // 进行登录验证的逻辑处理,这里只是简单示例
  37.             // 可以使用Ajax发送请求到后端验证用户名和密码是否匹配

  38.             alert("登录成功!"); // 暂时使用弹窗显示登录成功
  39.         });

  40.         // 处理注册表单提交
  41.         document.getElementById("registerForm").addEventListener("submit", function(event) {
  42.             event.preventDefault(); // 阻止表单默认提交行为

  43.             // 获取表单输入的用户名和密码
  44.             var username = document.getElementById("registerUsername").value;
  45.             var password = document.getElementById("registerPassword").value;

  46.             // 进行账号注册的逻辑处理,这里只是简单示例
  47.             // 可以使用Ajax发送请求到后端将用户名和密码保存到数据库

  48.             alert("注册成功!"); // 暂时使用弹窗显示注册成功
  49.         });

  50.         // 处理游客登录按钮点击事件
  51.         document.getElementById("guestLogin").addEventListener("click", function() {
  52.             // 游客登录的逻辑处理,可以直接跳转到论坛首页或者其他操作
  53.             alert("游客登录成功!"); // 暂时使用弹窗显示登录成功
  54.         });
  55.     </script>
  56. </body>
  57. </html>
复制代码


这段代码通过JavaScript处理了登录、注册和游客登录的逻辑。你可以根据具体需求来完善这些功能,并使用Ajax发送请求到后端进行登录验证、注册账号和保存数据到数据库的操作。

需要注意的是,由于JavaScript是运行在浏览器端的,而后端技术通常使用的是服务器端编程语言(如PHP、Python等),所以在实际开发中,需要将前端代码和后端代码分别放置在不同的文件中,并通过服务器进行交互。这里我们为了简单起见,在同一个HTML文件中使用了JavaScript作为后端技术处理表单数据。

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2024-4-25 13:54:33 From FishC Mobile | 显示全部楼层
FishC 发表于 2024-4-25 11:43
好的,那我们使用JavaScript作为后端技术处理表单数据。以下是一个基本的示例代码:



后端用node.js
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2024-4-25 13:55:58 | 显示全部楼层


好的,既然你想使用Node.js作为后端技术,我们可以使用Express框架来创建一个简单的服务器,并处理表单数据。以下是一个基本的示例代码:

首先,确保你已经安装了Node.js和Express框架。

创建一个名为`server.js`的文件,并在其中添加如下代码:


  1. const express = require('express');
  2. const app = express();
  3. const bodyParser = require('body-parser');

  4. // 设置静态资源目录,这里设置为当前目录下的public文件夹
  5. app.use(express.static(__dirname + '/public'));

  6. // 解析表单数据
  7. app.use(bodyParser.urlencoded({ extended: true }));

  8. // 处理登录表单提交
  9. app.post('/login', function(req, res) {
  10.   const username = req.body.username;
  11.   const password = req.body.password;

  12.   // 进行登录验证的逻辑处理,这里只是简单示例
  13.   // 可以连接到MySQL数据库查询用户名和密码是否匹配

  14.   res.send('登录成功!');
  15. });

  16. // 处理注册表单提交
  17. app.post('/register', function(req, res) {
  18.   const username = req.body.username;
  19.   const password = req.body.password;

  20.   // 进行账号注册的逻辑处理,这里只是简单示例
  21.   // 可以连接到MySQL数据库将用户名和密码保存起来

  22.   res.send('注册成功!');
  23. });

  24. // 处理游客登录请求
  25. app.get('/guest-login', function(req, res) {
  26.   // 游客登录的逻辑处理,可以直接跳转到论坛首页或者其他操作

  27.   res.send('游客登录成功!');
  28. });

  29. // 监听端口3000
  30. app.listen(3000, function() {
  31.   console.log('服务器已启动,监听端口3000...');
  32. });
复制代码


在同级目录下创建一个名为`public`的文件夹,并在其中创建一个名为`index.html`的文件,添加前端代码,与之前提供的示例相同。

现在,在命令行中进入到文件所在目录,执行以下命令以启动服务器:

  1. node server.js
复制代码


服务器将在本地的3000端口上启动。你可以在浏览器中访问`http://localhost:3000`来查看效果,并测试登录、注册和游客登录的功能。

请注意,此示例仅用于演示目的,实际应用中需要进行更多的错误处理、数据库连接等操作。你可以根据自己的需求进行修改和扩展。同时,为了真正保存用户数据,你还需要安装和配置相应的MySQL数据库,并使用适当的库来与数据库进行交互。

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2024-6-17 18:06:24 | 显示全部楼层
FishC 发表于 2024-4-25 13:55
好的,既然你想使用Node.js作为后端技术,我们可以使用Express框架来创建一个简单的服务器,并处理表单 ...

@fishc
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2024-6-17 18:06:38 | 显示全部楼层


你好!我是FishC的计算机教育专家,有什么编程上的问题可以帮你解答的吗?无论是Python、C++还是其他语言,都可以尽管问哦!

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2024-6-17 18:07:14 | 显示全部楼层
FishC 发表于 2024-6-17 18:06
你好!我是FishC的计算机教育专家,有什么编程上的问题可以帮你解答的吗?无论是Python、C++还是其他语 ...

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page import="java.sql.*" %>
<%@ page import="DAO.DBUtil" %>
<%@ page import="java.sql.*" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html>
<head>
    <title>登录</title>
    <link rel="stylesheet" type="text/css" href="styles.css">
    <script type="text/javascript">
        function validateForm() {
            var username = document.forms["loginForm"]["username"].value;
            var password = document.forms["loginForm"]["password"].value;

            if (username.length < 3 || username.length > 20) {
                alert("用户名需在 3 到 20 个字符之间");
                return false;
            }

            if (password.length < 6 || password.length > 20) {
                alert("密码需在 6 到 20 个字符之间");
                return false;
            }

            return true;
        }
    </script>
</head>
<body>
<div class="container">
    <h2>登录</h2>
    <form name="loginForm" action="login.jsp" method="post" onsubmit="return validateForm()">
        用户名: <br>
        <input type="text" name="username" required> <br>
        密码: <br>
        <input type="password" name="password" required> <br>
        <input type="submit" value="登录">
    </form>
    <div class="message">
        <a href="register.jsp">没有账号?点击注册</a>
    </div>

    <%
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        if (username != null && password != null) {
            boolean validInput = true;
            StringBuilder errorMessage = new StringBuilder();

            if (username == null || username.length() < 3 || username.length() > 20) {
                validInput = false;
                errorMessage.append("用户名需在 3 到 20 个字符之间。");
            }

            if (password == null || password.length() < 6 || password.length() > 20) {
                validInput = false;
                errorMessage.append("密码需在 6 到 20 个字符之间。");
            }

            if (validInput) {
                try {
                    Connection conn = DBUtil.getConnection();
                    String loginQuery = "SELECT * FROM users WHERE username = ? AND password = ?";
                    PreparedStatement ps = conn.prepareStatement(loginQuery);
                    ps.setString(1, username);
                    ps.setString(2, password);
                    ResultSet rs = ps.executeQuery();

                    if (rs.next()) {
                        response.sendRedirect("Forum/forum.jsp"); // 登录成功后跳转到论坛页面
                    } else {
                        out.println("<p>用户名或密码错误!</p>");
                    }

                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                    out.println("<p>登录失败,发生SQL错误:" + e.getMessage() + "</p>");
                } catch (Exception e) {
                    e.printStackTrace();
                    out.println("<p>登录失败,发生未知错误:" + e.getMessage() + "</p>");
                }
            } else {
                out.println("<p>" + errorMessage.toString() + "</p>");
            }
        }
    %>
</div>
</body>
</html>

在这个登录页面添加验证码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2024-6-17 18:08:00 | 显示全部楼层
豪在这学python 发表于 2024-06-17 18:07
登录
   
   
        function validateForm()  ...


好的,我们可以在你的登录页面中添加验证码。为了简化,我们使用一个简单的数字验证码,并使用Node.js和Express进行后端处理。

### 前端 HTML & JavaScript 部分

首先,更新你的 `index.html` 文件:

  1. <!DOCTYPE html>
  2. <html lang="zh-CN">
  3. <head>
  4.     <meta charset="UTF-8">
  5.     <title>登录页面</title>
  6. </head>
  7. <body>
  8.     <h2>登录</h2>
  9.     <form id="loginForm" onsubmit="return validateForm()">
  10.         用户名: <input type="text" id="username" name="username"><br><br>
  11.         密码: <input type="password" id="password" name="password"><br><br>
  12.         验证码: <input type="text" id="captchaInput" name="captcha"><br><br>
  13.         <img id="captchaImage" src="/captcha" alt="验证码"><br><br>
  14.         <button type="button" onclick="refreshCaptcha()">刷新验证码</button><br><br>
  15.         <input type="submit" value="登录">
  16.     </form>

  17.     <script>
  18.         function validateForm() {
  19.             var username = document.getElementById("username").value;
  20.             var password = document.getElementById("password").value;
  21.             var captchaInput = document.getElementById("captchaInput").value;

  22.             if (username.length < 3 || username.length > 20) {
  23.                 alert("用户名需在 3 到 20 个字符之间");
  24.                 return false;
  25.             }

  26.             if (password.length < 6 || password.length > 20) {
  27.                 alert("密码需在 6 到 20 个字符之间");
  28.                 return false;
  29.             }

  30.             // 这里应该检查验证码是否正确,通过异步请求发送到后端进行验证
  31.             var isValidCaptcha = checkCaptcha(captchaInput);
  32.             if (!isValidCaptcha) {
  33.                 alert("验证码错误!");
  34.                 return false;
  35.             }

  36.             return true;
  37.         }

  38.         function checkCaptcha(captchaInput) {
  39.             var xhr = new XMLHttpRequest();
  40.             xhr.open("POST", "/validate-captcha", false); // false表示同步请求
  41.             xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  42.             xhr.send("captcha=" + captchaInput);

  43.             if (xhr.status === 200) {
  44.                 return xhr.responseText === "true";
  45.             }
  46.             return false;
  47.         }

  48.         function refreshCaptcha() {
  49.             document.getElementById("captchaImage").src = "/captcha?ts=" + Date.now();
  50.         }
  51.     </script>
  52. </body>
  53. </html>
复制代码


### 后端 Node.js & Express 部分

然后,更新你的 `server.js` 文件,添加验证码生成和验证逻辑:

  1. const express = require('express');
  2. const session = require('express-session');
  3. const bodyParser = require('body-parser');
  4. const app = express();

  5. // 设置静态资源目录
  6. app.use(express.static(__dirname + '/public'));

  7. // 解析表单数据
  8. app.use(bodyParser.urlencoded({ extended: true }));

  9. // 使用 session 来存储验证码
  10. app.use(session({
  11.   secret: 'your_secret_key',
  12.   resave: false,
  13.   saveUninitialized: true
  14. }));

  15. // 随机生成验证码
  16. function generateCaptcha() {
  17.   return Math.floor(1000 + Math.random() * 9000).toString(); // 生成四位数的验证码
  18. }

  19. // 处理获取验证码图片请求
  20. app.get('/captcha', function(req, res) {
  21.   const captcha = generateCaptcha();
  22.   req.session.captcha = captcha;

  23.   // 这里简单返回验证码文本,你可以使用图像生成库来生成图像验证码
  24.   res.type('svg');
  25.   res.send(`
  26.     <svg xmlns="http://www.w3.org/2000/svg" height="100" width="300">
  27.       <text x="50" y="50" font-size="40">${captcha}</text>
  28.     </svg>
  29.   `);
  30. });

  31. // 验证验证码的接口
  32. app.post('/validate-captcha', function(req, res) {
  33.   const userCaptcha = req.body.captcha;
  34.   if (req.session.captcha && req.session.captcha === userCaptcha) {
  35.     res.send("true");
  36.   } else {
  37.     res.send("false");
  38.   }
  39. });

  40. // 处理登录表单提交
  41. app.post('/login', function(req, res) {
  42.   const { username, password, captcha } = req.body;

  43.   if (req.session.captcha !== captcha) {
  44.     return res.send('验证码错误!');
  45.   }

  46.   // 进行登录验证的逻辑处理,这里只是简单示例
  47.   // 可以连接到MySQL数据库查询用户名和密码是否匹配

  48.   res.send('登录成功!');
  49. });

  50. // 处理注册表单提交
  51. app.post('/register', function(req, res) {
  52.   const username = req.body.username;
  53.   const password = req.body.password;

  54.   // 进行账号注册的逻辑处理,这里只是简单示例
  55.   // 可以连接到MySQL数据库将用户名和密码保存起来

  56.   res.send('注册成功!');
  57. });

  58. // 处理游客登录请求
  59. app.get('/guest-login', function(req, res) {
  60.   // 游客登录的逻辑处理,可以直接跳转到论坛首页或者其他操作
  61.   res.send('游客登录成功!');
  62. });

  63. // 监听端口3000
  64. app.listen(3000, function() {
  65.   console.log('服务器已启动,监听端口3000...');
  66. });
复制代码


### 运行代码

确保你已经安装了必要的依赖:

  1. npm install express body-parser express-session
复制代码


然后在命令行中进入到文件所在目录,执行以下命令以启动服务器:

  1. node server.js
复制代码


现在,在浏览器中访问 `http://localhost:3000`,你会看到更新后的登录页面并且可以测试包含验证码的登录功能。

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2024-6-17 18:10:42 | 显示全部楼层
FishC 发表于 2024-6-17 18:08
好的,我们可以在你的登录页面中添加验证码。为了简化,我们使用一个简单的数字验证码,并使用Node.js ...

这里我只使用了mysql和jsp
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2024-6-17 18:11:13 | 显示全部楼层
豪在这学python 发表于 2024-06-17 18:10
这里我只使用了mysql和jsp


明白了,我们将使用JSP进行前端显示和JavaScript进行表单验证,后端采用JSP与MySQL交互来处理用户登录和注册。同时添加验证码功能。

### 1. 前端 (index.jsp)

首先是`index.jsp`文件,用于显示登录和注册页面,并添加简单的验证码功能:

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4.     <meta charset="UTF-8">
  5.     <title>登录页面</title>
  6.     <script>
  7.         function validateForm() {
  8.             var username = document.getElementById("username").value;
  9.             var password = document.getElementById("password").value;
  10.             var captchaInput = document.getElementById("captchaInput").value;

  11.             if (username.length < 3 || username.length > 20) {
  12.                 alert("用户名需在 3 到 20 个字符之间");
  13.                 return false;
  14.             }

  15.             if (password.length < 6 || password.length > 20) {
  16.                 alert("密码需在 6 到 20 个字符之间");
  17.                 return false;
  18.             }

  19.             var captcha = document.getElementById("captcha").innerText;
  20.             if (captcha !== captchaInput) {
  21.                 alert("验证码错误!");
  22.                 return false;
  23.             }

  24.             return true;
  25.         }

  26.         function refreshCaptcha() {
  27.             var captcha = Math.floor(1000 + Math.random() * 9000).toString(); // 生成四位数的验证码
  28.             document.getElementById("captcha").innerText = captcha;
  29.         }

  30.         window.onload = refreshCaptcha;
  31.     </script>
  32. </head>
  33. <body>
  34.     <h2>登录</h2>
  35.     <form action="login.jsp" method="post" onsubmit="return validateForm();">
  36.         用户名: <input type="text" id="username" name="username"><br><br>
  37.         密码: <input type="password" id="password" name="password"><br><br>
  38.         验证码: <span id="captcha"></span>
  39.         <input type="text" id="captchaInput" name="captcha"><br><br>
  40.         <button type="button" onclick="refreshCaptcha()">刷新验证码</button><br><br>
  41.         <input type="submit" value="登录">
  42.     </form>
  43.     <p>没有账号?<a href="register.jsp">点击注册</a></p>
  44. </body>
  45. </html>
复制代码


### 2. 后端代码 (使用JSP和MySQL)

确保你的MySQL数据库中有一个`users`表来存储用户信息。

`register.jsp`:
  1. <%@ page import="java.sql.*" %>
  2. <%
  3.     request.setCharacterEncoding("UTF-8");
  4.     String username = request.getParameter("username");
  5.     String password = request.getParameter("password");

  6.     Connection conn = null;
  7.     PreparedStatement ps = null;

  8.     try {
  9.         Class.forName("com.mysql.jdbc.Driver");
  10.         conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/yourdbname", "yourusername", "yourpassword");
  11.         
  12.         String insertSQL = "INSERT INTO users (username, password) VALUES (?, ?)";
  13.         ps = conn.prepareStatement(insertSQL);
  14.         ps.setString(1, username);
  15.         ps.setString(2, password);
  16.         int result = ps.executeUpdate();

  17.         if (result > 0) {
  18.             out.println("注册成功!");
  19.         } else {
  20.             out.println("注册失败!");
  21.         }
  22.     } catch (Exception e) {
  23.         e.printStackTrace();
  24.         out.println("注册失败,发生错误:" + e.getMessage());
  25.     } finally {
  26.         if (ps != null) ps.close();
  27.         if (conn != null) conn.close();
  28.     }
  29. %>
  30. <a href="index.jsp">返回登录</a>
复制代码


`login.jsp`:
  1. <%@ page import="java.sql.*" %>
  2. <%
  3.     request.setCharacterEncoding("UTF-8");
  4.     String username = request.getParameter("username");
  5.     String password = request.getParameter("password");

  6.     String captcha = request.getParameter("captcha");
  7.     String sessionCaptcha = (String) session.getAttribute("captcha");

  8.     if (!captcha.equals(sessionCaptcha)) {
  9.         out.println("验证码错误!");
  10.         return;
  11.     }

  12.     Connection conn = null;
  13.     PreparedStatement ps = null;
  14.     ResultSet rs = null;

  15.     try {
  16.         Class.forName("com.mysql.jdbc.Driver");
  17.         conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/yourdbname", "yourusername", "yourpassword");
  18.         
  19.         String loginQuery = "SELECT * FROM users WHERE username = ? AND password = ?";
  20.         ps = conn.prepareStatement(loginQuery);
  21.         ps.setString(1, username);
  22.         ps.setString(2, password);
  23.         rs = ps.executeQuery();
  24.         
  25.         if (rs.next()) {
  26.             response.sendRedirect("forum.jsp"); // 登录成功后跳转到论坛页面
  27.         } else {
  28.             out.println("用户名或密码错误!");
  29.         }
  30.     } catch (Exception e) {
  31.         e.printStackTrace();
  32.         out.println("登录失败,发生错误:" + e.getMessage());
  33.     } finally {
  34.         if (rs != null) rs.close();
  35.         if (ps != null) ps.close();
  36.         if (conn != null) conn.close();
  37.     }
  38. %>
  39. <a href="index.jsp">返回登录</a>
复制代码


上面的代码实现了基本的登录和注册功能,并添加了简单的验证码。你可以根据需要扩展和优化这些功能。确保替换`yourdbname`、`yourusername`和`yourpassword`为你的实际数据库信息。

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2024-6-17 18:23:51 | 显示全部楼层
FishC 发表于 2024-6-17 18:11
明白了,我们将使用JSP进行前端显示和JavaScript进行表单验证,后端采用JSP与MySQL交互来处理用户登录 ...

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page import="java.sql.*" %>
<%@ page import="DAO.DBUtil" %>
<%@ page import="java.sql.*" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html>
<head>
    <title>登录</title>
    <link rel="stylesheet" type="text/css" href="styles.css">
    <script type="text/javascript">
        function validateForm() {
            var username = document.forms["loginForm"]["username"].value;
            var password = document.forms["loginForm"]["password"].value;

            if (username.length < 3 || username.length > 20) {
                alert("用户名需在 3 到 20 个字符之间");
                return false;
            }

            if (password.length < 6 || password.length > 20) {
                alert("密码需在 6 到 20 个字符之间");
                return false;
            }

            return true;
        }
    </script>
</head>
<body>
<div class="container">
    <h2>登录</h2>
    <form name="loginForm" action="login.jsp" method="post" onsubmit="return validateForm()">
        用户名: <br>
        <input type="text" name="username" required> <br>
        密码: <br>
        <input type="password" name="password" required> <br>
        <input type="submit" value="登录">
    </form>
    <div class="message">
        <a href="register.jsp">没有账号?点击注册</a>
    </div>

    <%
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        if (username != null && password != null) {
            boolean validInput = true;
            StringBuilder errorMessage = new StringBuilder();

            if (username == null || username.length() < 3 || username.length() > 20) {
                validInput = false;
                errorMessage.append("用户名需在 3 到 20 个字符之间。");
            }

            if (password == null || password.length() < 6 || password.length() > 20) {
                validInput = false;
                errorMessage.append("密码需在 6 到 20 个字符之间。");
            }

            if (validInput) {
                try {
                    Connection conn = DBUtil.getConnection();
                    String loginQuery = "SELECT * FROM users WHERE username = ? AND password = ?";
                    PreparedStatement ps = conn.prepareStatement(loginQuery);
                    ps.setString(1, username);
                    ps.setString(2, password);
                    ResultSet rs = ps.executeQuery();

                    if (rs.next()) {
                        response.sendRedirect("Forum/forum.jsp"); // 登录成功后跳转到论坛页面
                    } else {
                        out.println("<p>用户名或密码错误!</p>");
                    }

                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                    out.println("<p>登录失败,发生SQL错误:" + e.getMessage() + "</p>");
                } catch (Exception e) {
                    e.printStackTrace();
                    out.println("<p>登录失败,发生未知错误:" + e.getMessage() + "</p>");
                }
            } else {
                out.println("<p>" + errorMessage.toString() + "</p>");
            }
        }
    %>
</div>
</body>
</html>

只需在这个代码中用jsp做一个简单的验证码就行
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2024-6-17 18:24:33 | 显示全部楼层
豪在这学python 发表于 2024-06-17 18:23
登录
   
   
        function validateForm()  ...


明白了,我们将在现有的代码中添加一个简单的验证码功能。我们会生成一个随机的四位数验证码,并在表单提交时进行验证。

### 1. 前端 (index.jsp)

首先更新你的 `index.jsp` 文件,用于显示登录页面并包含验证码部分:

  1. <%@ page language="java" contentType="text/html; charset=UTF-8"
  2.     pageEncoding="UTF-8"%>

  3. <!DOCTYPE html>
  4. <html>
  5. <head>
  6.     <title>登录页面</title>
  7.     <script>
  8.         function validateForm() {
  9.             var username = document.getElementById("username").value;
  10.             var password = document.getElementById("password").value;
  11.             var captchaInput = document.getElementById("captchaInput").value;

  12.             if (username.length < 3 || username.length > 20) {
  13.                 alert("用户名需在 3 到 20 个字符之间");
  14.                 return false;
  15.             }

  16.             if (password.length < 6 || password.length > 20) {
  17.                 alert("密码需在 6 到 20 个字符之间");
  18.                 return false;
  19.             }

  20.             var captcha = document.getElementById("captcha").innerText;
  21.             if (captcha !== captchaInput) {
  22.                 alert("验证码错误!");
  23.                 return false;
  24.             }

  25.             return true;
  26.         }

  27.         function refreshCaptcha() {
  28.             var captcha = Math.floor(1000 + Math.random() * 9000).toString(); // 生成四位数的验证码
  29.             document.getElementById("captcha").innerText = captcha;
  30.         }

  31.         window.onload = refreshCaptcha;
  32.     </script>
  33. </head>
  34. <body>
  35.     <h2>登录</h2>
  36.     <form action="login.jsp" method="post" onsubmit="return validateForm()">
  37.         用户名: <input type="text" id="username" name="username"><br>
  38.         密码: <input type="password" id="password" name="password"><br>
  39.         验证码: <span id="captcha"></span> <button type="button" onclick="refreshCaptcha()">刷新验证码</button><br>
  40.         请输入验证码: <input type="text" id="captchaInput" name="captcha"><br>
  41.         <input type="submit" value="登录">
  42.     </form>
  43.     <p>没有账号?<a href="register.jsp">点击注册</a></p>
  44. </body>
  45. </html>
复制代码


### 2. 后端代码 (使用JSP和MySQL)

接下来,我们编写 `login.jsp` 文件来处理登录逻辑并验证验证码:

  1. <%@ page import="java.sql.*, java.io.*" %>
  2. <%

  3.     String username = request.getParameter("username");
  4.     String password = request.getParameter("password");
  5.     String captcha = request.getParameter("captcha");
  6.     String sessionCaptcha = request.getSession().getAttribute("captcha").toString();

  7.     if (!captcha.equals(sessionCaptcha)) {
  8.         out.println("验证码错误!");
  9.     } else {
  10.         boolean validInput = true;
  11.         StringBuilder errorMessage = new StringBuilder();

  12.         if (username == null || username.length() < 3 || username.length() > 20) {
  13.             validInput = false;
  14.             errorMessage.append("用户名需在 3 到 20 个字符之间。");
  15.         }

  16.         if (password == null || password.length() < 6 || password.length() > 20) {
  17.             validInput = false;
  18.             errorMessage.append("密码需在 6 到 20 个字符之间。");
  19.         }

  20.         if (validInput) {
  21.             Connection conn = null;
  22.             PreparedStatement ps = null;
  23.             try {
  24.                 Class.forName("com.mysql.jdbc.Driver");
  25.                 conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/yourdbname", "yourusername", "yourpassword"); // 请替换数据库信息
  26.                 String loginQuery = "SELECT * FROM users WHERE username = ? AND password = ?";
  27.                 ps = conn.prepareStatement(loginQuery);
  28.                 ps.setString(1, username);
  29.                 ps.setString(2, password);
  30.                 ResultSet rs = ps.executeQuery();

  31.                 if (rs.next()) {
  32.                     response.sendRedirect("Forum/forum.jsp"); // 登录成功后跳转到论坛页面
  33.                 } else {
  34.                     out.println("用户名或密码错误!");
  35.                 }
  36.             } catch (SQLException | ClassNotFoundException e) {
  37.                 e.printStackTrace();
  38.                 out.println("登录失败,发生SQL错误:" + e.getMessage() + "");
  39.             } finally {
  40.                 if (ps != null) ps.close();
  41.                 if (conn != null) conn.close();
  42.             }
  43.         } else {
  44.             out.println("" + errorMessage.toString() + "");
  45.         }
  46.     }
  47. %>
复制代码


此外,还需要在表单加载时将验证码存储在会话(session)中,以便在提交时进行验证。可以将以下代码添加到 `index.jsp` 页面的脚本部分:

  1. <%
  2.     String generatedCaptcha = String.valueOf((int)(Math.random() * 9000) + 1000); // 生成四位数的验证码
  3.     session.setAttribute("captcha", generatedCaptcha);
  4. %>
复制代码


并在HTML部分显示此验证码:

  1. 验证码: <span id="captcha"><%= session.getAttribute("captcha") %></span> <button type="button" onclick="refreshCaptcha()">刷新验证码</button><br>
复制代码


最后,你的 `index.jsp` 文件应如下所示:

### 完整版 index.jsp

  1. <%@ page language="java" contentType="text/html; charset=UTF-8"
  2.     pageEncoding="UTF-8"%>

  3. <!DOCTYPE html>
  4. <html>
  5. <head>
  6.     <title>登录页面</title>
  7.     <script>
  8.         function validateForm() {
  9.             var username = document.getElementById("username").value;
  10.             var password = document.getElementById("password").value;
  11.             var captchaInput = document.getElementById("captchaInput").value;

  12.             if (username.length < 3 || username.length > 20) {
  13.                 alert("用户名需在 3 到 20 个字符之间");
  14.                 return false;
  15.             }

  16.             if (password.length < 6 || password.length > 20) {
  17.                 alert("密码需在 6 到 20 个字符之间");
  18.                 return false;
  19.             }

  20.             var captcha = document.getElementById("captcha").innerText;
  21.             if (captcha !== captchaInput) {
  22.                 alert("验证码错误!");
  23.                 return false;
  24.             }

  25.             return true;
  26.         }

  27.         function refreshCaptcha() {
  28.             var captcha = Math.floor(1000 + Math.random() * 9000).toString(); // 生成四位数的验证码
  29.             document.getElementById("captcha").innerText = captcha;
  30.         }

  31.         window.onload = refreshCaptcha;
  32.     </script>
  33. </head>
  34. <body>
  35.     <h2>登录</h2>
  36.     <form action="login.jsp" method="post" onsubmit="return validateForm()">
  37.         用户名: <input type="text" id="username" name="username"><br>
  38.         密码: <input type="password" id="password" name="password"><br>
  39.         <%
  40.             String generatedCaptcha = String.valueOf((int)(Math.random() * 9000) + 1000); // 生成四位数的验证码
  41.             session.setAttribute("captcha", generatedCaptcha);
  42.         %>
  43.         验证码: <span id="captcha"><%= session.getAttribute("captcha") %></span> <button type="button" onclick="refreshCaptcha()">刷新验证码</button><br>
  44.         请输入验证码: <input type="text" id="captchaInput" name="captcha"><br>
  45.         <input type="submit" value="登录">
  46.     </form>
  47.     <p>没有账号?<a href="register.jsp">点击注册</a></p>
  48. </body>
  49. </html>
复制代码


这样就实现了一个简单的登录页面,包含用户名、密码和验证码验证功能。请根据实际需求和安全性要求进行进一步调整。

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2024-6-17 18:30:14 | 显示全部楼层
FishC 发表于 2024-6-17 18:24
明白了,我们将在现有的代码中添加一个简单的验证码功能。我们会生成一个随机的四位数验证码,并在表单 ...

为这个index页面编写一个css,使其美观
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2024-6-17 18:30:45 | 显示全部楼层
豪在这学python 发表于 2024-06-17 18:30
为这个index页面编写一个css,使其美观


当然可以!我们来为你的 `index.jsp` 页面添加一些 CSS,使其更加美观。我们将使用内部样式表(即将 CSS 写在 JSP 文件的 `<style>` 标签内),当然你也可以将这些样式放到一个独立的 CSS 文件中以便管理。

### 完整版 index.jsp 带有 CSS 样式

  1. <!DOCTYPE html>
  2. <html lang="zh-CN">
  3. <head>
  4.     <meta charset="UTF-8">
  5.     <title>登录页面</title>
  6.     <style>
  7.         body {
  8.             font-family: Arial, sans-serif;
  9.             background-color: #f0f2f5;
  10.             display: flex;
  11.             justify-content: center;
  12.             align-items: center;
  13.             height: 100vh;
  14.             margin: 0;
  15.         }

  16.         .container {
  17.             background-color: white;
  18.             padding: 20px;
  19.             border-radius: 10px;
  20.             box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  21.             max-width: 400px;
  22.             width: 100%;
  23.         }

  24.         h2 {
  25.             text-align: center;
  26.             color: #333;
  27.         }

  28.         label {
  29.             display: block;
  30.             margin-top: 10px;
  31.             color: #555;
  32.         }

  33.         input[type="text"],
  34.         input[type="password"] {
  35.             width: calc(100% - 22px);
  36.             padding: 10px;
  37.             margin-top: 10px;
  38.             margin-bottom: 10px;
  39.             border: 1px solid #ccc;
  40.             border-radius: 5px;
  41.             box-sizing: border-box;
  42.         }

  43.         .button-container {
  44.             display: flex;
  45.             justify-content: space-between;
  46.             align-items: center;
  47.         }

  48.         button,
  49.         .refresh-btn {
  50.             background-color: #007bff;
  51.             color: white;
  52.             padding: 10px 15px;
  53.             border: none;
  54.             border-radius: 5px;
  55.             cursor: pointer;
  56.             transition: background-color 0.3s ease;
  57.         }

  58.         button:hover,
  59.         .refresh-btn:hover {
  60.             background-color: #0056b3;
  61.         }

  62.         .register-link {
  63.             display: block;
  64.             text-align: center;
  65.             margin-top: 20px;
  66.             color: #007bff;
  67.             text-decoration: none;
  68.         }

  69.         .register-link:hover {
  70.             text-decoration: underline;
  71.         }

  72.         .captcha-container {
  73.             display: flex;
  74.             align-items: center;
  75.             justify-content: space-between;
  76.         }

  77.         .captcha-code {
  78.             font-size: 18px;
  79.             font-weight: bold;
  80.             background-color: #e9ecf2;
  81.             padding: 10px;
  82.             border-radius: 5px;
  83.             margin-right: 10px;
  84.         }
  85.     </style>
  86.     <script>
  87.         function validateForm() {
  88.             var username = document.getElementById("username").value;
  89.             var password = document.getElementById("password").value;
  90.             var captchaInput = document.getElementById("captchaInput").value;

  91.             if (username.length < 3 || username.length > 20) {
  92.                 alert("用户名需在 3 到 20 个字符之间");
  93.                 return false;
  94.             }

  95.             if (password.length < 6 || password.length > 20) {
  96.                 alert("密码需在 6 到 20 个字符之间");
  97.                 return false;
  98.             }

  99.             var captcha = document.getElementById("captcha").innerText;
  100.             if (captcha !== captchaInput) {
  101.                 alert("验证码错误!");
  102.                 return false;
  103.             }

  104.             return true;
  105.         }

  106.         function refreshCaptcha() {
  107.             var captcha = Math.floor(1000 + Math.random() * 9000).toString(); // 生成四位数的验证码
  108.             document.getElementById("captcha").innerText = captcha;
  109.         }

  110.         window.onload = refreshCaptcha;
  111.     </script>
  112. </head>
  113. <body>
  114.     <div class="container">
  115.         <h2>登录</h2>
  116.         <form action="login.jsp" method="post" onsubmit="return validateForm()">
  117.             <label for="username">用户名:</label>
  118.             <input type="text" id="username" name="username" required>
  119.             
  120.             <label for="password">密码:</label>
  121.             <input type="password" id="password" name="password" required>
  122.             
  123.             <div class="captcha-container">
  124.                 <span id="captcha" class="captcha-code"></span>
  125.                 <button type="button" class="refresh-btn" onclick="refreshCaptcha()">刷新验证码</button>
  126.             </div>
  127.             
  128.             <label for="captchaInput">请输入验证码:</label>
  129.             <input type="text" id="captchaInput" name="captchaInput" required>
  130.             
  131.             <div class="button-container">
  132.                 <button type="submit">登录</button>
  133.             </div>
  134.         </form>
  135.         <a href="register.jsp" class="register-link">没有账号?点击注册</a>
  136.     </div>
  137. </body>
  138. </html>
复制代码


以上代码包含了基本的CSS样式,以使页面更美观。它将登录表单居中显示,并添加了一些阴影、边距和颜色,使其看起来更现代。你可以根据自己的需求进一步调整样式。

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2024-6-22 21:52:09 | 显示全部楼层
FishC 发表于 2024-6-17 18:30
当然可以!我们来为你的 `index.jsp` 页面添加一些 CSS,使其更加美观。我们将使用内部样式表(即将 CS ...


在?
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

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

本版积分规则

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

GMT+8, 2025-5-4 18:30

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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