08-基於JSP&Session&Cookie的學生管理系統

来源:https://www.cnblogs.com/OnlyOnYourself-lzw/archive/2022/08/03/16548063.html
-Advertisement-
Play Games

基於JSP&Session&Cookie的學生管理系統 因為本次系統僅作為練手和熟悉基本的MVC編程,所以僅供參考 1、環境準備 1.0、項目配置文件準備 WEB-INF/web.xml <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="h ...


基於JSP&Session&Cookie的學生管理系統

因為本次系統僅作為練手和熟悉基本的MVC編程,所以僅供參考

1、環境準備

1.0、項目配置文件準備

  • WEB-INF/web.xml

    • <?xml version="1.0" encoding="UTF-8"?>
      <web-app 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_4_0.xsd"
      	version="4.0">
      
      	<!--項目預設打開的首頁配置-->
      	<welcome-file-list>
      		<welcome-file>login.jsp</welcome-file>
      	</welcome-file-list>
      </web-app>
      
  • pom.xml

    • <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">  
        <modelVersion>4.0.0</modelVersion>
      
        <groupId>com.coolman</groupId>  
        <artifactId>_03StudentManagerSystemBaseOnJSPAndTomcat</artifactId>  
        <version>1.0-SNAPSHOT</version>  
        <packaging>war</packaging>
      
        <properties> 
          <maven.compiler.source>8</maven.compiler.source>  
          <maven.compiler.target>8</maven.compiler.target> 
        </properties>
      
      <!--  導入jar包-->
        <dependencies>
      <!--    數據訪問層
        mysql:
        mybatis:
          Mybatis的日誌配置
      -->
          <!--mysql-->
          <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.22</version>
          </dependency>
      
          <!-- mybatis -->
          <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.5</version>
          </dependency>
      
          <!--MyBatis日誌配置-->
          <!-- 添加slf4j日誌api -->
          <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.20</version>
          </dependency>
      
          <!-- 添加logback-classic依賴 -->
          <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.2.3</version>
          </dependency>
      
          <!-- 添加logback-core依賴 -->
          <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-core</artifactId>
            <version>1.2.3</version>
          </dependency>
      <!--
        邏輯業務層
          servlet
          jsp
            jstl
      -->
          <!-- servlet -->
          <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
          </dependency>
      
          <!-- jsp -->
          <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.2</version>
            <scope>provided</scope>
          </dependency>
      
          <!-- jstl -->
          <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
          </dependency>
      
            <dependency>
                <groupId>commons-beanutils</groupId>
                <artifactId>commons-beanutils</artifactId>
                <version>1.9.1</version>
            </dependency>
        </dependencies>
      
        <!-- tomcat7-maven-plugin插件 -->
          <build>
              <plugins>
                  <plugin>
                      <!--Maven直接啟動Tomcat的插件-->
                      <groupId>org.apache.tomcat.maven</groupId>
                      <artifactId>tomcat7-maven-plugin</artifactId>
                      <version>2.2</version>
                      <configuration>
                          <!--Tomcat7的插件的配置-->
                          <port>80</port>   <!--配置埠號-->
                          <path>/</path>  <!--配置項目路徑-->
                          <!--Tomcat的get請求在8版本以下會出現中文亂碼的問題,需要在這裡配置-->
                          <uriEncoding>UTF-8</uriEncoding>
                      </configuration>
                  </plugin>
              </plugins>
          </build>
      
      </project>
      
      

1.1、資料庫準備

  • 因為設計的比較簡單,只要登錄用戶和學生信息,大家可以自行設計資料庫,並導入自定義數據

1.2、實體類準備

  • User類

    • package com.coolman.pojo;
      
      public class User {
          private int id;
          private String name;
          private String phoneNumber;
          private String password;
      
      
          public User() {
          }
      
          public User(int id, String name, String phoneNumber, String password) {
              this.id = id;
              this.name = name;
              this.phoneNumber = phoneNumber;
              this.password = password;
          }
      
          /**
           * 獲取
           * @return id
           */
          public int getId() {
              return id;
          }
      
          /**
           * 設置
           * @param id
           */
          public void setId(int id) {
              this.id = id;
          }
      
          /**
           * 獲取
           * @return name
           */
          public String getName() {
              return name;
          }
      
          /**
           * 設置
           * @param name
           */
          public void setName(String name) {
              this.name = name;
          }
      
          /**
           * 獲取
           * @return phoneNumber
           */
          public String getPhoneNumber() {
              return phoneNumber;
          }
      
          /**
           * 設置
           * @param phoneNumber
           */
          public void setPhoneNumber(String phoneNumber) {
              this.phoneNumber = phoneNumber;
          }
      
          /**
           * 獲取
           * @return password
           */
          public String getPassword() {
              return password;
          }
      
          /**
           * 設置
           * @param password
           */
          public void setPassword(String password) {
              this.password = password;
          }
      
          public String toString() {
              return "User{id = " + id + ", name = " + name + ", phoneNumber = " + phoneNumber + ", password = " + password + "}";
          }
      }
      
  • Student類

    • package com.coolman.pojo;
      
      public class Student {
          private int id;
          private String stuNumber;
          private String name;
          private int age;
          private String sex;
          private double chineseScore;
          private double mathScore;
          private double englishScore;
      
      
          public Student() {
          }
      
          public Student(int id, String stuNumber, String name, int age, String sex, double chineseScore, double mathScore, double englishScore) {
              this.id = id;
              this.stuNumber = stuNumber;
              this.name = name;
              this.age = age;
              this.sex = sex;
              this.chineseScore = chineseScore;
              this.mathScore = mathScore;
              this.englishScore = englishScore;
          }
      
          /**
           * 獲取
           * @return id
           */
          public int getId() {
              return id;
          }
      
          /**
           * 設置
           * @param id
           */
          public void setId(int id) {
              this.id = id;
          }
      
          /**
           * 獲取
           * @return stuNumber
           */
          public String getStuNumber() {
              return stuNumber;
          }
      
          /**
           * 設置
           * @param stuNumber
           */
          public void setStuNumber(String stuNumber) {
              this.stuNumber = stuNumber;
          }
      
          /**
           * 獲取
           * @return name
           */
          public String getName() {
              return name;
          }
      
          /**
           * 設置
           * @param name
           */
          public void setName(String name) {
              this.name = name;
          }
      
          /**
           * 獲取
           * @return age
           */
          public int getAge() {
              return age;
          }
      
          /**
           * 設置
           * @param age
           */
          public void setAge(int age) {
              this.age = age;
          }
      
          /**
           * 獲取
           * @return sex
           */
          public String getSex() {
              return sex;
          }
      
          /**
           * 設置
           * @param sex
           */
          public void setSex(String sex) {
              this.sex = sex;
          }
      
          /**
           * 獲取
           * @return chineseScore
           */
          public double getChineseScore() {
              return chineseScore;
          }
      
          /**
           * 設置
           * @param chineseScore
           */
          public void setChineseScore(double chineseScore) {
              this.chineseScore = chineseScore;
          }
      
          /**
           * 獲取
           * @return mathScore
           */
          public double getMathScore() {
              return mathScore;
          }
      
          /**
           * 設置
           * @param mathScore
           */
          public void setMathScore(double mathScore) {
              this.mathScore = mathScore;
          }
      
          /**
           * 獲取
           * @return englishScore
           */
          public double getEnglishScore() {
              return englishScore;
          }
      
          /**
           * 設置
           * @param englishScore
           */
          public void setEnglishScore(double englishScore) {
              this.englishScore = englishScore;
          }
      
          public String toString() {
              return "Student{id = " + id + ", stuNumber = " + stuNumber + ", name = " + name + ", age = " + age + ", sex = " + sex + ", chineseScore = " + chineseScore + ", mathScore = " + mathScore + ", englishScore = " + englishScore + "}";
          }
      }
      
      

