基于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
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>
-
- <appender name="Console" >
- <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>
-
- <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>
-
- <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" >添加学生信息</h3>
- <form action="addStudentServlet" method="post">
-
- 学号:
- <input name="stuNumber"><br>
-
- 姓名:
- <input name="name"><br>
-
- 年龄:
- <input name="age"><br>
-
- 性别:
- <input name="sex"><br>
-
- 语文成绩:
- <input name="chineseScore"><br>
-
- 数学成绩:
- <input name="mathScore"><br>
-
- 英语成绩:
- <input name="englishScore"><br>
-
- <input type="submit" value="提交">
-
- </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>
- <form action="loginServlet" method="post" id="form">
- <h1 id="loginMsg">登 录</h1>
- ${loginMessage} ${registerMessage}
- <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>
-
- <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>
-
-
- <input type="submit" value="登 录">
- <input type="reset" value="reset">
- <a target="_blank" href="https://www.cnblogs.com/register.jsp">没有账号?</a>
-
- </form>
- </body>
- <%----%>
- </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>
-
- <h1>欢迎注册</h1>
- 已有帐号? <a target="_blank" href="https://www.cnblogs.com/login.jsp">登录</a>
-
- <form id="reg-form" action="registerServlet" method="post">
- <table>
- <tr>
- <td>姓名</td>
- <td >
- <input name="username" type="text" id="username">
- <br>
- </td>
- </tr>
- <tr>
- <td>手机号码</td>
- <td >
- <input name="phone_number" type="text" id="phone_number">
- <br>
- ${phone_number_err_msg}
- </td>
- </tr>
- <tr>
- <td>密码</td>
- <td >
- <input name="password" type="password" id="password">
- <br>
- </td>
- </tr>
- <tr>
- <td>验证码:</td>
- <td >
- <input name="checkCode" type="text" id="checkCode">
- <img id="checkCodeImg" src="https://www.cnblogs.com/checkCodeServlet">
- <a target="_blank" href="https://www.cnblogs.com/#" id="changeImg">看不清?</a>
- <p align="left" id="checkCode_err" >
- ${checkCode_err_msg}
- </p>
- </td>
- </tr>
- <%-- <tr>--%>
- <%-- <td></td>--%>
- <%-- <td align="center" id="checkCode_err" >${checkCode_err_msg}</td>--%>
- <%-- </tr>--%>
- </table>
-
- <input value="注 册" type="submit" id="reg_btn">
-
- <br >
- </form>
- </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 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 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>
- </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">
-
- <input type="hidden" name="id" value="<%=id%>">
- 学号:
- <input name="stuNumber"><br>
-
- 姓名:
- <input name="name"><br>
-
- 年龄:
- <input name="age"><br>
-
- 性别:
- <input name="sex"><br>
-
- 语文成绩:
- <input name="chineseScore"><br>
-
- 数学成绩:
- <input name="mathScore"><br>
-
- 英语成绩:
- <input name="englishScore"><br>
-
- <input type="submit" value="提交">
-
- </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("/https://www.cnblogs.com/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项目中启动即可,不过这个案例有很多不足的地方,可自行修改;最终目录结构如下所示
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作! |