JSP01:一个简单的JSP+Servlet项目开头

练手:一个简单的JSP+Servlet项目开头

工具:

Apache NetBeans IDE 17

mysql 8.0.31

jdk 1.8

apache-tomcat-10.0.12

1.项目目录

2.具体代码

JSP代码

login.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
  <title>登录</title>
  <style>
    /* 样式表 */
    body {
      font-family: Arial, Helvetica, sans-serif;
      background-color: #f2f2f2;
    }
    h1 {
      text-align: center;
    }
    form {
      border: 3px solid #f1f1f1;
      width: 50%;
      margin: auto;
      padding: 20px;
      background-color: #ffffff;
    }
    input[type=text], input[type=password] {
      width: 100%;
      padding: 12px 20px;
      margin: 8px 0;
      display: inline-block;
      border: 1px solid #ccc;
      box-sizing: border-box;
    }
    button[type=submit] {
      background-color: #4CAF50;
      color: white;
      padding: 14px 20px;
      margin: 8px 0;
      border: none;
      cursor: pointer;
      width: 100%;
    }
    button[type=submit]:hover {
      opacity: 0.8;
    }
    .container {
      padding: 16px;
    }
    span.psw {
      float: right;
      padding-top: 16px;
    }
    /* 清除浮动 */
    .clearfix::after {
      content: "";
      clear: both;
      display: table;
    }
  </style>
</head>
<body>
  <h1>登录</h1>
  <form method="post" action="LoginServlet" >
    <div class="container">
      <label for="username"><b>用户名:</b></label>
      <input type="text" placeholder="请输入用户名" name="username" required>

      <label for="password"><b>密码:</b></label>
      <input type="password" placeholder="请输入密码" name="password" required>
      <button type="submit">登录</button>
    </div>
    <div class="container clearfix">
      <a href="register.jsp" style="float:right">没有账号?点击这里注册!</a>
    </div>
  </form>
</body>
</html>

register.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
  <title>注册</title>
  <style>
    /* 样式表 */
    body {
      font-family: Arial, Helvetica, sans-serif;
      background-color: #f2f2f2;
    }
    h1 {
      text-align: center;
    }
    form {
      border: 3px solid #f1f1f1;
      width: 50%;
      margin: auto;
      padding: 20px;
      background-color: #ffffff;
    }
    input[type=text], input[type=password] {
      width: 100%;
      padding: 12px 20px;
      margin: 8px 0;
      display: inline-block;
      border: 1px solid #ccc;
      box-sizing: border-box;
    }
    button[type=submit] {
      background-color: #4CAF50;
      color: white;
      padding: 14px 20px;
      margin: 8px 0;
      border: none;
      cursor: pointer;
      width: 100%;
    }
    button[type=submit]:hover {
      opacity: 0.8;
    }
    .container {
      padding: 16px;
    }
    /* 清除浮动 */
    .clearfix::after {
      content: "";
      clear: both;
      display: table;
    }
    .error {
      color: red;
    }
    .success {
      color: green;
    }
  </style>
</head>
<body>
  <h1>注册</h1>
  <form method="post" action="RegisterServlet" class="clearfix">
    <div class="container">
      <label for="username"><b>用户名:</b></label>
      <input type="text" placeholder="请输入用户名" name="username" required>

      <label for="password"><b>密码:</b></label>
      <input type="password" placeholder="请输入密码" name="password" id="password" pattern="^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[0-9a-zA-Z]{8,}$" required>
      <p class="error">密码必须包含大小写字母和数字,并且至少8位</p>

      <label for="password_confirm"><b>确认密码:</b></label>
      <input type="password" placeholder="请再次输入密码" name="password_confirm" id="password_confirm" required>
      <p class="error">两次输入的密码必须相同</p>
      <p class="success">密码符合要求</p>

      <button type="submit">注册</button>
    </div>
    <div class="container clearfix">
      <a href="login.jsp" style="float:right">已有账号?点击这里登录!</a>
    </div>
  </form>
  <script>
    // 添加密码复杂度和一致性检查
    const password = document.getElementById("password");
    const confirmPassword = document.getElementById("password_confirm");
    const errorMessages = document.querySelectorAll(".error");
    const successMsg = document.querySelector(".success");

    function checkPasswords() {
      if (password.value !== confirmPassword.value) {
        errorMessages[1].style.display = "block";
        successMsg.style.display = "none";
      } else {
        errorMessages[1].style.display = "none";
        successMsg.style.display = "block";
      }
    }

    function checkPasswordStrength() {
      const passwordRegex = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[0-9a-zA-Z]{8,}$/;
      if (password.value.match(passwordRegex)) {
        errorMessages[0].style.display = "none";
      } else {
        errorMessages[0].style.display = "block";
      }
    }

    password.addEventListener("input", checkPasswords);
    confirmPassword.addEventListener("input", checkPasswords);
    password.addEventListener("input", checkPasswordStrength);
  </script>
