08-基于JSP&Session&Cookie的学生管理系统

打印 上一主题 下一主题

主题 895|帖子 895|积分 2685

基于JSP&Session&Cookie的学生管理系统

因为本次系统仅作为练手和熟悉基本的MVC编程,所以仅供参考
1、环境准备

1.0、项目配置文件准备


  • WEB-INF/web.xml

      1. <?xml version="1.0" encoding="UTF-8"?>
      2. <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
      3.         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      4.         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
      5.         version="4.0">
      6.        
      7.         <welcome-file-list>
      8.                 <welcome-file>login.jsp</welcome-file>
      9.         </welcome-file-list>
      10. </web-app>
      复制代码

  • pom.xml

      1. <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">  
      2.   <modelVersion>4.0.0</modelVersion>
      3.   <groupId>com.coolman</groupId>  
      4.   <artifactId>_03StudentManagerSystemBaseOnJSPAndTomcat</artifactId>  
      5.   <version>1.0-SNAPSHOT</version>  
      6.   <packaging>war</packaging>
      7.   <properties>
      8.     <maven.compiler.source>8</maven.compiler.source>  
      9.     <maven.compiler.target>8</maven.compiler.target>
      10.   </properties>
      11.   <dependencies>
      12.    
      13.     <dependency>
      14.       <groupId>mysql</groupId>
      15.       <artifactId>mysql-connector-java</artifactId>
      16.       <version>8.0.22</version>
      17.     </dependency>
      18.    
      19.     <dependency>
      20.       <groupId>org.mybatis</groupId>
      21.       <artifactId>mybatis</artifactId>
      22.       <version>3.5.5</version>
      23.     </dependency>
      24.    
      25.    
      26.     <dependency>
      27.       <groupId>org.slf4j</groupId>
      28.       <artifactId>slf4j-api</artifactId>
      29.       <version>1.7.20</version>
      30.     </dependency>
      31.    
      32.     <dependency>
      33.       <groupId>ch.qos.logback</groupId>
      34.       <artifactId>logback-classic</artifactId>
      35.       <version>1.2.3</version>
      36.     </dependency>
      37.    
      38.     <dependency>
      39.       <groupId>ch.qos.logback</groupId>
      40.       <artifactId>logback-core</artifactId>
      41.       <version>1.2.3</version>
      42.     </dependency>
      43.    
      44.     <dependency>
      45.       <groupId>javax.servlet</groupId>
      46.       <artifactId>javax.servlet-api</artifactId>
      47.       <version>3.1.0</version>
      48.       <scope>provided</scope>
      49.     </dependency>
      50.    
      51.     <dependency>
      52.       <groupId>javax.servlet.jsp</groupId>
      53.       <artifactId>jsp-api</artifactId>
      54.       <version>2.2</version>
      55.       <scope>provided</scope>
      56.     </dependency>
      57.    
      58.     <dependency>
      59.       <groupId>jstl</groupId>
      60.       <artifactId>jstl</artifactId>
      61.       <version>1.2</version>
      62.     </dependency>
      63.       <dependency>
      64.           <groupId>commons-beanutils</groupId>
      65.           <artifactId>commons-beanutils</artifactId>
      66.           <version>1.9.1</version>
      67.       </dependency>
      68.   </dependencies>
      69.   
      70.     <build>
      71.         <plugins>
      72.             <plugin>
      73.                
      74.                 <groupId>org.apache.tomcat.maven</groupId>
      75.                 <artifactId>tomcat7-maven-plugin</artifactId>
      76.                 <version>2.2</version>
      77.                 <configuration>
      78.                     
      79.                     <port>80</port>   
      80.                     <path>/</path>  
      81.                     
      82.                     <uriEncoding>UTF-8</uriEncoding>
      83.                 </configuration>
      84.             </plugin>
      85.         </plugins>
      86.     </build>
      87. </project>
      复制代码

1.1、数据库准备


  • 因为设计的比较简单,只要登录用户和学生信息,大家可以自行设计数据库,并导入自定义数据
