基于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项目中启动即可,不过这个案例有很多不足的地方,可自行修改;最终目录结构如下所示