</body>
</html>

home.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>宠物医院</title>
  <style>
    /* 导航栏样式 */
    .navbar {
      background-color: #333;
      overflow: auto;
      text-align: center;
    }
    .navbar a {
      color: white;
      text-decoration: none;
      font-size: 20px;
      float: left;
      padding: 12px 16px;
    }
    .navbar a:hover {
      background-color: #ddd;
      color: black;
    }

    /* 轮播图样式 */
    .slideshow {
      position: relative;
    }
    .slideshow img {
      display: block;
      width: 100%;
      height: auto;
    }
    .slideshow .dots {
      position: absolute;
      bottom: 0;
      width: 100%;
      text-align: center;
    }
    .slideshow .dot {
      display: inline-block;
      margin: 0 5px;
      width: 10px;
      height: 10px;
      border-radius: 50%;
      background-color: gray;
      cursor: pointer;
    }
    .slideshow .active {
      background-color: white;
    }

    /* 服务介绍样式 */
    .services {
      text-align: center;
      margin: 80px 0;
    }
    .services h2 {
      font-size: 36px;
      margin-bottom: 40px;
    }
    .services .card {
      display: inline-block;
      width: 30%;
      background-color: #f5f5f5;
      border-radius: 20px;
      padding: 30px;
      margin: 20px;
    }
    .services .card h3 {
      font-size: 24px;
      margin-bottom: 20px;
    }
    .services .card p {
      font-size: 16px;
      line-height: 1.5;
      margin-bottom: 30px;
    }

    /* 新闻动态样式 */
    .news {
      text-align: center;
      background-color: #333;
      color: white;
      padding: 80px 0;
    }
    .news h2 {
      font-size: 36px;
      margin-bottom: 40px;
    }
    .news .article {
      display: inline-block;
      width: 30%;
      background-color: white;
      border-radius: 20px;
      padding: 30px;
      margin: 20px;
      box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.2);
      text-align: left;
    }
    .news .article h3 {
      font-size: 24px;
      margin-bottom: 20px;
    }
    .news .article p {
      font-size: 16px;
      line-height: 1.5;
      margin-bottom: 30px;
    }

    /* 联系方式样式 */
    .contact {
      text-align: center;
      background-color: #f5f5f5;
      padding: 80px;
    }
    .contact h2 {
      font-size: 36px;
      margin-bottom: 40px;
    }
    .contact p {
      font-size: 24px;
      margin-bottom: 20px;
    }
  </style>
</head>
<body>
  <!-- 导航栏 -->
  <div class="navbar">
    <a href="#">首页</a>
    <a href="#">服务项目</a>
    <a href="#">医生团队</a>
    <a href="#">新闻动态</a>
    <a href="#">联系我们</a>
  </div>

  <!-- 轮播图 -->
  <div class="slideshow">
    <img src="https://picsum.photos/1200/500/?random=1" alt="slide1">
    <img src="https://picsum.photos/1200/500/?random=2" alt="slide2">
    <img src="https://picsum.photos/1200/500/?random=3" alt="slide3">
    <div class="dots">
      <span class="dot active"></span>
      <span class="dot"></span>
      <span class="dot"></span>
    </div>
  </div>

  <!-- 服务介绍 -->
  <div class="services">
    <h2>我们的服务项目</h2>
    <div class="card">
      <h3>疫苗接种</h3>
      <p>为您的宠物提供各种疫苗接种与预防保健服务,让它们健康成长。</p>
    </div>
    <div class="card">
      <h3>手术治疗</h3>
      <p>高水平的外科医生团队,为您的宠物提供各种手术治疗服务。</p>
    </div>
    <div class="card">
      <h3>诊断检查</h3>
      <p>全面的诊疗设备,帮助医生快速准确地诊断宠物的病情,为其制定最佳治疗方案。</p>
    </div>
  </div>

  <!-- 新闻动态 -->
  <div class="news">
    <h2>最新动态</h2>
    <div class="article">
      <h3>怎样给宠物洗澡比较好?</h3>
      <p>洗澡是宠物日常护理的重要环节,但如果不正确地给宠物洗澡,反而会对其健康造成不利影响。</p>
    </div>
    <div class="article">
      <h3>如何预防宠物感冒?</h3>
      <p>在寒冷的天气里,宠物也容易感冒,而且感冒后的宠物病情往往不容乐观。那么我们该如何预防宠物感冒呢?</p>
    </div>
    <div class="article">
      <h3>如何选择猫咪粮?</h3>
      <p>猫咪粮的质量直接影响宠物的健康,因此选择一款适合的猫咪粮是非常重要的。</p>
    </div>
  </div>

  <!-- 联系方式 -->
  <div class="contact">
    <h2>联系我们</h2>
    <p>地址:XX省XX市XX区XX街道XX号</p>
    <p>电话:0123-4567890</p>
    <p>邮箱:info@pet-hospital.com</p>
  </div>