1.2、实体类准备


  • User类

      1. package com.coolman.pojo;
      2. public class User {
      3.     private int id;
      4.     private String name;
      5.     private String phoneNumber;
      6.     private String password;
      7.     public User() {
      8.     }
      9.     public User(int id, String name, String phoneNumber, String password) {
      10.         this.id = id;
      11.         this.name = name;
      12.         this.phoneNumber = phoneNumber;
      13.         this.password = password;
      14.     }
      15.     /**
      16.      * 获取
      17.      * @return id
      18.      */
      19.     public int getId() {
      20.         return id;
      21.     }
      22.     /**
      23.      * 设置
      24.      * @param id
      25.      */
      26.     public void setId(int id) {
      27.         this.id = id;
      28.     }
      29.     /**
      30.      * 获取
      31.      * @return name
      32.      */
      33.     public String getName() {
      34.         return name;
      35.     }
      36.     /**
      37.      * 设置
      38.      * @param name
      39.      */
      40.     public void setName(String name) {
      41.         this.name = name;
      42.     }
      43.     /**
      44.      * 获取
      45.      * @return phoneNumber
      46.      */
      47.     public String getPhoneNumber() {
      48.         return phoneNumber;
      49.     }
      50.     /**
      51.      * 设置
      52.      * @param phoneNumber
      53.      */
      54.     public void setPhoneNumber(String phoneNumber) {
      55.         this.phoneNumber = phoneNumber;
      56.     }
      57.     /**
      58.      * 获取
      59.      * @return password
      60.      */
      61.     public String getPassword() {
      62.         return password;
      63.     }
      64.     /**
      65.      * 设置
      66.      * @param password
      67.      */
      68.     public void setPassword(String password) {
      69.         this.password = password;
      70.     }
      71.     public String toString() {
      72.         return "User{id = " + id + ", name = " + name + ", phoneNumber = " + phoneNumber + ", password = " + password + "}";
      73.     }
      74. }
      复制代码

  • Student类

      1. package com.coolman.pojo;
      2. public class Student {
      3.     private int id;
      4.     private String stuNumber;
      5.     private String name;
      6.     private int age;
      7.     private String sex;
      8.     private double chineseScore;
      9.     private double mathScore;
      10.     private double englishScore;
      11.     public Student() {
      12.     }
      13.     public Student(int id, String stuNumber, String name, int age, String sex, double chineseScore, double mathScore, double englishScore) {
      14.         this.id = id;
      15.         this.stuNumber = stuNumber;
      16.         this.name = name;
      17.         this.age = age;
      18.         this.sex = sex;
      19.         this.chineseScore = chineseScore;
      20.         this.mathScore = mathScore;
      21.         this.englishScore = englishScore;
      22.     }
      23.     /**
      24.      * 获取
      25.      * @return id
      26.      */
      27.     public int getId() {
      28.         return id;
      29.     }
      30.     /**
      31.      * 设置
      32.      * @param id
      33.      */
      34.     public void setId(int id) {
      35.         this.id = id;
      36.     }
      37.     /**
      38.      * 获取
      39.      * @return stuNumber
      40.      */
      41.     public String getStuNumber() {
      42.         return stuNumber;
      43.     }
      44.     /**
      45.      * 设置
      46.      * @param stuNumber
      47.      */
      48.     public void setStuNumber(String stuNumber) {
      49.         this.stuNumber = stuNumber;
      50.     }
      51.     /**
      52.      * 获取
      53.      * @return name
      54.      */
      55.     public String getName() {
      56.         return name;
      57.     }
      58.     /**
      59.      * 设置
      60.      * @param name
      61.      */
      62.     public void setName(String name) {
      63.         this.name = name;
      64.     }
      65.     /**
      66.      * 获取
      67.      * @return age
      68.      */
      69.     public int getAge() {
      70.         return age;
      71.     }
      72.     /**
      73.      * 设置
      74.      * @param age
      75.      */
      76.     public void setAge(int age) {
      77.         this.age = age;
      78.     }
      79.     /**
      80.      * 获取
      81.      * @return sex
      82.      */
      83.     public String getSex() {
      84.         return sex;
      85.     }
      86.     /**
      87.      * 设置
      88.      * @param sex
      89.      */
      90.     public void setSex(String sex) {
      91.         this.sex = sex;
      92.     }
      93.     /**
      94.      * 获取
      95.      * @return chineseScore
      96.      */
      97.     public double getChineseScore() {
      98.         return chineseScore;
      99.     }
      100.     /**
      101.      * 设置
      102.      * @param chineseScore
      103.      */
      104.     public void setChineseScore(double chineseScore) {
      105.         this.chineseScore = chineseScore;
      106.     }
      107.     /**
      108.      * 获取
      109.      * @return mathScore
      110.      */
      111.     public double getMathScore() {
      112.         return mathScore;
      113.     }
      114.     /**
      115.      * 设置
      116.      * @param mathScore
      117.      */
      118.     public void setMathScore(double mathScore) {
      119.         this.mathScore = mathScore;
      120.     }
      121.     /**
      122.      * 获取
      123.      * @return englishScore
      124.      */
      125.     public double getEnglishScore() {
      126.         return englishScore;
      127.     }
      128.     /**
      129.      * 设置
      130.      * @param englishScore
      131.      */
      132.     public void setEnglishScore(double englishScore) {
      133.         this.englishScore = englishScore;
      134.     }
      135.     public String toString() {
      136.         return "Student{id = " + id + ", stuNumber = " + stuNumber + ", name = " + name + ", age = " + age + ", sex = " + sex + ", chineseScore = " + chineseScore + ", mathScore = " + mathScore + ", englishScore = " + englishScore + "}";
      137.     }
      138. }
      复制代码