1.3、工具類準備

  • MyBatisUtils工具類

    • 用來指定MyBatis的配置文件和創建SqlSession或者SqlSessionFactory實例

    • package com.coolman.utils;
      
      import org.apache.ibatis.io.Resources;
      import org.apache.ibatis.session.SqlSession;
      import org.apache.ibatis.session.SqlSessionFactory;
      import org.apache.ibatis.session.SqlSessionFactoryBuilder;
      
      import java.io.IOException;
      import java.io.InputStream;
      
      // 這是MyBatis的工具類,簡化MyBatis代碼
      public class MyBatisUtils {
          private static SqlSessionFactory sqlSessionFactory;
          // 我們只需要一個SqlSessionFactory,在靜態代碼塊中創建SqlSessionFactory
          static {
              try {
                  // 編寫代碼讓MyBatis跑起來,執行SQL語句
                  String resource = "mybatis-config.xml";
                  // 載入核心配置文件
                  InputStream inputStream = Resources.getResourceAsStream(resource);
                  // 得到SqlSession工廠,賦值給成員變數
                  sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      
          // 返回SqlSessionFactory
          public static SqlSessionFactory getSqlSessionFactory() {
              return sqlSessionFactory;
          }
      
          // 返回SqlSession
          public static SqlSession openSession() {
              return sqlSessionFactory.openSession();
          }
      
          public static SqlSession openSession(boolean autoCommit) {
              return sqlSessionFactory.openSession(autoCommit);
          }
      }
      
  • CheckCodeUtils工具類

    • 用來生成驗證碼的工具類,其原理可以參考像關於Java的awt圖像生成和驗證碼生成原理相關博客;(複製使用即可,原理不用深究)

    • package com.coolman.utils;
      
      import javax.imageio.ImageIO;
      import java.awt.*;
      import java.awt.geom.AffineTransform;
      import java.awt.image.BufferedImage;
      import java.io.File;
      import java.io.FileOutputStream;
      import java.io.IOException;
      import java.io.OutputStream;
      import java.util.Arrays;
      import java.util.Random;
      
      /**
       * 生成驗證碼工具類
       */
      public class CheckCodeUtil {
      
          private static final String VERIFY_CODES = "123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
          private static Random random = new Random();
      
          public static void main(String[] args) throws IOException {
              FileOutputStream fos = new FileOutputStream("d:\\a.jpg");
              String str = CheckCodeUtil.outputVerifyImage(100, 40, fos, 4);
              System.out.println("str = " + str);
          }
      
      
          /**
           * 輸出隨機驗證碼圖片流,並返回驗證碼值(一般傳入輸出流,響應response頁面端,Web項目用的較多)
           *
           * @param width      圖片寬度
           * @param height     圖片高度
           * @param os         輸出流
           * @param verifySize 數據長度
           * @return 驗證碼數據
           * @throws IOException
           */
          public static String outputVerifyImage(int width, int height, OutputStream os, int verifySize) throws IOException {
              String verifyCode = generateVerifyCode(verifySize);
              outputImage(width, height, os, verifyCode);
              return verifyCode;
          }
      
          /**
           * 使用系統預設字元源生成驗證碼
           *
           * @param verifySize 驗證碼長度
           * @return
           */
          public static String generateVerifyCode(int verifySize) {
              return generateVerifyCode(verifySize, VERIFY_CODES);
          }
      
          /**
           * 使用指定源生成驗證碼
           *
           * @param verifySize 驗證碼長度
           * @param sources    驗證碼字元源
           * @return
           */
          public static String generateVerifyCode(int verifySize, String sources) {
              // 未設定展示源的字碼,賦預設值大寫字母+數字
              if (sources == null || sources.length() == 0) {
                  sources = VERIFY_CODES;
              }
              int codesLen = sources.length();
              Random rand = new Random(System.currentTimeMillis());
              StringBuilder verifyCode = new StringBuilder(verifySize);
              for (int i = 0; i < verifySize; i++) {
                  verifyCode.append(sources.charAt(rand.nextInt(codesLen - 1)));
              }
              return verifyCode.toString();
          }
      
          /**
           * 生成隨機驗證碼文件,並返回驗證碼值 (生成圖片形式,用的較少)
           *
           * @param w
           * @param h
           * @param outputFile
           * @param verifySize
           * @return
           * @throws IOException
           */
          public static String outputVerifyImage(int w, int h, File outputFile, int verifySize) throws IOException {
              String verifyCode = generateVerifyCode(verifySize);
              outputImage(w, h, outputFile, verifyCode);
              return verifyCode;
          }
      
      
          /**
           * 生成指定驗證碼圖像文件
           *
           * @param w
           * @param h
           * @param outputFile
           * @param code
           * @throws IOException
           */
          public static void outputImage(int w, int h, File outputFile, String code) throws IOException {
              if (outputFile == null) {
                  return;
              }
              File dir = outputFile.getParentFile();
              //文件不存在
              if (!dir.exists()) {
                  //創建
                  dir.mkdirs();
              }
              try {
                  outputFile.createNewFile();
                  FileOutputStream fos = new FileOutputStream(outputFile);
                  outputImage(w, h, fos, code);
                  fos.close();
              } catch (IOException e) {
                  throw e;
              }
          }
      
          /**
           * 輸出指定驗證碼圖片流
           *
           * @param w
           * @param h
           * @param os
           * @param code
           * @throws IOException
           */
          public static void outputImage(int w, int h, OutputStream os, String code) throws IOException {
              int verifySize = code.length();
              BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
              Random rand = new Random();
              Graphics2D g2 = image.createGraphics();
              g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
      
              // 創建顏色集合,使用java.awt包下的類
              Color[] colors = new Color[5];
              Color[] colorSpaces = new Color[]{Color.WHITE, Color.CYAN,
                      Color.GRAY, Color.LIGHT_GRAY, Color.MAGENTA, Color.ORANGE,
                      Color.PINK, Color.YELLOW};
              float[] fractions = new float[colors.length];
              for (int i = 0; i < colors.length; i++) {
                  colors[i] = colorSpaces[rand.nextInt(colorSpaces.length)];
                  fractions[i] = rand.nextFloat();
              }
              Arrays.sort(fractions);
              // 設置邊框色
              g2.setColor(Color.GRAY);
              g2.fillRect(0, 0, w, h);
      
              Color c = getRandColor(200, 250);
              // 設置背景色
              g2.setColor(c);
              g2.fillRect(0, 2, w, h - 4);
      
              // 繪製干擾線
              Random random = new Random();
              // 設置線條的顏色
              g2.setColor(getRandColor(160, 200));
              for (int i = 0; i < 20; i++) {
                  int x = random.nextInt(w - 1);
                  int y = random.nextInt(h - 1);
                  int xl = random.nextInt(6) + 1;
                  int yl = random.nextInt(12) + 1;
                  g2.drawLine(x, y, x + xl + 40, y + yl + 20);
              }
      
              // 添加噪點
              // 雜訊率
              float yawpRate = 0.05f;
              int area = (int) (yawpRate * w * h);
              for (int i = 0; i < area; i++) {
                  int x = random.nextInt(w);
                  int y = random.nextInt(h);
                  // 獲取隨機顏色
                  int rgb = getRandomIntColor();
                  image.setRGB(x, y, rgb);
              }
              // 添加圖片扭曲
              shear(g2, w, h, c);
      
              g2.setColor(getRandColor(100, 160));
              int fontSize = h - 4;
              Font font = new Font("Algerian", Font.ITALIC, fontSize);
              g2.setFont(font);
              char[] chars = code.toCharArray();
              for (int i = 0; i < verifySize; i++) {
                  AffineTransform affine = new AffineTransform();
                  affine.setToRotation(Math.PI / 4 * rand.nextDouble() * (rand.nextBoolean() ? 1 : -1), (w / verifySize) * i + fontSize / 2, h / 2);
                  g2.setTransform(affine);
                  g2.drawChars(chars, i, 1, ((w - 10) / verifySize) * i + 5, h / 2 + fontSize / 2 - 10);
              }
      
              g2.dispose();
              ImageIO.write(image, "jpg", os);
          }
      
          /**
           * 隨機顏色
           *
           * @param fc
           * @param bc
           * @return
           */
          private static Color getRandColor(int fc, int bc) {
              if (fc > 255) {
                  fc = 255;
              }
              if (bc > 255) {
                  bc = 255;
              }
              int r = fc + random.nextInt(bc - fc);
              int g = fc + random.nextInt(bc - fc);
              int b = fc + random.nextInt(bc - fc);
              return new Color(r, g, b);
          }
      
          private static int getRandomIntColor() {
              int[] rgb = getRandomRgb();
              int color = 0;
              for (int c : rgb) {
                  color = color << 8;
                  color = color | c;
              }
              return color;
          }
      
          private static int[] getRandomRgb() {
              int[] rgb = new int[3];
              for (int i = 0; i < 3; i++) {
                  rgb[i] = random.nextInt(255);
              }
              return rgb;
          }
      
          private static void shear(Graphics g, int w1, int h1, Color color) {
              shearX(g, w1, h1, color);
              shearY(g, w1, h1, color);
          }
      
          private static void shearX(Graphics g, int w1, int h1, Color color) {
              int period = random.nextInt(2);
      
              boolean borderGap = true;
              int frames = 1;
              int phase = random.nextInt(2);
      
              for (int i = 0; i < h1; i++) {
                  double d = (double) (period >> 1)
                          * Math.sin((double) i / (double) period
                          + (6.2831853071795862D * (double) phase)
                          / (double) frames);
                  g.copyArea(0, i, w1, 1, (int) d, 0);
                  if (borderGap) {
                      g.setColor(color);
                      g.drawLine((int) d, i, 0, i);
                      g.drawLine((int) d + w1, i, w1, i);
                  }
              }
          }
      
          private static void shearY(Graphics g, int w1, int h1, Color color) {
              int period = random.nextInt(40) + 10; // 50;
      
              boolean borderGap = true;
              int frames = 20;
              int phase = 7;
              for (int i = 0; i < w1; i++) {
                  double d = (double) (period >> 1)
                          * Math.sin((double) i / (double) period
                          + (6.2831853071795862D * (double) phase)
                          / (double) frames);
                  g.copyArea(i, 0, 1, h1, 0, (int) d);
                  if (borderGap) {
                      g.setColor(color);
                      g.drawLine(i, (int) d, i, 0);
                      g.drawLine(i, (int) d + h1, i, h1);
                  }
              }
          }
      }
      

1.4、MyBatis相關配置準備

  • logback.xml

    • 日誌配置文件

    • <?xml version="1.0" encoding="UTF-8"?>
      <configuration>
          <!--CONSOLE :表示當前的日誌信息是可以輸出到控制台的。-->
          <appender name="Console" class="ch.qos.logback.core.ConsoleAppender">
              <encoder>
                  <pattern>[%level] %blue(%d{HH:mm:ss.SSS}) %cyan([%thread]) %boldGreen(%logger{15}) - %msg %n</pattern>
              </encoder>
          </appender>
      
          <logger name="com.coolman" level="DEBUG" additivity="false">
              <appender-ref ref="Console"/>
          </logger>
      
          <!--level:用來設置列印級別,大小寫無關:TRACE, DEBUG, INFO, WARN, ERROR, ALL 和 OFF, 預設debug
            <root>可以包含零個或多個<appender-ref>元素,標識這個輸出位置將會被本日誌級別控制。-->
          <root level="DEBUG">
              <appender-ref ref="Console"/>
          </root>
      </configuration>
      
  • mybatis-config.xml

    • MyBatis的配置文件

    • <?xml version="1.0" encoding="UTF-8" ?>
      <!DOCTYPE configuration
              PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
              "http://mybatis.org/dtd/mybatis-3-config.dtd">
      <configuration>
          <settings>
      <!--        開啟駝峰命名自動映射-->
              <setting name="mapUnderscoreToCamelCase" value="true"/>
          </settings>
          
          <!--起別名-->
          <typeAliases>
              <package name="com.coolman.pojo"/>
          </typeAliases>
      
          <environments default="development">
              <environment id="development">
                  <transactionManager type="JDBC"/>
                  <dataSource type="POOLED">
                      <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                      <property name="url" value="jdbc:mysql://localhost:3306/sms?serverTimezone=Asia/Shanghai"/>
                      <property name="username" value="root"/>
                      <property name="password" value="123"/>
                  </dataSource>
              </environment>
          </environments>
      
          <mappers>
              <!--掃描mapper-->
              <package name="com.coolman.mapper"/>
          </mappers>
      </configuration>
      

1.5、前端代碼準備

  • css文件夾相關文件

    • login.css

      • * {
            margin: 0;
            padding: 0;
        }
        
        html {
            height: 100%;
            width: 100%;
            overflow: hidden;
            margin: 0;
            padding: 0;
            background: url(../imgs/Desert1.jpg) no-repeat 0px 0px;
            background-repeat: no-repeat;
            background-size: 100% 100%;
            -moz-background-size: 100% 100%;
        }
        
        body {
            display: flex;
            align-items: center;
            justify-content: center;
            height: 100%;
        }
        
        #loginDiv {
            width: 37%;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 380px;
            background-color: rgba(75, 81, 95, 0.3);
            box-shadow: 7px 7px 17px rgba(52, 56, 66, 0.5);
            border-radius: 5px;
        }
        
        #name_trip {
            margin-left: 50px;
            color: red;
        }
        
        p {
            margin-top: 30px;
            margin-left: 20px;
            color: azure;
        }
        
        
        #remember{
            margin-left: 15px;
            border-radius: 5px;
            border-style: hidden;
            background-color: rgba(216, 191, 216, 0.5);
            outline: none;
            padding-left: 10px;
            height: 20px;
            width: 20px;
        }
        #phone_number{
            width: 200px;
            margin-left: 15px;
            border-radius: 5px;
            border-style: hidden;
            height: 30px;
            background-color: rgba(216, 191, 216, 0.5);
            outline: none;
            color: #f0edf3;
            padding-left: 10px;
        }
        #password{
            width: 202px;
            margin-left: 30px;
            border-radius: 5px;
            border-style: hidden;
            height: 30px;
            background-color: rgba(216, 191, 216, 0.5);
            outline: none;
            color: #f0edf3;
            padding-left: 10px;
        }
        .button {
            border-color: cornsilk;
            background-color: rgba(100, 149, 237, .7);
            color: aliceblue;
            border-style: hidden;
            border-radius: 5px;
            width: 100px;
            height: 31px;
            font-size: 16px;
        }
        
        #subDiv {
            text-align: center;
            margin-top: 30px;
        }
        #loginMsg{
            text-align: center;
            color: aliceblue;
        }
        #errorMsg{
            text-align: center;
            color:red;
        }
        
    • register.css

      • * {
            margin: 0;
            padding: 0;
            list-style-type: none;
        }
        .reg-content{
            padding: 30px;
            margin: 3px;
        }
        a, img {
            border: 0;
        }
        
        body {
            background-image: url("../imgs/reg_bg_min.jpg") ;
            text-align: center;
        }
        
        table {
            border-collapse: collapse;
            border-spacing: 0;
        }
        
        td, th {
            padding: 0;
            height: 90px;
        
        }
        .inputs{
            vertical-align: top;
        }
        
        .clear {
            clear: both;
        }
        
        .clear:before, .clear:after {
            content: "";
            display: table;
        }
        
        .clear:after {
            clear: both;
        }
        
        .form-div {
            background-color: rgba(255, 255, 255, 0.27);
            border-radius: 10px;
            border: 1px solid #aaa;
            width: 424px;
            margin-top: 150px;
            margin-left:1050px;
            padding: 30px 0 20px 0px;
            font-size: 16px;
            box-shadow: inset 0px 0px 10px rgba(255, 255, 255, 0.5), 0px 0px 15px rgba(75, 75, 75, 0.3);
            text-align: left;
        }
        
        .form-div input[type="text"], .form-div input[type="password"], .form-div input[type="email"] {
            width: 268px;
            margin: 10px;
            line-height: 20px;
            font-size: 16px;
        }
        
        .form-div input[type="checkbox"] {
            margin: 20px 0 20px 10px;
        }
        
        .form-div input[type="button"], .form-div input[type="submit"] {
            margin: 10px 20px 0 0;
        }
        
        .form-div table {
            margin: 0 auto;
            text-align: right;
            color: rgba(64, 64, 64, 1.00);
        }
        
        .form-div table img {
            vertical-align: middle;
            margin: 0 0 5px 0;
        }
        
        .footer {
            color: rgba(64, 64, 64, 1.00);
            font-size: 12px;
            margin-top: 30px;
        }
        
        .form-div .buttons {
            float: right;
        }
        
        input[type="text"], input[type="password"], input[type="email"] {
            border-radius: 8px;
            box-shadow: inset 0 2px 5px #eee;
            padding: 10px;
            border: 1px solid #D4D4D4;
            color: #333333;
            margin-top: 5px;
        }
        
        input[type="text"]:focus, input[type="password"]:focus, input[type="email"]:focus {
            border: 1px solid #50afeb;
            outline: none;
        }
        
        input[type="button"], input[type="submit"] {
            padding: 7px 15px;
            background-color: #3c6db0;
            text-align: center;
            border-radius: 5px;
            overflow: hidden;
            min-width: 80px;
            border: none;
            color: #FFF;
            box-shadow: 1px 1px 1px rgba(75, 75, 75, 0.3);
        }
        
        input[type="button"]:hover, input[type="submit"]:hover {
            background-color: #5a88c8;
        }
        
        input[type="button"]:active, input[type="submit"]:active {
            background-color: #5a88c8;
        }
        .phone_number_err_msg{
            color: red;
            padding-right: 170px;
        }
        
        #password_err,#tel_err{
            padding-right: 195px;
        }
        
        #reg_btn{
            margin-right:50px; width: 285px; height: 45px; margin-top:20px;
        }
        
        #checkCode{
            width: 100px;
        }
        
        #changeImg{
            color: aqua;
        }
        
  • img文件夾相關圖片

    • Desert1.jpg
    • reg_bg_min.jpg
  • JSP相關文件

    • addStudnet.jsp

      • <%@ page contentType="text/html;charset=UTF-8" language="java" %>
        <html>
        <head>
            <title>添加學生信息</title>
        </head>
        <body>
        
        <h3 align="center" style="color: red">添加學生信息</h3>
        <form action="addStudentServlet" method="post">
            <div align="center">
                <span>學號:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                    <input name="stuNumber"><br>
                </span>
                <span>姓名:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                    <input name="name"><br>
                </span>
                <span>年齡:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                    <input name="age"><br>
                </span>
                <span>性別:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                    <input name="sex"><br>
                </span>
                <span>語文成績:
                    <input name="chineseScore"><br>
                </span>
                <span>數學成績:
                    <input name="mathScore"><br>
                </span>
                <span>英語成績:
                    <input name="englishScore"><br>
                </span>
        
                <input type="submit" value="提交">
            </div>
        </form>
        </body>
        </html>
        
    • login.jsp

      • <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
        <%@ page contentType="text/html;charset=UTF-8" language="java" %>
        <!DOCTYPE html>
        <html lang="en">
        
        <head>
            <meta charset="UTF-8">
            <title>login</title>
            <link href="css/login.css" rel="stylesheet">
        </head>
        
        <body>
        <div id="loginDiv" style="height: 350px">
            <form action="loginServlet" method="post" id="form">
                <h1 id="loginMsg">登 錄</h1>
                <div id="errorMsg">${loginMessage} ${registerMessage}</div>
                <p>用戶名:<input id="phone_number" name="phone_number" type="text" value="${cookie.cookie_phone_number.value}"></p>
                <p>密碼:<input id="password" name="password" type="password" value="${cookie.cookie_password.value}"></p>
                <div style="text-align: center">
                    <c:if test="${cookie.cookie_phone_number.value != null}">
                        <p>記住我: <input name="remember" type="checkbox" value="1" checked="checked"></p>
                    </c:if>
                    <c:if test="${cookie.cookie_phone_number.value == null}">
                        <p>記住我: <input name="remember" type="checkbox" value="1"></p>
                    </c:if>
                </div>
                <div id="subDiv">
                    <input type="submit" class="button" value="登 錄">
                    <input type="reset" class="button" value="reset">&nbsp;&nbsp;&nbsp;
                    <a href="register.jsp">沒有賬號?</a>
                </div>
            </form>
        </div>
        </body>
        <%--<script>--%>
        <%--    document.querySelectorAll('.inputs')[3].removeAttribute("check")--%>
        <%--</script>--%>
        </html>
        
    • register.jsp

      • <%@ page contentType="text/html;charset=UTF-8" language="java" %>
        <!DOCTYPE html>
        <html lang="en">
        <head>
            <meta charset="UTF-8">
            <title>歡迎註冊</title>
            <link href="css/register.css" rel="stylesheet">
        </head>
        <body>
        
        <div class="form-div">
            <div class="reg-content">
                <h1>歡迎註冊</h1>
                <span>已有帳號?</span> <a href="login.jsp">登錄</a>
            </div>
            <form id="reg-form" action="registerServlet" method="post">
                <table>
                    <tr>
                        <td>姓名</td>
                        <td class="inputs">
                            <input name="username" type="text" id="username">
                            <br>
                        </td>
                    </tr>
                    <tr>
                        <td>手機號碼</td>
                        <td class="inputs">
                            <input name="phone_number" type="text" id="phone_number">
                            <br>
                            <span id="phone_number_err" class="phone_number_err_msg">${phone_number_err_msg}</span>
                        </td>
                    </tr>
        
                    <tr>
                        <td>密碼</td>
                        <td class="inputs">
                            <input name="password" type="password" id="password">
                            <br>
                        </td>
                    </tr>
        
                    <tr>
                        <td>驗證碼:</td>
                        <td class="inputs">
                            <input name="checkCode" type="text" id="checkCode">
                            <img id="checkCodeImg" src="checkCodeServlet">
                            <a href="#" id="changeImg">看不清?</a>
                            <p  style="color: red"  align="left" id="checkCode_err" class="checkCode_err_msg">
                                ${checkCode_err_msg}
                            </p>
                        </td>
                    </tr>
        <%--            <tr>--%>
        <%--                <td></td>--%>
        <%--                <td style="color: red" align="center" id="checkCode_err" class="checkCode_err_msg">${checkCode_err_msg}</td>--%>
        <%--            </tr>--%>
        
                </table>
        
                <div class="buttons">
                    <input value="註 冊" type="submit" id="reg_btn">
                </div>
                <br class="clear">
            </form>
        </div>
        
        <script>
            // 點擊換圖片
            document.getElementById("changeImg").onclick = function () {
                let time = new Date().getTime();
        
                // 找到img標簽,更換src屬性, 如果src相同,不會更換圖片
                document.getElementById("checkCodeImg").src = "checkCodeServlet?time=" + time;
            }
        </script>
        </body>
        </html>
        
    • studentList.jsp

      • <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
        <%@ page contentType="text/html;charset=UTF-8" language="java" %>
        
        <!DOCTYPE html>
        <html lang="en">
        <head>
            <meta charset="UTF-8">
            <title>Title</title>
        </head>
        <body>
        <h1 style="color: red" align="center">歡迎您: ${username} 登錄成功, 來到學生信息管理系統</h1>
        <br>
        <hr>
        <table border="1" cellspacing="0" width="800" align="center">
            <tr>
                <th>序號</th>
                <th>學號</th>
                <th>姓名</th>
                <th>年齡</th>
                <th>性別</th>
                <th>語文成績</th>
                <th>數學成績</th>
                <th>英語成績</th>
                <th>操作</th>
            </tr>
        
            <c:forEach items="${students}" var="student" varStatus="varSta">
                <tr align="center">
                    <td>${varSta.count}</td>
                    <td>${student.stuNumber}</td>
                    <td>${student.name}</td>
                    <td>${student.age}</td>
                    <td>${student.sex}</td>
                    <td>${student.chineseScore}</td>
                    <td>${student.mathScore}</td>
                    <td>${student.englishScore}</td>
                    <td><a href="updateBrand.jsp?id=${student.id}">修改</a> <a href="DeleteStudentByIdServlet?id=${student.id}">刪除</a></td>
                </tr>
            </c:forEach>
        
            <tr align="center">
                <td></td>
                <td></td>
                <td></td>
                <td></td>
                <td></td>
                <td></td>
                <td></td>
                <td></td>
                <td><input type="button" value="新增學生信息" onclick="location.href=('addStudent.jsp')"></td>
            </tr>
        </table>
        
        </body>
        </html>
        
    • updateBrand.jsp

      • <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
        <%@ page contentType="text/html;charset=UTF-8" language="java" %>
        <html>
        <head>
            <title>修改品牌</title>
        </head>
        <body>
        <%
            String id = request.getParameter("id");
        %>
        <h3>修改品牌</h3>
        <form action="updateStudentByIdServlet" method="post">
            <div align="center">
                <input type="hidden" name="id" value="<%=id%>">
                <span>學號:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                    <input name="stuNumber"><br>
                </span>
                <span>姓名:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                    <input name="name"><br>
                </span>
                <span>年齡:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                    <input name="age"><br>
                </span>
                <span>性別:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                    <input name="sex"><br>
                </span>
                <span>語文成績:
                    <input name="chineseScore"><br>
                </span>
                <span>數學成績:
                    <input name="mathScore"><br>
                </span>
                <span>英語成績:
                    <input name="englishScore"><br>
                </span>
        
                <input type="submit" value="提交">
            </div>
        </form>
        
        </body>
        </html>
        
        