</body>
</html>


web.xml代码

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
    <servlet>
        <servlet-name>LoginServlet</servlet-name>
        <servlet-class>test.LoginServlet</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>RegisterServlet</servlet-name>
        <servlet-class>test.RegisterServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>LoginServlet</servlet-name>
        <url-pattern>/LoginServlet</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>RegisterServlet</servlet-name>
        <url-pattern>/RegisterServlet</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
</web-app>

Java代码

LoginServlet.java

package test;

import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class LoginServlet extends HttpServlet {
  @Override
  public void doPost(HttpServletRequest request,HttpServletResponse response) 
  throws ServletException, IOException {
    String username = request.getParameter("username");
    String password = request.getParameter("password");

    // 进行用户认证
    boolean isAuthenticated = authenticate(username, password);

    if (isAuthenticated) {
      // 认证成功,将用户信息保存到 session 中
      // 跳转到主页
      response.sendRedirect("home.jsp");
    } else {
      // 认证失败,返回登录页面
      response.sendRedirect("login.jsp");
    }
  }

  // 自定义用户认证逻辑
  private boolean authenticate(String username, String password) {

    boolean isUserExist = false;
    
    try {
        // 加载数据库驱动
        Class.forName("com.mysql.jdbc.Driver");

        // 建立数据库连接
        String url = "jdbc:mysql://localhost:3306/jsp";
        String dbUsername = "root";
        String dbPassword = "root";
        Connection connection = DriverManager.getConnection(url, dbUsername, dbPassword);

        // 准备 SQL 查询语句
        String sql = "SELECT * FROM user WHERE username = ? AND password = ?";
        PreparedStatement statement = connection.prepareStatement(sql);
        statement.setString(1, username);
        statement.setString(2, password);

        // 执行查询操作
        ResultSet resultSet = statement.executeQuery();

        // 判断查询结果是否存在
        if (resultSet.next()) {
            isUserExist = true;
        }

        // 关闭数据库连接
        resultSet.close();
        statement.close();
        connection.close();
        
    } catch (ClassNotFoundException | SQLException e) {
        e.printStackTrace();
    }
    
      
    return isUserExist;
  }
}

RegisterServlet.java

package test;

import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class RegisterServlet extends HttpServlet {
  public void doPost(HttpServletRequest request,HttpServletResponse response) 
  throws ServletException, IOException {
    String username = request.getParameter("username");
    String password = request.getParameter("password");

    // 进行用户注册逻辑
    boolean isRegisterSuccessful = register(username, password);

    if (isRegisterSuccessful) {
      // 注册成功,将用户信息保存到 session 中
      HttpSession session = request.getSession(true);
      session.setAttribute("username", username);

      // 跳转到主页
      response.sendRedirect("home.jsp");
    } else {
      // 注册失败,返回注册页面
      response.sendRedirect("register.jsp");
    }
  }

  // 自定义用户注册逻辑
  private boolean register(String username, String password ) {
      boolean isUserExist = false;

        try (
            
            Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/jsp", "root", "root")) {
            // 创建 PreparedStatement 对象,并设置参数
            PreparedStatement pstmt = conn.prepareStatement("INSERT INTO user (username, password) VALUES (?, ?)");
            pstmt.setString(1, username);
            pstmt.setString(2, password);

            // 执行插入操作并获取返回结果
            int rowsAffected = pstmt.executeUpdate();
            
            // 判断插入是否成功
            if (rowsAffected > 0) {
                isUserExist = true;
            } else {
                System.out.println("Insert failed.");
            }

        } catch (SQLException e) {
            System.out.println("Database connection failed.");
            e.printStackTrace();
        }

      
    // 省略具体实现
    return isUserExist;
  }
}

数据库:

mySQL数据库:

1.建立数据库
CREATE DATABASE JSP;

2.选中数据库
use  JSP;
 
3.在选中的数据库中创建user表
CREATE TABLE user (
       username VARCHAR(50) NOT NULL,
       password VARCHAR(50) NOT NULL,
       PRIMARY KEY (username)
    );

运行结果:

实现功能:

  1. 登录(与数据库进行信息比对)
  2. 注册(包含密码强度要求【正则表达式】,密码二次确定)
  3. 简单的home主页面。





posted @ 2023-05-17 05:10  猪无名  阅读(30)  评论(0编辑  收藏  举报