1.3、工具类准备


  • MyBatisUtils工具类

    • 用来指定MyBatis的配置文件和创建SqlSession或者SqlSessionFactory实例
      1. package com.coolman.utils;
      2. import org.apache.ibatis.io.Resources;
      3. import org.apache.ibatis.session.SqlSession;
      4. import org.apache.ibatis.session.SqlSessionFactory;
      5. import org.apache.ibatis.session.SqlSessionFactoryBuilder;
      6. import java.io.IOException;
      7. import java.io.InputStream;
      8. // 这是MyBatis的工具类,简化MyBatis代码
      9. public class MyBatisUtils {
      10.     private static SqlSessionFactory sqlSessionFactory;
      11.     // 我们只需要一个SqlSessionFactory,在静态代码块中创建SqlSessionFactory
      12.     static {
      13.         try {
      14.             // 编写代码让MyBatis跑起来,执行SQL语句
      15.             String resource = "mybatis-config.xml";
      16.             // 加载核心配置文件
      17.             InputStream inputStream = Resources.getResourceAsStream(resource);
      18.             // 得到SqlSession工厂,赋值给成员变量
      19.             sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
      20.         } catch (IOException e) {
      21.             e.printStackTrace();
      22.         }
      23.     }
      24.     // 返回SqlSessionFactory
      25.     public static SqlSessionFactory getSqlSessionFactory() {
      26.         return sqlSessionFactory;
      27.     }
      28.     // 返回SqlSession
      29.     public static SqlSession openSession() {
      30.         return sqlSessionFactory.openSession();
      31.     }
      32.     public static SqlSession openSession(boolean autoCommit) {
      33.         return sqlSessionFactory.openSession(autoCommit);
      34.     }
      35. }
      复制代码

  • CheckCodeUtils工具类

    • 用来生成验证码的工具类,其原理可以参考像关于Java的awt图像生成和验证码生成原理相关博客;(复制使用即可,原理不用深究)
      1. package com.coolman.utils;
      2. import javax.imageio.ImageIO;
      3. import java.awt.*;
      4. import java.awt.geom.AffineTransform;
      5. import java.awt.image.BufferedImage;
      6. import java.io.File;
      7. import java.io.FileOutputStream;
      8. import java.io.IOException;
      9. import java.io.OutputStream;
      10. import java.util.Arrays;
      11. import java.util.Random;
      12. /**
      13. * 生成验证码工具类
      14. */
      15. public class CheckCodeUtil {
      16.     private static final String VERIFY_CODES = "123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
      17.     private static Random random = new Random();
      18.     public static void main(String[] args) throws IOException {
      19.         FileOutputStream fos = new FileOutputStream("d:\\a.jpg");
      20.         String str = CheckCodeUtil.outputVerifyImage(100, 40, fos, 4);
      21.         System.out.println("str = " + str);
      22.     }
      23.     /**
      24.      * 输出随机验证码图片流,并返回验证码值(一般传入输出流,响应response页面端,Web项目用的较多)
      25.      *
      26.      * @param width      图片宽度
      27.      * @param height     图片高度
      28.      * @param os         输出流
      29.      * @param verifySize 数据长度
      30.      * @return 验证码数据
      31.      * @throws IOException
      32.      */
      33.     public static String outputVerifyImage(int width, int height, OutputStream os, int verifySize) throws IOException {
      34.         String verifyCode = generateVerifyCode(verifySize);
      35.         outputImage(width, height, os, verifyCode);
      36.         return verifyCode;
      37.     }
      38.     /**
      39.      * 使用系统默认字符源生成验证码
      40.      *
      41.      * @param verifySize 验证码长度
      42.      * @return
      43.      */
      44.     public static String generateVerifyCode(int verifySize) {
      45.         return generateVerifyCode(verifySize, VERIFY_CODES);
      46.     }
      47.     /**
      48.      * 使用指定源生成验证码
      49.      *
      50.      * @param verifySize 验证码长度
      51.      * @param sources    验证码字符源
      52.      * @return
      53.      */
      54.     public static String generateVerifyCode(int verifySize, String sources) {
      55.         // 未设定展示源的字码,赋默认值大写字母+数字
      56.         if (sources == null || sources.length() == 0) {
      57.             sources = VERIFY_CODES;
      58.         }
      59.         int codesLen = sources.length();
      60.         Random rand = new Random(System.currentTimeMillis());
      61.         StringBuilder verifyCode = new StringBuilder(verifySize);
      62.         for (int i = 0; i < verifySize; i++) {
      63.             verifyCode.append(sources.charAt(rand.nextInt(codesLen - 1)));
      64.         }
      65.         return verifyCode.toString();
      66.     }
      67.     /**
      68.      * 生成随机验证码文件,并返回验证码值 (生成图片形式,用的较少)
      69.      *
      70.      * @param w
      71.      * @param h
      72.      * @param outputFile
      73.      * @param verifySize
      74.      * @return
      75.      * @throws IOException
      76.      */
      77.     public static String outputVerifyImage(int w, int h, File outputFile, int verifySize) throws IOException {
      78.         String verifyCode = generateVerifyCode(verifySize);
      79.         outputImage(w, h, outputFile, verifyCode);
      80.         return verifyCode;
      81.     }
      82.     /**
      83.      * 生成指定验证码图像文件
      84.      *
      85.      * @param w
      86.      * @param h
      87.      * @param outputFile
      88.      * @param code
      89.      * @throws IOException
      90.      */
      91.     public static void outputImage(int w, int h, File outputFile, String code) throws IOException {
      92.         if (outputFile == null) {
      93.             return;
      94.         }
      95.         File dir = outputFile.getParentFile();
      96.         //文件不存在
      97.         if (!dir.exists()) {
      98.             //创建
      99.             dir.mkdirs();
      100.         }
      101.         try {
      102.             outputFile.createNewFile();
      103.             FileOutputStream fos = new FileOutputStream(outputFile);
      104.             outputImage(w, h, fos, code);
      105.             fos.close();
      106.         } catch (IOException e) {
      107.             throw e;
      108.         }
      109.     }
      110.     /**
      111.      * 输出指定验证码图片流
      112.      *
      113.      * @param w
      114.      * @param h
      115.      * @param os
      116.      * @param code
      117.      * @throws IOException
      118.      */
      119.     public static void outputImage(int w, int h, OutputStream os, String code) throws IOException {
      120.         int verifySize = code.length();
      121.         BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
      122.         Random rand = new Random();
      123.         Graphics2D g2 = image.createGraphics();
      124.         g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
      125.         // 创建颜色集合,使用java.awt包下的类
      126.         Color[] colors = new Color[5];
      127.         Color[] colorSpaces = new Color[]{Color.WHITE, Color.CYAN,
      128.                 Color.GRAY, Color.LIGHT_GRAY, Color.MAGENTA, Color.ORANGE,
      129.                 Color.PINK, Color.YELLOW};
      130.         float[] fractions = new float[colors.length];
      131.         for (int i = 0; i < colors.length; i++) {
      132.             colors[i] = colorSpaces[rand.nextInt(colorSpaces.length)];
      133.             fractions[i] = rand.nextFloat();
      134.         }
      135.         Arrays.sort(fractions);
      136.         // 设置边框色
      137.         g2.setColor(Color.GRAY);
      138.         g2.fillRect(0, 0, w, h);
      139.         Color c = getRandColor(200, 250);
      140.         // 设置背景色
      141.         g2.setColor(c);
      142.         g2.fillRect(0, 2, w, h - 4);
      143.         // 绘制干扰线
      144.         Random random = new Random();
      145.         // 设置线条的颜色
      146.         g2.setColor(getRandColor(160, 200));
      147.         for (int i = 0; i < 20; i++) {
      148.             int x = random.nextInt(w - 1);
      149.             int y = random.nextInt(h - 1);
      150.             int xl = random.nextInt(6) + 1;
      151.             int yl = random.nextInt(12) + 1;
      152.             g2.drawLine(x, y, x + xl + 40, y + yl + 20);
      153.         }
      154.         // 添加噪点
      155.         // 噪声率
      156.         float yawpRate = 0.05f;
      157.         int area = (int) (yawpRate * w * h);
      158.         for (int i = 0; i < area; i++) {
      159.             int x = random.nextInt(w);
      160.             int y = random.nextInt(h);
      161.             // 获取随机颜色
      162.             int rgb = getRandomIntColor();
      163.             image.setRGB(x, y, rgb);
      164.         }
      165.         // 添加图片扭曲
      166.         shear(g2, w, h, c);
      167.         g2.setColor(getRandColor(100, 160));
      168.         int fontSize = h - 4;
      169.         Font font = new Font("Algerian", Font.ITALIC, fontSize);
      170.         g2.setFont(font);
      171.         char[] chars = code.toCharArray();
      172.         for (int i = 0; i < verifySize; i++) {
      173.             AffineTransform affine = new AffineTransform();
      174.             affine.setToRotation(Math.PI / 4 * rand.nextDouble() * (rand.nextBoolean() ? 1 : -1), (w / verifySize) * i + fontSize / 2, h / 2);
      175.             g2.setTransform(affine);
      176.             g2.drawChars(chars, i, 1, ((w - 10) / verifySize) * i + 5, h / 2 + fontSize / 2 - 10);
      177.         }
      178.         g2.dispose();
      179.         ImageIO.write(image, "jpg", os);
      180.     }
      181.     /**
      182.      * 随机颜色
      183.      *
      184.      * @param fc
      185.      * @param bc
      186.      * @return
      187.      */
      188.     private static Color getRandColor(int fc, int bc) {
      189.         if (fc > 255) {
      190.             fc = 255;
      191.         }
      192.         if (bc > 255) {
      193.             bc = 255;
      194.         }
      195.         int r = fc + random.nextInt(bc - fc);
      196.         int g = fc + random.nextInt(bc - fc);
      197.         int b = fc + random.nextInt(bc - fc);
      198.         return new Color(r, g, b);
      199.     }
      200.     private static int getRandomIntColor() {
      201.         int[] rgb = getRandomRgb();
      202.         int color = 0;
      203.         for (int c : rgb) {
      204.             color = color << 8;
      205.             color = color | c;
      206.         }
      207.         return color;
      208.     }
      209.     private static int[] getRandomRgb() {
      210.         int[] rgb = new int[3];
      211.         for (int i = 0; i < 3; i++) {
      212.             rgb[i] = random.nextInt(255);
      213.         }
      214.         return rgb;
      215.     }
      216.     private static void shear(Graphics g, int w1, int h1, Color color) {
      217.         shearX(g, w1, h1, color);
      218.         shearY(g, w1, h1, color);
      219.     }
      220.     private static void shearX(Graphics g, int w1, int h1, Color color) {
      221.         int period = random.nextInt(2);
      222.         boolean borderGap = true;
      223.         int frames = 1;
      224.         int phase = random.nextInt(2);
      225.         for (int i = 0; i < h1; i++) {
      226.             double d = (double) (period >> 1)
      227.                     * Math.sin((double) i / (double) period
      228.                     + (6.2831853071795862D * (double) phase)
      229.                     / (double) frames);
      230.             g.copyArea(0, i, w1, 1, (int) d, 0);
      231.             if (borderGap) {
      232.                 g.setColor(color);
      233.                 g.drawLine((int) d, i, 0, i);
      234.                 g.drawLine((int) d + w1, i, w1, i);
      235.             }
      236.         }
      237.     }
      238.     private static void shearY(Graphics g, int w1, int h1, Color color) {
      239.         int period = random.nextInt(40) + 10; // 50;
      240.         boolean borderGap = true;
      241.         int frames = 20;
      242.         int phase = 7;
      243.         for (int i = 0; i < w1; i++) {
      244.             double d = (double) (period >> 1)
      245.                     * Math.sin((double) i / (double) period
      246.                     + (6.2831853071795862D * (double) phase)
      247.                     / (double) frames);
      248.             g.copyArea(i, 0, 1, h1, 0, (int) d);
      249.             if (borderGap) {
      250.                 g.setColor(color);
      251.                 g.drawLine(i, (int) d, i, 0);
      252.                 g.drawLine(i, (int) d + h1, i, h1);
      253.             }
      254.         }
      255.     }
      256. }
      复制代码