2、編碼實現

2.1、登錄註冊

2.1.1、登錄

Servlet實現
  • package com.coolman.web;
    
    import com.coolman.pojo.User;
    import com.coolman.service.UserService;
    
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.*;
    import java.io.IOException;
    
    @WebServlet("/loginServlet")
    public class LoginServlet extends HttpServlet {
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            doGet(request, response);
        }
    
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            // 在這裡處理請求
    
            // 獲取登錄頁面POST請求傳遞迴來的參數
            String phoneNumber = request.getParameter("phone_number");
            String password = request.getParameter("password");
            String remember = request.getParameter("remember");
    
            // 調用服務查詢該用戶是否存在
            User user = new UserService().selectUserByPhoneNumberAndPassword(phoneNumber, password);
    
            // 如果用戶存在
            if (user != null) {
                // “記住我”功能
                // 如果用戶勾選了記住我,那麼就將該數據存儲至cookie中,交由客戶端保存
                Cookie phoneNumberCookie = new Cookie("cookie_phone_number", phoneNumber);
                Cookie passwordCookie = new Cookie("cookie_password", password);
                if ("1".equals(remember)) {
                    // 如果勾選
    
                    response.addCookie(phoneNumberCookie);
                    response.addCookie(passwordCookie);
    
                    System.out.println("用戶勾選了“記住我”功能,並將數據保存到了cookie當中");
    
                } else {
                    phoneNumberCookie.setMaxAge(0);
                    passwordCookie.setMaxAge(0);
                    response.addCookie(phoneNumberCookie);
                    response.addCookie(passwordCookie);
                }
    
                // 將用戶信息存儲在Session中,並跳轉到信息展示列表頁
                HttpSession session = request.getSession();
                session.setAttribute("username", user.getName());
    
                // 跳轉到信息展示列表頁
                response.sendRedirect("selectAllStudentsServlet");
            } else {
                // 如果用戶不存在
                // 提示錯誤信息
                request.setAttribute("loginMessage", "用戶名或者密碼錯誤!");
    
                // 請求轉發重新回到登錄界面
                request.getRequestDispatcher("login.jsp").forward(request, response);
            }
    
        }
    }
    
    
Service實現
  • // 根據賬號和密碼查詢用戶
        public User selectUserByPhoneNumberAndPassword(String phoneNumber, String password) {
            SqlSession sqlSession = MyBatisUtils.openSession();
    
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    
            User user = mapper.selectUserByPhoneNumberAndPassword(phoneNumber, password);
    
            sqlSession.close();
    
            return user;
        }
    
mapper實現
  •     // 根據賬號和密碼查詢用戶
        @Select("select * from sms.user where phone_number = #{phoneNumber} and password = #{password};")
        User selectUserByPhoneNumberAndPassword(@Param("phoneNumber") String phoneNumber, @Param("password") String password);
    
    

2.1.2、註冊

Servlet實現
  • RegisterServlet

    • package com.coolman.web;
      
      import com.coolman.pojo.User;
      import com.coolman.service.UserService;
      
      import javax.servlet.ServletException;
      import javax.servlet.annotation.WebServlet;
      import javax.servlet.http.HttpServlet;
      import javax.servlet.http.HttpServletRequest;
      import javax.servlet.http.HttpServletResponse;
      import javax.servlet.http.HttpSession;
      import java.io.IOException;
      
      @WebServlet("/registerServlet")
      public class RegisterServlet extends HttpServlet {
          protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
              doGet(request, response);
          }
      
          protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
              // 在這裡處理請求
              // 獲取表單參數
      
              String username = request.getParameter("username");
              String phoneNumber = request.getParameter("phone_number");
              String password = request.getParameter("password");
              String checkCode = request.getParameter("checkCode");
      
              // 獲取正確的驗證碼
              HttpSession session = request.getSession();
              String correctCode = (String) session.getAttribute("correctCode");
      
              // 判斷phoneNumber是否唯一
              // 查詢資料庫,調用服務
              UserService service = new UserService();
              User user = service.selectUserByPhoneNumber(phoneNumber);
      
              if (user == null) {
                  // user 為空,說明不存在該用戶,所以可以創建賬號
                  // 調用服務,添加用戶
                  // 判斷驗證碼是否輸入正確(忽略大小寫)
                  if (correctCode.equalsIgnoreCase(checkCode)) {
                      // 如果驗證碼輸入正確
                      // 調用服務,添加用戶
                      service.addUser(new User(0, username, phoneNumber, password));
      
                      request.setAttribute("registerMessage", "註冊成功,請登錄");
                      request.getRequestDispatcher("login.jsp").forward(request, response);
                  } else {
                      // 如果輸入錯誤
                      // 給出錯誤信息,驗證碼輸入錯誤!
                      request.setAttribute("checkCode_err_msg", "驗證碼輸入錯誤!");
                      request.getRequestDispatcher("register.jsp").forward(request, response);
                  }
      
              } else {
                  // 給出錯誤信息:手機號碼重覆!
                  request.setAttribute("phone_number_err_msg", "手機號碼重覆,請重新輸入!");
                  // 請求轉發回去給register.jsp
                  request.getRequestDispatcher("register.jsp").forward(request, response);
              }
      
          }
      }
      
      
  • CheckCodeServlet

    • package com.coolman.web;
      
      import com.coolman.utils.CheckCodeUtil;
      
      import javax.servlet.ServletException;
      import javax.servlet.ServletOutputStream;
      import javax.servlet.annotation.WebServlet;
      import javax.servlet.http.HttpServlet;
      import javax.servlet.http.HttpServletRequest;
      import javax.servlet.http.HttpServletResponse;
      import javax.servlet.http.HttpSession;
      import java.io.IOException;
      
      @WebServlet("/checkCodeServlet")
      public class CheckCodeServlet extends HttpServlet {
          protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
              doGet(request, response);
          }
      
          protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
              // 在這裡處理請求
              // 獲取驗證碼
              // 創建一個輸出流
              ServletOutputStream out = response.getOutputStream();
              String correctCode = CheckCodeUtil.outputVerifyImage(100, 40, out, 4);
      
              // 將正確的驗證碼存儲到Session中
              HttpSession session = request.getSession();
      
              session.setAttribute("correctCode", correctCode);
          }
      }
      
      