1.4、MyBatis相关配置准备


  • logback.xml

    • 日志配置文件
      1. <?xml version="1.0" encoding="UTF-8"?>
      2. <configuration>
      3.    
      4.     <appender name="Console" >
      5.         <encoder>
      6.             <pattern>[%level] %blue(%d{HH:mm:ss.SSS}) %cyan([%thread]) %boldGreen(%logger{15}) - %msg %n</pattern>
      7.         </encoder>
      8.     </appender>
      9.     <logger name="com.coolman" level="DEBUG" additivity="false">
      10.         <appender-ref ref="Console"/>
      11.     </logger>
      12.    
      13.     <root level="DEBUG">
      14.         <appender-ref ref="Console"/>
      15.     </root>
      16. </configuration>
      复制代码

  • mybatis-config.xml

    • MyBatis的配置文件
      1. <?xml version="1.0" encoding="UTF-8" ?>
      2. <!DOCTYPE configuration
      3.         PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
      4.         "http://mybatis.org/dtd/mybatis-3-config.dtd">
      5. <configuration>
      6.     <settings>
      7.         <setting name="mapUnderscoreToCamelCase" value="true"/>
      8.     </settings>
      9.    
      10.    
      11.     <typeAliases>
      12.         <package name="com.coolman.pojo"/>
      13.     </typeAliases>
      14.     <environments default="development">
      15.         <environment id="development">
      16.             <transactionManager type="JDBC"/>
      17.             <dataSource type="POOLED">
      18.                 <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
      19.                 <property name="url" value="jdbc:mysql://localhost:3306/sms?serverTimezone=Asia/Shanghai"/>
      20.                 <property name="username" value="root"/>
      21.                 <property name="password" value="123"/>
      22.             </dataSource>
      23.         </environment>
      24.     </environments>
      25.     <mappers>
      26.         
      27.         <package name="com.coolman.mapper"/>
      28.     </mappers>
      29. </configuration>
      复制代码