Service實現
  •     // 根據賬號查詢用戶
        public User selectUserByPhoneNumber(String phoneNumber) {
            SqlSession sqlSession = MyBatisUtils.openSession();
    
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    
            User user = mapper.selectUserByPhoneNumber(phoneNumber);
    
            sqlSession.close();
    
            return user;
        }
        // 添加用戶
        public void addUser(User user) {
            SqlSession sqlSession = MyBatisUtils.openSession();
    
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    
            mapper.addUser(user);
    
            sqlSession.commit();
            sqlSession.close();
        }
    
mapper實現
  •     // 根據賬號查詢用戶
        @Select("select * from sms.user where phone_number = #{phoneNumber}")
        User selectUserByPhoneNumber(String phoneNumber);
    
        // 添加用戶
        @Insert("insert into sms.user values (null, #{name}, #{phoneNumber}, #{password});")
        void addUser(User user);
    
    

2.2、查詢學生信息列表

Servlet實現

  • package com.coolman.web;
    
    import com.coolman.pojo.Student;
    import com.coolman.service.StudentService;
    
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;
    import java.util.List;
    
    @WebServlet("/selectAllStudentsServlet")
    public class SelectAllStudentsServlet extends HttpServlet {
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            doGet(request, response);
        }
    
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            // 在這裡處理請求
            List<Student> students = new StudentService().selectAllStudent();
    
            request.setAttribute("students", students);
    
            request.getRequestDispatcher("studentList.jsp").forward(request, response);
        }
    }
    
    