1.5、前端代码准备


  • css文件夹相关文件

    • login.css

        1. * {
        2.     margin: 0;
        3.     padding: 0;
        4. }
        5. html {
        6.     height: 100%;
        7.     width: 100%;
        8.     overflow: hidden;
        9.     margin: 0;
        10.     padding: 0;
        11.     background: url(../imgs/Desert1.jpg) no-repeat 0px 0px;
        12.     background-repeat: no-repeat;
        13.     background-size: 100% 100%;
        14.     -moz-background-size: 100% 100%;
        15. }
        16. body {
        17.     display: flex;
        18.     align-items: center;
        19.     justify-content: center;
        20.     height: 100%;
        21. }
        22. #loginDiv {
        23.     width: 37%;
        24.     display: flex;
        25.     justify-content: center;
        26.     align-items: center;
        27.     height: 380px;
        28.     background-color: rgba(75, 81, 95, 0.3);
        29.     box-shadow: 7px 7px 17px rgba(52, 56, 66, 0.5);
        30.     border-radius: 5px;
        31. }
        32. #name_trip {
        33.     margin-left: 50px;
        34.     color: red;
        35. }
        36. p {
        37.     margin-top: 30px;
        38.     margin-left: 20px;
        39.     color: azure;
        40. }
        41. #remember{
        42.     margin-left: 15px;
        43.     border-radius: 5px;
        44.     border-style: hidden;
        45.     background-color: rgba(216, 191, 216, 0.5);
        46.     outline: none;
        47.     padding-left: 10px;
        48.     height: 20px;
        49.     width: 20px;
        50. }
        51. #phone_number{
        52.     width: 200px;
        53.     margin-left: 15px;
        54.     border-radius: 5px;
        55.     border-style: hidden;
        56.     height: 30px;
        57.     background-color: rgba(216, 191, 216, 0.5);
        58.     outline: none;
        59.     color: #f0edf3;
        60.     padding-left: 10px;
        61. }
        62. #password{
        63.     width: 202px;
        64.     margin-left: 30px;
        65.     border-radius: 5px;
        66.     border-style: hidden;
        67.     height: 30px;
        68.     background-color: rgba(216, 191, 216, 0.5);
        69.     outline: none;
        70.     color: #f0edf3;
        71.     padding-left: 10px;
        72. }
        73. .button {
        74.     border-color: cornsilk;
        75.     background-color: rgba(100, 149, 237, .7);
        76.     color: aliceblue;
        77.     border-style: hidden;
        78.     border-radius: 5px;
        79.     width: 100px;
        80.     height: 31px;
        81.     font-size: 16px;
        82. }
        83. #subDiv {
        84.     text-align: center;
        85.     margin-top: 30px;
        86. }
        87. #loginMsg{
        88.     text-align: center;
        89.     color: aliceblue;
        90. }
        91. #errorMsg{
        92.     text-align: center;
        93.     color:red;
        94. }
        复制代码

    • register.css

        1. * {
        2.     margin: 0;
        3.     padding: 0;
        4.     list-style-type: none;
        5. }
        6. .reg-content{
        7.     padding: 30px;
        8.     margin: 3px;
        9. }
        10. a, img {
        11.     border: 0;
        12. }
        13. body {
        14.     background-image: url("../imgs/reg_bg_min.jpg") ;
        15.     text-align: center;
        16. }
        17. table {
        18.     border-collapse: collapse;
        19.     border-spacing: 0;
        20. }
        21. td, th {
        22.     padding: 0;
        23.     height: 90px;
        24. }
        25. .inputs{
        26.     vertical-align: top;
        27. }
        28. .clear {
        29.     clear: both;
        30. }
        31. .clear:before, .clear:after {
        32.     content: "";
        33.     display: table;
        34. }
        35. .clear:after {
        36.     clear: both;
        37. }
        38. .form-div {
        39.     background-color: rgba(255, 255, 255, 0.27);
        40.     border-radius: 10px;
        41.     border: 1px solid #aaa;
        42.     width: 424px;
        43.     margin-top: 150px;
        44.     margin-left:1050px;
        45.     padding: 30px 0 20px 0px;
        46.     font-size: 16px;
        47.     box-shadow: inset 0px 0px 10px rgba(255, 255, 255, 0.5), 0px 0px 15px rgba(75, 75, 75, 0.3);
        48.     text-align: left;
        49. }
        50. .form-div input[type="text"], .form-div input[type="password"], .form-div input[type="email"] {
        51.     width: 268px;
        52.     margin: 10px;
        53.     line-height: 20px;
        54.     font-size: 16px;
        55. }
        56. .form-div input[type="checkbox"] {
        57.     margin: 20px 0 20px 10px;
        58. }
        59. .form-div input[type="button"], .form-div input[type="submit"] {
        60.     margin: 10px 20px 0 0;
        61. }
        62. .form-div table {
        63.     margin: 0 auto;
        64.     text-align: right;
        65.     color: rgba(64, 64, 64, 1.00);
        66. }
        67. .form-div table img {
        68.     vertical-align: middle;
        69.     margin: 0 0 5px 0;
        70. }
        71. .footer {
        72.     color: rgba(64, 64, 64, 1.00);
        73.     font-size: 12px;
        74.     margin-top: 30px;
        75. }
        76. .form-div .buttons {
        77.     float: right;
        78. }
        79. input[type="text"], input[type="password"], input[type="email"] {
        80.     border-radius: 8px;
        81.     box-shadow: inset 0 2px 5px #eee;
        82.     padding: 10px;
        83.     border: 1px solid #D4D4D4;
        84.     color: #333333;
        85.     margin-top: 5px;
        86. }
        87. input[type="text"]:focus, input[type="password"]:focus, input[type="email"]:focus {
        88.     border: 1px solid #50afeb;
        89.     outline: none;
        90. }
        91. input[type="button"], input[type="submit"] {
        92.     padding: 7px 15px;
        93.     background-color: #3c6db0;
        94.     text-align: center;
        95.     border-radius: 5px;
        96.     overflow: hidden;
        97.     min-width: 80px;
        98.     border: none;
        99.     color: #FFF;
        100.     box-shadow: 1px 1px 1px rgba(75, 75, 75, 0.3);
        101. }
        102. input[type="button"]:hover, input[type="submit"]:hover {
        103.     background-color: #5a88c8;
        104. }
        105. input[type="button"]:active, input[type="submit"]:active {
        106.     background-color: #5a88c8;
        107. }
        108. .phone_number_err_msg{
        109.     color: red;
        110.     padding-right: 170px;
        111. }
        112. #password_err,#tel_err{
        113.     padding-right: 195px;
        114. }
        115. #reg_btn{
        116.     margin-right:50px; width: 285px; height: 45px; margin-top:20px;
        117. }
        118. #checkCode{
        119.     width: 100px;
        120. }
        121. #changeImg{
        122.     color: aqua;
        123. }
        复制代码


  • img文件夹相关图片

    • Desert1.jpg



    • reg_bg_min.jpg




  • JSP相关文件

    • addStudnet.jsp

        1. <%@ page contentType="text/html;charset=UTF-8" language="java" %>
        2. <html>
        3. <head>
        4.     <title>添加学生信息</title>
        5. </head>
        6. <body>
        7. <h3 align="center" >添加学生信息</h3>
        8. <form action="addStudentServlet" method="post">
        9.    
        10.         学号:       
        11.             <input name="stuNumber"><br>
        12.         
        13.         姓名:       
        14.             <input name="name"><br>
        15.         
        16.         年龄:       
        17.             <input name="age"><br>
        18.         
        19.         性别:       
        20.             <input name="sex"><br>
        21.         
        22.         语文成绩:
        23.             <input name="chineseScore"><br>
        24.         
        25.         数学成绩:
        26.             <input name="mathScore"><br>
        27.         
        28.         英语成绩:
        29.             <input name="englishScore"><br>
        30.         
        31.         <input type="submit" value="提交">
        32.    
        33. </form>
        34. </body>
        35. </html>
        复制代码

    • login.jsp

        1. <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
        2. <%@ page contentType="text/html;charset=UTF-8" language="java" %>
        3. <!DOCTYPE html>
        4. <html lang="en">
        5. <head>
        6.     <meta charset="UTF-8">
        7.     <title>login</title>
        8.     <link href="css/login.css" rel="stylesheet">
        9. </head>
        10. <body>
        11.     <form action="loginServlet" method="post" id="form">
        12.         <h1 id="loginMsg">登 录</h1>
        13.         ${loginMessage} ${registerMessage}
        14.         <p>用户名:<input id="phone_number" name="phone_number" type="text" value="${cookie.cookie_phone_number.value}"></p>
        15.         <p>密码:<input id="password" name="password" type="password" value="${cookie.cookie_password.value}"></p>
        16.         
        17.             <c:if test="${cookie.cookie_phone_number.value != null}">
        18.                 <p>记住我: <input name="remember" type="checkbox" value="1" checked="checked"></p>
        19.             </c:if>
        20.             <c:if test="${cookie.cookie_phone_number.value == null}">
        21.                 <p>记住我: <input name="remember" type="checkbox" value="1"></p>
        22.             </c:if>
        23.         
        24.         
        25.             <input type="submit"  value="登 录">
        26.             <input type="reset"  value="reset">   
        27.             <a target="_blank" href="https://www.cnblogs.com/register.jsp">没有账号?</a>
        28.         
        29.     </form>
        30. </body>
        31. <%----%>
        32. </html>
        复制代码

    • register.jsp

        1. <%@ page contentType="text/html;charset=UTF-8" language="java" %>
        2. <!DOCTYPE html>
        3. <html lang="en">
        4. <head>
        5.     <meta charset="UTF-8">
        6.     <title>欢迎注册</title>
        7.     <link href="css/register.css" rel="stylesheet">
        8. </head>
        9. <body>
        10.    
        11.         <h1>欢迎注册</h1>
        12.         已有帐号? <a target="_blank" href="https://www.cnblogs.com/login.jsp">登录</a>
        13.    
        14.     <form id="reg-form" action="registerServlet" method="post">
        15.         <table>
        16.             <tr>
        17.                 <td>姓名</td>
        18.                 <td >
        19.                     <input name="username" type="text" id="username">
        20.                     <br>
        21.                 </td>
        22.             </tr>
        23.             <tr>
        24.                 <td>手机号码</td>
        25.                 <td >
        26.                     <input name="phone_number" type="text" id="phone_number">
        27.                     <br>
        28.                     ${phone_number_err_msg}
        29.                 </td>
        30.             </tr>
        31.             <tr>
        32.                 <td>密码</td>
        33.                 <td >
        34.                     <input name="password" type="password" id="password">
        35.                     <br>
        36.                 </td>
        37.             </tr>
        38.             <tr>
        39.                 <td>验证码:</td>
        40.                 <td >
        41.                     <input name="checkCode" type="text" id="checkCode">
        42.                     <img id="checkCodeImg" src="https://www.cnblogs.com/checkCodeServlet">
        43.                     <a target="_blank" href="https://www.cnblogs.com/#" id="changeImg">看不清?</a>
        44.                     <p    align="left" id="checkCode_err" >
        45.                         ${checkCode_err_msg}
        46.                     </p>
        47.                 </td>
        48.             </tr>
        49. <%--            <tr>--%>
        50. <%--                <td></td>--%>
        51. <%--                <td  align="center" id="checkCode_err" >${checkCode_err_msg}</td>--%>
        52. <%--            </tr>--%>
        53.         </table>
        54.         
        55.             <input value="注 册" type="submit" id="reg_btn">
        56.         
        57.         <br >
        58.     </form>
        59. </body>
        60. </html>
        复制代码

    • studentList.jsp

        1. <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
        2. <%@ page contentType="text/html;charset=UTF-8" language="java" %>
        3. <!DOCTYPE html>
        4. <html lang="en">
        5. <head>
        6.     <meta charset="UTF-8">
        7.     <title>Title</title>
        8. </head>
        9. <body>
        10. <h1  align="center">欢迎您: ${username} 登录成功, 来到学生信息管理系统</h1>
        11. <br>
        12. <hr>
        13. <table border="1" cellspacing="0" width="800" align="center">
        14.     <tr>
        15.         <th>序号</th>
        16.         <th>学号</th>
        17.         <th>姓名</th>
        18.         <th>年龄</th>
        19.         <th>性别</th>
        20.         <th>语文成绩</th>
        21.         <th>数学成绩</th>
        22.         <th>英语成绩</th>
        23.         <th>操作</th>
        24.     </tr>
        25.     <c:forEach items="${students}" var="student" varStatus="varSta">
        26.         <tr align="center">
        27.             <td>${varSta.count}</td>
        28.             <td>${student.stuNumber}</td>
        29.             <td>${student.name}</td>
        30.             <td>${student.age}</td>
        31.             <td>${student.sex}</td>
        32.             <td>${student.chineseScore}</td>
        33.             <td>${student.mathScore}</td>
        34.             <td>${student.englishScore}</td>
        35.             <td><a target="_blank" href="https://www.cnblogs.com/updateBrand.jsp?id=${student.id}">修改</a> <a target="_blank" href="https://www.cnblogs.com/DeleteStudentByIdServlet?id=${student.id}">删除</a></td>
        36.         </tr>
        37.     </c:forEach>
        38.     <tr align="center">
        39.         <td></td>
        40.         <td></td>
        41.         <td></td>
        42.         <td></td>
        43.         <td></td>
        44.         <td></td>
        45.         <td></td>
        46.         <td></td>
        47.         <td><input type="button" value="新增学生信息" onclick="location.href=('addStudent.jsp')"></td>
        48.     </tr>
        49. </table>
        50. </body>
        51. </html>
        复制代码

    • updateBrand.jsp

        1. <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
        2. <%@ page contentType="text/html;charset=UTF-8" language="java" %>
        3. <html>
        4. <head>
        5.     <title>修改品牌</title>
        6. </head>
        7. <body>
        8. <%
        9.     String id = request.getParameter("id");
        10. %>
        11. <h3>修改品牌</h3>
        12. <form action="updateStudentByIdServlet" method="post">
        13.    
        14.         <input type="hidden" name="id" value="<%=id%>">
        15.         学号:       
        16.             <input name="stuNumber"><br>
        17.         
        18.         姓名:       
        19.             <input name="name"><br>
        20.         
        21.         年龄:       
        22.             <input name="age"><br>
        23.         
        24.         性别:       
        25.             <input name="sex"><br>
        26.         
        27.         语文成绩:
        28.             <input name="chineseScore"><br>
        29.         
        30.         数学成绩:
        31.             <input name="mathScore"><br>
        32.         
        33.         英语成绩:
        34.             <input name="englishScore"><br>
        35.         
        36.         <input type="submit" value="提交">
        37.    
        38. </form>
        39. </body>
        40. </html>
        复制代码


2、编码实现

2.1、登录注册

2.1.1、登录

Servlet实现


    1. package com.coolman.web;
    2. import com.coolman.pojo.User;
    3. import com.coolman.service.UserService;
    4. import javax.servlet.ServletException;
    5. import javax.servlet.annotation.WebServlet;
    6. import javax.servlet.http.*;
    7. import java.io.IOException;
    8. @WebServlet("/loginServlet")
    9. public class LoginServlet extends HttpServlet {
    10.     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    11.         doGet(request, response);
    12.     }
    13.     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    14.         // 在这里处理请求
    15.         // 获取登录页面POST请求传递回来的参数
    16.         String phoneNumber = request.getParameter("phone_number");
    17.         String password = request.getParameter("password");
    18.         String remember = request.getParameter("remember");
    19.         // 调用服务查询该用户是否存在
    20.         User user = new UserService().selectUserByPhoneNumberAndPassword(phoneNumber, password);
    21.         // 如果用户存在
    22.         if (user != null) {
    23.             // “记住我”功能
    24.             // 如果用户勾选了记住我,那么就将该数据存储至cookie中,交由客户端保存
    25.             Cookie phoneNumberCookie = new Cookie("cookie_phone_number", phoneNumber);
    26.             Cookie passwordCookie = new Cookie("cookie_password", password);
    27.             if ("1".equals(remember)) {
    28.                 // 如果勾选
    29.                 response.addCookie(phoneNumberCookie);
    30.                 response.addCookie(passwordCookie);
    31.                 System.out.println("用户勾选了“记住我”功能,并将数据保存到了cookie当中");
    32.             } else {
    33.                 phoneNumberCookie.setMaxAge(0);
    34.                 passwordCookie.setMaxAge(0);
    35.                 response.addCookie(phoneNumberCookie);
    36.                 response.addCookie(passwordCookie);
    37.             }
    38.             // 将用户信息存储在Session中,并跳转到信息展示列表页
    39.             HttpSession session = request.getSession();
    40.             session.setAttribute("username", user.getName());
    41.             // 跳转到信息展示列表页
    42.             response.sendRedirect("selectAllStudentsServlet");
    43.         } else {
    44.             // 如果用户不存在
    45.             // 提示错误信息
    46.             request.setAttribute("loginMessage", "用户名或者密码错误!");
    47.             // 请求转发重新回到登录界面
    48.             request.getRequestDispatcher("login.jsp").forward(request, response);
    49.         }
    50.     }
    51. }
    复制代码