Service實現

  •     // 查詢所有學生信息
        public List<Student> selectAllStudent() {
            SqlSession sqlSession = MyBatisUtils.openSession();
    
            StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
    
            List<Student> students = mapper.selectAllStudents();
    
            sqlSession.close();
    
            return students;
        }
    

mapper實現

  •     // 查詢所有學生信息
        @Select("select * from sms.student;")
        List<Student> selectAllStudents();
    

2.3、學生信息更新

這裡我沒有做數據回顯,有興趣的可以做一下

2.3.1、添加

Servlet實現
  • package com.coolman.web;
    
    import com.coolman.pojo.Student;
    import com.coolman.service.StudentService;
    import org.apache.commons.beanutils.BeanUtils;
    
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;
    import java.lang.reflect.InvocationTargetException;
    import java.util.Map;
    
    @WebServlet("/addStudentServlet")
    public class AddStudentServlet extends HttpServlet {
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            doGet(request, response);
        }
    
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            // 在這裡處理請求
            Map<String, String[]> map = request.getParameterMap();
    
            Student student = new Student();
    
            try {
                BeanUtils.populate(student, map);
            } catch (IllegalAccessException | InvocationTargetException e) {
                e.printStackTrace();
            }
    
    //        System.out.println(student);
    
            // 調用服務
            StudentService service = new StudentService();
            service.addStudent(student);
    
            response.sendRedirect("selectAllStudentsServlet");
        }
    }
    
    