Service实现


    1. // 根据账号和密码查询用户
    2.     public User selectUserByPhoneNumberAndPassword(String phoneNumber, String password) {
    3.         SqlSession sqlSession = MyBatisUtils.openSession();
    4.         UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    5.         User user = mapper.selectUserByPhoneNumberAndPassword(phoneNumber, password);
    6.         sqlSession.close();
    7.         return user;
    8.     }
    复制代码
mapper实现


    1.     // 根据账号和密码查询用户
    2.     @Select("select * from sms.user where phone_number = #{phoneNumber} and password = #{password};")
    3.     User selectUserByPhoneNumberAndPassword(@Param("phoneNumber") String phoneNumber, @Param("password") String password);
    复制代码
2.1.2、注册

Servlet实现


  • RegisterServlet

      1. package com.coolman.web;
      2. import com.coolman.pojo.User;
      3. import com.coolman.service.UserService;
      4. import javax.servlet.ServletException;
      5. import javax.servlet.annotation.WebServlet;
      6. import javax.servlet.http.HttpServlet;
      7. import javax.servlet.http.HttpServletRequest;
      8. import javax.servlet.http.HttpServletResponse;
      9. import javax.servlet.http.HttpSession;
      10. import java.io.IOException;
      11. @WebServlet("/registerServlet")
      12. public class RegisterServlet extends HttpServlet {
      13.     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      14.         doGet(request, response);
      15.     }
      16.     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      17.         // 在这里处理请求
      18.         // 获取表单参数
      19.         String username = request.getParameter("username");
      20.         String phoneNumber = request.getParameter("phone_number");
      21.         String password = request.getParameter("password");
      22.         String checkCode = request.getParameter("checkCode");
      23.         // 获取正确的验证码
      24.         HttpSession session = request.getSession();
      25.         String correctCode = (String) session.getAttribute("correctCode");
      26.         // 判断phoneNumber是否唯一
      27.         // 查询数据库,调用服务
      28.         UserService service = new UserService();
      29.         User user = service.selectUserByPhoneNumber(phoneNumber);
      30.         if (user == null) {
      31.             // user 为空,说明不存在该用户,所以可以创建账号
      32.             // 调用服务,添加用户
      33.             // 判断验证码是否输入正确(忽略大小写)
      34.             if (correctCode.equalsIgnoreCase(checkCode)) {
      35.                 // 如果验证码输入正确
      36.                 // 调用服务,添加用户
      37.                 service.addUser(new User(0, username, phoneNumber, password));
      38.                 request.setAttribute("registerMessage", "注册成功,请登录");
      39.                 request.getRequestDispatcher("login.jsp").forward(request, response);
      40.             } else {
      41.                 // 如果输入错误
      42.                 // 给出错误信息,验证码输入错误!
      43.                 request.setAttribute("checkCode_err_msg", "验证码输入错误!");
      44.                 request.getRequestDispatcher("register.jsp").forward(request, response);
      45.             }
      46.         } else {
      47.             // 给出错误信息:手机号码重复!
      48.             request.setAttribute("phone_number_err_msg", "手机号码重复,请重新输入!");
      49.             // 请求转发回去给register.jsp
      50.             request.getRequestDispatcher("register.jsp").forward(request, response);
      51.         }
      52.     }
      53. }
      复制代码

  • CheckCodeServlet

      1. package com.coolman.web;
      2. import com.coolman.utils.CheckCodeUtil;
      3. import javax.servlet.ServletException;
      4. import javax.servlet.ServletOutputStream;
      5. import javax.servlet.annotation.WebServlet;
      6. import javax.servlet.http.HttpServlet;
      7. import javax.servlet.http.HttpServletRequest;
      8. import javax.servlet.http.HttpServletResponse;
      9. import javax.servlet.http.HttpSession;
      10. import java.io.IOException;
      11. @WebServlet("/https://www.cnblogs.com/checkCodeServlet")
      12. public class CheckCodeServlet extends HttpServlet {
      13.     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      14.         doGet(request, response);
      15.     }
      16.     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      17.         // 在这里处理请求
      18.         // 获取验证码
      19.         // 创建一个输出流
      20.         ServletOutputStream out = response.getOutputStream();
      21.         String correctCode = CheckCodeUtil.outputVerifyImage(100, 40, out, 4);
      22.         // 将正确的验证码存储到Session中
      23.         HttpSession session = request.getSession();
      24.         session.setAttribute("correctCode", correctCode);
      25.     }
      26. }
      复制代码

Service实现


    1.     // 根据账号查询用户
    2.     public User selectUserByPhoneNumber(String phoneNumber) {
    3.         SqlSession sqlSession = MyBatisUtils.openSession();
    4.         UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    5.         User user = mapper.selectUserByPhoneNumber(phoneNumber);
    6.         sqlSession.close();
    7.         return user;
    8.     }
    9.     // 添加用户
    10.     public void addUser(User user) {
    11.         SqlSession sqlSession = MyBatisUtils.openSession();
    12.         UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    13.         mapper.addUser(user);
    14.         sqlSession.commit();
    15.         sqlSession.close();
    16.     }
    复制代码
mapper实现


    1.     // 根据账号查询用户
    2.     @Select("select * from sms.user where phone_number = #{phoneNumber}")
    3.     User selectUserByPhoneNumber(String phoneNumber);
    4.     // 添加用户
    5.     @Insert("insert into sms.user values (null, #{name}, #{phoneNumber}, #{password});")
    6.     void addUser(User user);
    复制代码
2.2、查询学生信息列表

Servlet实现


    1. package com.coolman.web;
    2. import com.coolman.pojo.Student;
    3. import com.coolman.service.StudentService;
    4. import javax.servlet.ServletException;
    5. import javax.servlet.annotation.WebServlet;
    6. import javax.servlet.http.HttpServlet;
    7. import javax.servlet.http.HttpServletRequest;
    8. import javax.servlet.http.HttpServletResponse;
    9. import java.io.IOException;
    10. import java.util.List;
    11. @WebServlet("/selectAllStudentsServlet")
    12. public class SelectAllStudentsServlet extends HttpServlet {
    13.     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    14.         doGet(request, response);
    15.     }
    16.     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    17.         // 在这里处理请求
    18.         List<Student> students = new StudentService().selectAllStudent();
    19.         request.setAttribute("students", students);
    20.         request.getRequestDispatcher("studentList.jsp").forward(request, response);
    21.     }
    22. }
    复制代码