Service實現
  •     // 新增學生信息
        public void addStudent(Student student) {
            SqlSession sqlSession = MyBatisUtils.openSession();
    
            StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
    
            mapper.addStudent(student);
    
            sqlSession.commit();
            sqlSession.close();
    
        }
    
mapper實現
  •     // 新增學生信息
        @Insert("insert into sms.student values (null, #{stuNumber}, #{name}, #{age}, #{sex}, #{chineseScore}, " +
                "#{mathScore}, #{englishScore});")
        void addStudent(Student student);
    

2.3.2、刪除

Servlet實現
  • package com.coolman.web;
    
    import com.coolman.service.StudentService;
    
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;
    
    @WebServlet("/DeleteStudentByIdServlet")
    public class DeleteStudentByIdServlet extends HttpServlet {
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            doGet(request, response);
        }
    
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            // 在這裡處理請求
    
            // 獲取id
            int sid = Integer.parseInt(request.getParameter("id"));
    
            // 調用服務
            StudentService service = new StudentService();
            service.deleteStudentById(sid);
    
            response.sendRedirect("selectAllStudentsServlet");
    
        }
    }
    
    
Service實現
  •     // 刪除學生信息
        public void deleteStudentById(int sid) {
            SqlSession sqlSession = MyBatisUtils.openSession();
    
            StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
    
            mapper.deleteStudentById(sid);
    
            sqlSession.commit();
            sqlSession.close();
    
        }
    