Service实现


    1.     // 查询所有学生信息
    2.     public List<Student> selectAllStudent() {
    3.         SqlSession sqlSession = MyBatisUtils.openSession();
    4.         StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
    5.         List<Student> students = mapper.selectAllStudents();
    6.         sqlSession.close();
    7.         return students;
    8.     }
    复制代码
mapper实现


    1.     // 查询所有学生信息
    2.     @Select("select * from sms.student;")
    3.     List<Student> selectAllStudents();
    复制代码
2.3、学生信息更新

这里我没有做数据回显,有兴趣的可以做一下
2.3.1、添加

Servlet实现


    1. package com.coolman.web;
    2. import com.coolman.pojo.Student;
    3. import com.coolman.service.StudentService;
    4. import org.apache.commons.beanutils.BeanUtils;
    5. import javax.servlet.ServletException;
    6. import javax.servlet.annotation.WebServlet;
    7. import javax.servlet.http.HttpServlet;
    8. import javax.servlet.http.HttpServletRequest;
    9. import javax.servlet.http.HttpServletResponse;
    10. import java.io.IOException;
    11. import java.lang.reflect.InvocationTargetException;
    12. import java.util.Map;
    13. @WebServlet("/addStudentServlet")
    14. public class AddStudentServlet extends HttpServlet {
    15.     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    16.         doGet(request, response);
    17.     }
    18.     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    19.         // 在这里处理请求
    20.         Map<String, String[]> map = request.getParameterMap();
    21.         Student student = new Student();
    22.         try {
    23.             BeanUtils.populate(student, map);
    24.         } catch (IllegalAccessException | InvocationTargetException e) {
    25.             e.printStackTrace();
    26.         }
    27. //        System.out.println(student);
    28.         // 调用服务
    29.         StudentService service = new StudentService();
    30.         service.addStudent(student);
    31.         response.sendRedirect("selectAllStudentsServlet");
    32.     }
    33. }
    复制代码
Service实现


    1.     // 新增学生信息
    2.     public void addStudent(Student student) {
    3.         SqlSession sqlSession = MyBatisUtils.openSession();
    4.         StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
    5.         mapper.addStudent(student);
    6.         sqlSession.commit();
    7.         sqlSession.close();
    8.     }
    复制代码
mapper实现


    1.     // 新增学生信息
    2.     @Insert("insert into sms.student values (null, #{stuNumber}, #{name}, #{age}, #{sex}, #{chineseScore}, " +
    3.             "#{mathScore}, #{englishScore});")
    4.     void addStudent(Student student);
    复制代码
2.3.2、删除

Servlet实现


    1. package com.coolman.web;
    2. import com.coolman.service.StudentService;
    3. import javax.servlet.ServletException;
    4. import javax.servlet.annotation.WebServlet;
    5. import javax.servlet.http.HttpServlet;
    6. import javax.servlet.http.HttpServletRequest;
    7. import javax.servlet.http.HttpServletResponse;
    8. import java.io.IOException;
    9. @WebServlet("/DeleteStudentByIdServlet")
    10. public class DeleteStudentByIdServlet extends HttpServlet {
    11.     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    12.         doGet(request, response);
    13.     }
    14.     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    15.         // 在这里处理请求
    16.         // 获取id
    17.         int sid = Integer.parseInt(request.getParameter("id"));
    18.         // 调用服务
    19.         StudentService service = new StudentService();
    20.         service.deleteStudentById(sid);
    21.         response.sendRedirect("selectAllStudentsServlet");
    22.     }
    23. }
    复制代码
Service实现


    1.     // 删除学生信息
    2.     public void deleteStudentById(int sid) {
    3.         SqlSession sqlSession = MyBatisUtils.openSession();
    4.         StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
    5.         mapper.deleteStudentById(sid);
    6.         sqlSession.commit();
    7.         sqlSession.close();
    8.     }
    复制代码
mapper实现


    1.     // 删除学生信息
    2.     @Delete("delete from sms.student where id = #{sid};")
    3.     void deleteStudentById(int sid);
    复制代码
2.3.3、修改

Servlet实现


    1. package com.coolman.web;
    2. import com.coolman.pojo.Student;
    3. import com.coolman.service.StudentService;
    4. import org.apache.commons.beanutils.BeanUtils;
    5. import javax.servlet.ServletException;
    6. import javax.servlet.annotation.WebServlet;
    7. import javax.servlet.http.HttpServlet;
    8. import javax.servlet.http.HttpServletRequest;
    9. import javax.servlet.http.HttpServletResponse;
    10. import java.io.IOException;
    11. import java.lang.reflect.InvocationTargetException;
    12. import java.util.Map;
    13. @WebServlet("/updateStudentByIdServlet")
    14. public class UpdateStudentByIdServlet extends HttpServlet {
    15.     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    16.         doGet(request, response);
    17.     }
    18.     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    19.         // 在这里处理请求
    20.         request.setCharacterEncoding("utf-8");
    21.         Map<String, String[]> map = request.getParameterMap();
    22.         Student student = new Student();
    23.         try {
    24.             BeanUtils.populate(student, map);
    25.         } catch (IllegalAccessException | InvocationTargetException e) {
    26.             e.printStackTrace();
    27.         }
    28. //        System.out.println(student);
    29.         StudentService service = new StudentService();
    30.         service.updateStudentById(student);
    31.         response.sendRedirect("selectAllStudentsServlet");
    32.     }
    33. }
    复制代码
Service实现


    1.     // 根据学生id修改学生数据
    2.     public void updateStudentById(Student student) {
    3.         SqlSession sqlSession = MyBatisUtils.openSession();
    4.         StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
    5.         mapper.updateStudentById(student);
    6.         sqlSession.commit();
    7.         sqlSession.close();
    8.     }
    复制代码
mapper实现


    1.     // 根据学生id修改学生数据
    2.     @Update("update sms.student set stu_number = #{stuNumber}, name = #{name}, age = #{age}, sex = #{sex}, " +
    3.             "chinese_score = #{chineseScore}, math_score = #{mathScore}, " +
    4.             "english_score = #{englishScore} where id = #{id};")
    5.     void updateStudentById(Student student);
    复制代码
  • 至此功能已经基本实现完成,直接添加到Tomcat项目中启动即可,不过这个案例有很多不足的地方,可自行修改;最终目录结构如下所示




免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

本帖子中包含更多资源

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

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

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

本版积分规则

铁佛

金牌会员
这个人很懒什么都没写!

标签云

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