mapper實現
  •     // 刪除學生信息
        @Delete("delete from sms.student where id = #{sid};")
        void deleteStudentById(int sid);
    

2.3.3、修改

Servlet實現
  • package com.coolman.web;
    
    import com.coolman.pojo.Student;
    import com.coolman.service.StudentService;
    import org.apache.commons.beanutils.BeanUtils;
    
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;
    import java.lang.reflect.InvocationTargetException;
    import java.util.Map;
    
    @WebServlet("/updateStudentByIdServlet")
    public class UpdateStudentByIdServlet extends HttpServlet {
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            doGet(request, response);
        }
    
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            // 在這裡處理請求
            request.setCharacterEncoding("utf-8");
            Map<String, String[]> map = request.getParameterMap();
            Student student = new Student();
    
            try {
                BeanUtils.populate(student, map);
            } catch (IllegalAccessException | InvocationTargetException e) {
                e.printStackTrace();
            }
    
    //        System.out.println(student);
            StudentService service = new StudentService();
    
            service.updateStudentById(student);
    
            response.sendRedirect("selectAllStudentsServlet");
        }
    }
    
    
Service實現
  •     // 根據學生id修改學生數據
        public void updateStudentById(Student student) {
            SqlSession sqlSession = MyBatisUtils.openSession();
    
            StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
    
            mapper.updateStudentById(student);
    
            sqlSession.commit();
            sqlSession.close();
        }
    
mapper實現
  • 
        // 根據學生id修改學生數據
        @Update("update sms.student set stu_number = #{stuNumber}, name = #{name}, age = #{age}, sex = #{sex}, " +
                "chinese_score = #{chineseScore}, math_score = #{mathScore}, " +
                "english_score = #{englishScore} where id = #{id};")
        void updateStudentById(Student student);
    
  • 至此功能已經基本實現完成,直接添加到Tomcat項目中啟動即可,不過這個案例有很多不足的地方,可自行修改;最終目錄結構如下所示


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 一個工作薄中快速新建多個數據表 一、建立數據源數表 將所有數據統一錄入到本數據源表中,併進行統一排列數據。 註意:這裡的序號很重要,是對應後面工作表格獲取數據的來源,具體見公式設置。 二、建立一個表格模板 ① 將自己需要的表格進行製作及調整格式。 註意:做好表格列印格式調整。 ② 表格做好讀取表格名 ...
  • 1.用戶定義 在前面的案例中,我們的登錄用戶是基於配置文件來配置的(本質是基於記憶體),但是在實際開發中,這種方式肯定是不可取的,在實際項目中,用戶信息肯定要存入資料庫之中。 Spring Security支持多種用戶定義方式,接下來我們就逐個來看一下這些定義方式。通過前面的介紹(參見3小節),大家對 ...
  • 目錄 一.簡介 二.效果演示 三.源碼下載 四.猜你喜歡 零基礎 OpenGL (ES) 學習路線推薦 : OpenGL (ES) 學習目錄 >> OpenGL ES 基礎 零基礎 OpenGL (ES) 學習路線推薦 : OpenGL (ES) 學習目錄 >> OpenGL ES 轉場 零基礎 O ...
  • 1.文件上傳 新建空項目 準備工作 在maven倉庫里下載commons io 和 commons fileupload兩個jar包 實用類介紹 文件上傳註意事項 為保證伺服器安全,上傳文件應該放在外界無法直接訪問的目錄下,比如放在WEB-INF目錄下 為防止文件覆蓋現象發生,要為上傳文件產生一個唯 ...
  • Java概述 什麼是Java? Java 是一種編程語言和計算平臺,由 Sun Microsystems 在 1995 年首次發佈。它從微末起步,逐漸發展為當今數字世界中很大一部分資產所依賴的基礎,是用於構建許多服務和應用程式的可靠平臺。面向未來的創新產品和數字服務也仍然依賴 Java。 儘管大多數 ...
  • 使用django+websocket+redis+channels實現簡易聊天室 1.創建一個django項目 從存儲項目的文件夾進入cmd命令行終端,輸入以下命令創建chatroom項目 django-admin startproject chatroom 然後再進入項目文件夾,打開cmd命令行終 ...
  • 0、綜合案例功能介紹 以上是在綜合案例要實現的功能。除了對數據的增刪改查功能之外,還有一些複雜的功能,如批量刪除,分頁查詢,條件查詢等功能 批量刪除功能:每條數據前都有覆選框,當我們選中多條數據並點擊批量刪除按鈕後,會發送請求到後端並刪除資料庫指定的多條數據 分頁查詢功能:當資料庫中有很多數據的時候 ...
  • selenium介紹 由於requests模塊不能執行js,有的頁面內容,我們在瀏覽器中可以看到,但是請求下來沒有。 selenium模塊:模擬操作瀏覽器,完成人的行為。 selenium本質是通過驅動瀏覽器,完全模擬瀏覽器的操作,比如跳轉、輸入、點擊、下拉等,來拿到網頁渲染之後的結果,可支持多種瀏 ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...