springboot项目(学生管理系统)day01

本文涉及的产品
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
云数据库 RDS MySQL,集群系列 2核4GB
推荐场景:
搭建个人博客
云数据库 RDS PostgreSQL,集群系列 2核4GB
简介: 了解项目和创建springboot文件,编写pom.xml文件

1.了解项目和创建springboot文件


1.JPG


2.编写pom.xml文件


学生管理系统所使用的技术主要是soringboot+jsp+ajax+SSM,所以我们需要引入的包大概有这些:


<?xml version="1.0" encoding="UTF-8"?>
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.3.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com</groupId>
    <artifactId>student_system</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>student_system</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.3</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.9</version>
        </dependency>
        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.22</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>
复制代码


3.编写application.properties


spring.application.name=student_system 
server.servlet.context-path=/student_system 
server.servlet.jsp.init-parameters.development=true
spring.datasource.username=root
spring.datasource.password=
spring.datasource.url=jdbc:mysql://localhost:3306/student_system?useSSL=false&serverTimezone=UTC&characterEncoding=utf-8
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.mvc.view.prefix=/
spring.mvc.view.suffix=.jsp
mybatis.mapper-locations=classpath:com/mapper/*.xml
mybatis.type-aliases-package=com.pojo
logging.level.root=info
logging.level.com.baizhi.dao=debug
复制代码


4.数据库设计


2.JPG

/*用户表*/
create table t_user(
  id int(6) primary key auto_increment,
  name varchar(40),
  password varchar(20),
  status varchar(10),
  regtime timestamp,
  role  varchar(10)
);
/*城市表*/
create table t_city(
  id int(6) primary key auto_increment,
  name varchar(40),
  createtime timestamp,
  numbers int(8)
);
/*标签表*/
create table t_tag(
  id int(6) primary key auto_increment,
  name varchar(40),
  type varchar(20),
  createtime timestamp
);
/*班级表*/
create table t_clazz(
  id int(6) primary key auto_increment,
  name varchar(40),
  tagid int(6) references t_tag(id)
);
/*小组表*/
create table t_group(
  id  int(6) primary key auto_increment,
  name varchar(40),
  content varchar(200),
  clazzid int(6) references t_clazz(id)
);
/*学生表*/
create table t_student(
  id  int(6) primary key auto_increment,
  name varchar(40),
  age int(3),
  bir timestamp,
  phone varchar(11),
  qq    varchar(16),
  attr  varchar(6),
  starts varchar(14),
  mark   varchar(200),
  cityid int(6) references t_city(id),
  clazzid int(6) references t_clazz(id),
  groupid int(6) references t_group(id)
);
/*学生标签关系表*/
create table t_student_tag(
  id int(6) primary key auto_increment,
  studentid int(6) references t_student(id),
  tagid int(6) references t_tag(id),
);
建立数据库: student_system   UTF-8
复制代码


5.用户登陆功能的实现(jsp)


a.登陆


由于我们这次没有使用thymeleaf模板引擎,所以还需要在main下面创建一个webapp目录来保存jsp。前端的页面去网上cope了一个还算美观整洁的页面,自带表单验证功能和一些好看的UI设计,让我这个后端的小白还是很喜欢的。


3.JPG

<%@page contentType="text/html; UTF-8" pageEncoding="UTF-8" isELIgnored="false" %>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>登陆</title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="robots" content="all,follow">
    <link rel="stylesheet" href="https://ajax.aspnetcdn.com/ajax/bootstrap/4.2.1/css/bootstrap.min.css">
    <link rel="stylesheet" href="statics/css/style.default.css" id="theme-stylesheet">
</head>
<body>
<div class="page login-page">
    <div class="container d-flex align-items-center">
        <div class="form-holder has-shadow">
            <div class="row">
                <!-- Logo & Information Panel-->
                <div class="col-lg-6">
                    <div class="info d-flex align-items-center">
                        <div class="content">
                            <div class="logo">
                                <h1>欢迎登录</h1>
                            </div>
                            <p>班级管理系统</p>
                        </div>
                    </div>
                </div>
                <!-- Form Panel    -->
                <div class="col-lg-6 bg-white">
                    <div class="form d-flex align-items-center">
                        <div class="content">
                            <form method="post"  class="form-validate" id="loginFrom">
                                <div class="form-group">
                                    <input id="login-username" type="text" name="name" required data-msg="请输入用户名" placeholder="用户名" value="admin" class="input-material">
                                </div>
                                <div class="form-group">
                                    <input id="login-password" type="password" name="password" required data-msg="请输入密码" placeholder="密码" class="input-material">
                                </div>
                                <div class="form-group">
                                    <input id="login-code" style="width: 60%;float: left" type="text" name="code" required data-msg="请输入验证码" placeholder="验证码" class="input-material">
                                    <img src="${pageContext.request.contextPath}/user/getImage" id="image">
                                </div>
                                <button id="logBtn" type="button" class="btn btn-primary">登录</button>
                                <div style="margin-top: -40px;">
                                    <!-- <input type="checkbox"  id="check1"/>&nbsp;<span>记住密码</span>
                                    <input type="checkbox" id="check2"/>&nbsp;<span>自动登录</span> -->
                                    <div class="custom-control custom-checkbox " style="float: right;">
                                        <input type="checkbox" class="custom-control-input" id="check2" >
                                        <label class="custom-control-label" for="check2">自动登录</label>
                                    </div>
                                    <div class="custom-control custom-checkbox " style="float: right;">
                                        <input type="checkbox" class="custom-control-input" id="check1" >
                                        <label class="custom-control-label" for="check1">记住密码&nbsp;&nbsp;</label>
                                    </div>
                                </div>
                            </form>
                            <br>
                            <br>
                            <small>没有账号?</small><a href="regist.jsp" class="signup">&nbsp;注册</a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
</body>
</html>
<!-- JavaScript files-->
<script src="statics/js/jquery.min.js"></script>
<script src="statics/layui/layui.js"></script>
<script src="statics/js/bootstrap.min.js"></script>
<script src="statics/vendor/jquery-validation/jquery.validate.min.js"></script><!--表单验证-->
<script>
    $(function () {
        // 绑定登陆按钮的单击事件
        $("#logBtn").click(function () {
            $.post("${pageContext.request.contextPath}/user/login",$("#loginFrom").serialize(),function (res) {
                if (res.statue) {
                    layui.use("layer",function () {
                        layer.alert(res.msg+",点击确定跳转至主页", {
                            skin: 'layui-layer-molv' //样式类名
                            ,closeBtn: 0
                        });
                        // var layer=layui.layer;
                        // layer.alert(res.msg+",点击确定跳转至主页");
                    });
                    location.href = "${pageContext.request.contextPath}/back/index.jsp";
                }else(
                    layui.use("layer",function () {
                        var layer=layui.layer;
                        layer.msg(res.msg, {icon: 5});
                    })
                )
            })
        });
        //更换验证码
        $("#image").click(function () {
            $("#image").attr("src","${pageContext.request.contextPath}/user/getImage");
        })
    });
    $(function(){
        /*判断上次是否勾选记住密码和自动登录*/
        var check1s=localStorage.getItem("check1");
        var check2s=localStorage.getItem("check2");
        var oldName=localStorage.getItem("userName");
        var oldPass=localStorage.getItem("passWord");
        if(check1s=="true"){
            $("#login-username").val(oldName);
            $("#login-password").val(oldPass);
            $("#check1").prop('checked',true);
        }else{
            $("#login-username").val('');
            $("#login-password").val('');
            $("#check1").prop('checked',false);
        }
        if(check2s=="true"){
            $("#check2").prop('checked',true);
            $("#loginFrom").submit();
            //location="https://www.baidu.com?userName="+oldName+"&passWord="+oldPass;//添加退出当前账号功能
        }else{
            $("#check2").prop('checked',false);
        }
        $("#login").click(function(){
            var userName=$("#login-username").val();
            var passWord=$("#login-password").val();
            /*获取当前输入的账号密码*/
            localStorage.setItem("userName",userName)
            localStorage.setItem("passWord",passWord)
            /*获取记住密码  自动登录的 checkbox的值*/
            var check1 = $("#check1").prop('checked');
            var check2 = $('#check2').prop('checked');
            localStorage.setItem("check1",check1);
            localStorage.setItem("check2",check2);
        })
        /*$("#check2").click(function(){
            var flag=$('#check2').prop('checked');
            if(flag){
                var userName=$("#login-username").val();
                var passWord=$("#login-password").val();
                $.ajax({
                    type:"post",
                    url:"http://localhost:8080/powers/pow/regUsers",
                    data:{"userName":userName,"passWord":passWord},
                    async:true,
                    success:function(res){
                        alert(res);
                    }
                });
            }
        })*/
    })
</script>
复制代码


创建一个实体类User(偷懒了使用了lombok)


package com.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import lombok.experimental.Accessors;
import java.util.Date;
@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
@Accessors(chain = true)
public class User {
    private String id;
    private String name;
    private String password;
    private String status;
    private Date regtime;
    private String role;
}
复制代码


编写Mapper接口(UserMapper)


package com.mapper;
import com.pojo.User;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface UserMapper {
   User  findByName(String name);
}
复制代码


编写Mapper.xml(UserMapper)


<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.mapper.UserMapper">
    <select id="findByName" parameterType="string" resultType="com.pojo.User">
        select * from t_user where name = #{name}
    </select>
</mapper>
复制代码


编写Service接口(UserService)


package com.service;
import com.pojo.User;
public interface UserService {
    User login (User user);
}
复制代码


顺便写了实现类(UserServiceImpl)


package com.service.impl;
import com.mapper.UserMapper;
import com.pojo.User;
import com.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Date;
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserMapper userMapper;
    @Override
    public User login(User user) {
        User u=userMapper.findByName(user.getName());
        if (u!=null){
            if (u.getPassword().equals(user.getPassword())){
                return u;
            }else {
                throw new RuntimeException("密码输入错误");
            }
        }
        throw new RuntimeException("用户名输入错误,请从新输入");
    }
}
复制代码


还漏了一个很重要的东西—验证码!我在网上找了一个很不错的验证码的工具类,可以码起来,有需要的时候可以拿!


package com.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 VerifyCodeUtils{
    //使用到Algerian字体,系统里没有的话需要安装字体,字体只显示大写,去掉了1,0,i,o几个容易混淆的字符
    public static final String VERIFY_CODES = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";
    private static Random random = new Random();
    /**
     * 使用系统默认字符源生成验证码
     * @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 os
     * @param verifySize
     * @return
     * @throws IOException
     */
    public static String outputVerifyImage(int w, int h, OutputStream os, int verifySize) throws IOException{
        String verifyCode = generateVerifyCode(verifySize);
        outputImage(w, h, os, 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);
        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);
    }
    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);
            }
        }
    }
    public static void main(String[] args) throws IOException {
        //获取验证码
        String s = generateVerifyCode(4);
        //将验证码放入图片中
        outputImage(260,60,new File("/Users/chenyannan/Desktop/安工资料/aa.jpg"),s);
        System.out.println(s);
    }
}
复制代码


最后就是编写我们的Controller进行测试啦(UserController)


package com.controller;
import com.Result.Result;
import com.mapper.UserMapper;
import com.pojo.User;
import com.service.UserService;
import com.utils.VerifyCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserService userService;
    @RequestMapping("login")
    @ResponseBody
    public Result login(String code,User user,HttpSession session){
        Result result =new Result();
//        取出验证码
        String imagecode = (String) session.getAttribute("code");
        try {
            if (imagecode.equalsIgnoreCase(code)){
                User u = userService.login(user);
                session.setAttribute("user",u);//把用户存到session中
                result.setMsg("登陆成功");
                result.setStatue(true);
                return result;
            }
            throw new RuntimeException("验证码输入错误!!");
        }catch (Exception e){
            e.printStackTrace();
            result.setStatue(false);
            result.setMsg(e.getMessage());
        }
        return result;
    }
    //    生成验证码
    @RequestMapping("getImage")
    public void getImage(HttpSession session, HttpServletResponse response) throws IOException {
//        1.获取随机数
        String code = VerifyCodeUtils.generateVerifyCode(4);//获取4位随机数
//        2.将数字存入session中
        session.setAttribute("code", code);
//        3.生成验证码图片
        VerifyCodeUtils.outputImage(120, 43, response.getOutputStream(), code);
    }
}
复制代码


结语:这样我们的登陆功能就写好啦,如果有bug可以留言噢


b.注册


注册的功能其实和登陆如出一辙,一个是去数据库里面根据用户名查询,然后检验密码是否正确,注册就是往数据库里面添加一条数据,首先是页面的引入


4.JPG

<%@page contentType="text/html; UTF-8" pageEncoding="UTF-8" isELIgnored="false" %>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Bootstrap Material Admin</title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="robots" content="all,follow">
    <!-- Bootstrap CSS-->
    <link rel="stylesheet" href="statics/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Poppins:300,400,700">
    <link rel="stylesheet" href="statics/css/style.default.css" id="theme-stylesheet">
</head>
<body>
<div class="page login-page">
    <div class="container d-flex align-items-center">
        <div class="form-holder has-shadow">
            <div class="row">
                <!-- Logo & Information Panel-->
                <div class="col-lg-6">
                    <div class="info d-flex align-items-center">
                        <div class="content">
                            <div class="logo">
                                <h1>欢迎注册</h1>
                            </div>
                            <p>注册登录界面模板</p>
                        </div>
                    </div>
                </div>
                <!-- Form Panel    -->
                <div class="col-lg-6 bg-white">
                    <div class="form d-flex align-items-center">
                        <div class="content">
                            <form id="regForm">
                            <div class="form-group">
                                <input id="register-username" class="input-material" type="text" name="name" placeholder="请输入用户名/姓名" >
                                <div class="invalid-feedback">
                                    用户名必须在2~10位之间
                                </div>
                            </div>
                            <div class="form-group">
                                <input id="register-password" class="input-material" type="password" name="password" placeholder="请输入密码"   >
                                <div class="invalid-feedback">
                                    密码必须在6~10位之间
                                </div>
                            </div>
                            <div class="form-group">
                                <input id="register-passwords" class="input-material" type="password" name="passwords" placeholder="确认密码"   >
                                <div class="invalid-feedback">
                                    两次密码必须相同 且在6~10位之间
                                </div>
                            </div>
                            <div class="form-group">
                                <label for="role"></label>
                            <select class="form-control" name="role" id="role">
                                <option value="admin">管理员</option>
                                <option value="student">学生</option>
                            </select>
                            </div>
                            <br>
                            <div class="form-group">
                                <button id="regBtn" type="button" name="registerSubmit" class="btn btn-primary">注册</button>
                            </div>
                            <small>已有账号?</small><a href="login.html" class="signup">&nbsp;登录</a>
                        </form>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<!-- JavaScript files-->
<script src="statics/js/jquery.min.js"></script>
<script src="statics/layui/layui.js"></script>
<script src="statics/js/bootstrap.min.js"></script>
<script>
    $(function(){
        //注册
        $("#regBtn").click(function(){
            $.post("${pageContext.request.contextPath}/user/register",$("#regForm").serialize(),function (res) {
                if(res.statue){
                    layui.use("layer",function () {
                        var layer=layui.layer;
                        layer.alert(res.msg+",点击确定跳转至登录页面", {icon: 6});
                    });
                    location.href = "${pageContext.request.contextPath}/back/login.jsp";
                }else{
                    layui.use("layer",function () {
                        var layer=layui.layer;
                        layer.msg(res.msg, {icon: 5});
                    });
                }
            });
        });
        /*错误class  form-control is-invalid
        正确class  form-control is-valid*/
        var flagName=false;
        var flagPas=false;
        var flagPass=false;
        /*验证用户名*/
        var name,passWord,passWords;
        $("#register-username").change(function(){
            name=$("#register-username").val();
            if(name.length<2||name.length>10){
                $("#register-username").removeClass("form-control is-valid")
                $("#register-username").addClass("form-control is-invalid");
                flagName=false;
            }else{
                $("#register-username").removeClass("form-control is-invalid")
                $("#register-username").addClass("form-control is-valid");
                flagName=true;
            }
        })
        /*验证密码*/
        $("#register-password").change(function(){
            passWord=$("#register-password").val();
            if(passWord.length<6||passWord.length>18){
                $("#register-password").removeClass("form-control is-valid")
                $("#register-password").addClass("form-control is-invalid");
                flagPas=false;
            }else{
                $("#register-password").removeClass("form-control is-invalid")
                $("#register-password").addClass("form-control is-valid");
                flagPas=true;
            }
        })
        /*验证确认密码*/
        $("#register-passwords").change(function(){
            passWords=$("#register-passwords").val();
            if((passWord!=passWords)||(passWords.length<6||passWords.length>18)){
                $("#register-passwords").removeClass("form-control is-valid")
                $("#register-passwords").addClass("form-control is-invalid");
                flagPass=false;
            }else{
                $("#register-passwords").removeClass("form-control is-invalid")
                $("#register-passwords").addClass("form-control is-valid");
                flagPass=true;
            }
        })
        $("#regbtn").click(function(){
            if(flagName&&flagPas&&flagPass){
                localStorage.setItem("name",name);
                localStorage.setItem("passWord",passWord);
                location="login.html"
            }else{
                if(!flagName){
                    $("#register-username").addClass("form-control is-invalid");
                }
                if(!flagPas){
                    $("#register-password").addClass("form-control is-invalid");
                }
                if(!flagPass){
                    $("#register-passwords").addClass("form-control is-invalid");
                }
            }
        })
    })
</script>
</body>
</html>
复制代码


编写Mapper接口


package com.mapper;
import com.pojo.User;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface UserMapper {
    void save(User user);
   User  findByName(String name);
}
复制代码


编写Mapper.xml(一定要注意namespace的值和Mapper的名字要相同)


<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.mapper.UserMapper">
    <insert id="save" parameterType="com.pojo.User" useGeneratedKeys="true" keyProperty="id">
        insert into t_user values (#{id},#{name},#{password},#{status},#{regtime},#{role})
    </insert>
    <select id="findByName" parameterType="string" resultType="com.pojo.User">
        select * from t_user where name = #{name}
    </select>
</mapper>
复制代码


编写Service接口


package com.service;
import com.pojo.User;
public interface UserService {
    void register(User user);
    User login (User user);
}
复制代码


编写ServiceImpl


package com.service.impl;
import com.mapper.UserMapper;
import com.pojo.User;
import com.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Date;
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserMapper userMapper;
    @Override
    public void register(User user) {
        User u = userMapper.findByName(user.getName());
        if (u!=null){
            throw new RuntimeException("当前用户名已被注册");
        }else {
            user.setRegtime(new Date());
            user.setStatus("激活");
            userMapper.save(user);
        }
    }
    @Override
    public User login(User user) {
        User u=userMapper.findByName(user.getName());
        if (u!=null){
            if (u.getPassword().equals(user.getPassword())){
                return u;
            }else {
                throw new RuntimeException("密码输入错误");
            }
        }
        throw new RuntimeException("用户名输入错误,请从新输入");
    }
}
复制代码


最后就是到了Controller的时候了


package com.controller;
import com.Result.Result;
import com.mapper.UserMapper;
import com.pojo.User;
import com.service.UserService;
import com.utils.VerifyCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserService userService;
//    用户退出
    @RequestMapping("logout")
    public String logout(HttpSession session){
        session.invalidate();
        return "redirect:/back/login.jsp";
    }
    @RequestMapping("login")
    @ResponseBody
    public Result login(String code,User user,HttpSession session){
        Result result =new Result();
//        取出验证码
        String imagecode = (String) session.getAttribute("code");
        try {
            if (imagecode.equalsIgnoreCase(code)){
                User u = userService.login(user);
                session.setAttribute("user",u);//把用户存到session中
                result.setMsg("登陆成功");
                result.setStatue(true);
                return result;
            }
            throw new RuntimeException("验证码输入错误!!");
        }catch (Exception e){
            e.printStackTrace();
            result.setStatue(false);
            result.setMsg(e.getMessage());
        }
        return result;
    }
    @RequestMapping("register")
    @ResponseBody
    public Result register(User user) {
        Result result = new Result();
        try {
            userService.register(user);
            result.setMsg("注册成功");
            result.setStatue(true);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            result.setStatue(false);
            result.setMsg(e.getMessage());
            return result;
        }
    }
    //    生成验证码
    @RequestMapping("getImage")
    public void getImage(HttpSession session, HttpServletResponse response) throws IOException {
//        1.获取随机数
        String code = VerifyCodeUtils.generateVerifyCode(4);//获取4位随机数
//        2.将数字存入session中
        session.setAttribute("code", code);
//        3.生成验证码图片
        VerifyCodeUtils.outputImage(120, 43, response.getOutputStream(), code);
    }
}
复制代码


c.跳转首页(略丑,轻喷)


5.JPG


头部jsp


<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@page contentType="text/html; UTF-8" pageEncoding="UTF-8" isELIgnored="false" %>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css"/>
<script src="${pageContext.request.contextPath}/back/statics/js/jquery-1.8.3.min.js"></script>
<body >
<nav class="navbar navbar-default">
    <div class="container-fluid">
        <!-- Brand and toggle get grouped for better mobile display -->
        <div class="navbar-header">
            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse"
                    data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
            <a class="navbar-brand" href="#">班级管理系统
                <small>V1.0</small>
            </a>
        </div>
        <!-- Collect the nav links, forms, and other content for toggling -->
        <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
            <ul class="nav navbar-nav navbar-right">
                <c:if test="${sessionScope.user!=null}">
                    <li><a href="javascript:;">欢迎: <span class="text-danger">${sessionScope.user.name}</span></a></li>
                    <a href="${pageContext.request.contextPath}/user/logout" target="_top" type="button"
                       class="btn btn-danger navbar-btn">退出</a>
                </c:if>
                <c:if test="${sessionScope.user==null}">
                    <li><a href="javascript:;"><span class="text-info">您当前还是访客身份,赶紧去登录吧~~</span></a></li>
                    <a href="${pageContext.request.contextPath}/back/login.jsp" target="_top" type="button"
                       class="btn btn-primary navbar-btn">登录</a>
                </c:if>
            </ul>
        </div>
    </div>
</nav>
</body>
复制代码


菜单jsp


<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@page contentType="text/html; UTF-8" pageEncoding="UTF-8" isELIgnored="false" %>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css"/>
<script src="${pageContext.request.contextPath}/back/statics/js/jquery-1.8.3.min.js"></script>
<style>
    body,ul,li{
        background:#eee;
    }
    .list-group-item{
        background: #eee;
    }
</style>
<body>
<ul class="list-group text-center" style="margin-top: 70px;">
    <li class="list-group-item"><a href="${pageContext.request.contextPath}/student/findAll" target="content">学生管理</a>
    </li>
    <c:if test="${sessionScope.user.role=='admin'}">
        <li class="list-group-item"><a href="${pageContext.request.contextPath}/group/findAll" target="content">小组管理</a>
        </li>
        <li class="list-group-item"><a href="${pageContext.request.contextPath}/clazz/findAll" target="content">班级管理</a>
        </li>
        <li class="list-group-item"><a href="${pageContext.request.contextPath}/tag/findAll" target="content">标签管理</a>
        </li>
        <li class="list-group-item"><a href="${pageContext.request.contextPath}/city/findAll" target="content">城市管理</a>
        </li>
    </c:if>
</ul>
</body>
复制代码


主页jsp


<%@page contentType="text/html; UTF-8" pageEncoding="UTF-8" isELIgnored="false" %>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css"/>
<div class="jumbotron">
    <div class="container">
        <h1>Hello, world!</h1>
        <p>This is a simple hero unit, a simple jumbotron-style component for calling extra attention to featured
            content or informatio...</p>
        <p><a class="btn btn-primary btn-lg" href="#" role="button">Learn more</a></p>
        <p>磁盘使用率:(40%)</p>
        <div class="progress">
            <div class="progress-bar progress-bar-success progress-bar-striped" role="progressbar" aria-valuenow="40"
                 aria-valuemin="0" aria-valuemax="100" style="width: 40%">
                <span class="sr-only">40% Complete (success)</span>
            </div>
        </div>
        <p>内存使用率:(20%)</p>
        <div class="progress">
            <div class="progress-bar progress-bar-info progress-bar-striped" role="progressbar" aria-valuenow="20"
                 aria-valuemin="0" aria-valuemax="100" style="width: 20%">
                <span class="sr-only">20% Complete</span>
            </div>
        </div>
        <p>cpu使用率:(60%)</p>
        <div class="progress">
            <div class="progress-bar progress-bar-warning progress-bar-striped" role="progressbar" aria-valuenow="60"
                 aria-valuemin="0" aria-valuemax="100" style="width: 60%">
                <span class="sr-only">60% Complete (warning)</span>
            </div>
        </div>
        <p>数据库使用率:(80%)</p>
        <div class="progress">
            <div class="progress-bar progress-bar-danger progress-bar-striped" role="progressbar" aria-valuenow="80"
                 aria-valuemin="0" aria-valuemax="100" style="width: 80%">
                <span class="sr-only">80% Complete (danger)</span>
            </div>
        </div>
        <div class="row" style="margin-top: 20px;">
            <div class="col-sm-6 col-md-4">
                <div class="thumbnail">
                    <%--<img src="${pageContext.request.contextPath}/back/statics/images/home.jpeg" >--%>
                    <div class="caption">
                        <h3>班级管理系统V1.0</h3>
                    </div>
                </div>
            </div>
            <div class="col-sm-6 col-md-4">
                <div class="thumbnail">
                    <%--<img src="${pageContext.request.contextPath}/back/statics/images/home.jpeg" >--%>
                    <div class="caption">
                        <h3>班级管理系统V1.0</h3>
                    </div>
                </div>
            </div>
            <div class="col-sm-6 col-md-4">
                <div class="thumbnail">
                    <img src="${pageContext.request.contextPath}/back/statics/images/home.jpeg" >
                    <div class="caption">
                        <h3>班级管理系统V1.0</h3>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
复制代码


主页引用


<%@page contentType="text/html; UTF-8" pageEncoding="UTF-8" isELIgnored="false" %>
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<frameset rows="50px,*" border="1px" borderColor="black" scrolling="no" noresize="noresize">
    <%--引入标题--%>
    <frame src="${pageContext.request.contextPath}/back/main/head.jsp">
    <frameset cols="200px,*">
        <frame src="${pageContext.request.contextPath}/back/main/menu.jsp">
        <%--中心布局--%>
        <frame src="${pageContext.request.contextPath}/back/main/home.jsp" name="content">
    </frameset>
</frameset>
</html>
复制代码

6.结语


day01就结束了,简单的写一个注册和登陆功能,明天会开始正式进入业务实现功能和编码,如果想获取源码的话可以移步我的码云,不做白嫖党(坏笑),喜欢的小朋友可以给一个start



相关实践学习
【文生图】一键部署Stable Diffusion基于函数计算
本实验教你如何在函数计算FC上从零开始部署Stable Diffusion来进行AI绘画创作,开启AIGC盲盒。函数计算提供一定的免费额度供用户使用。本实验答疑钉钉群:29290019867
建立 Serverless 思维
本课程包括: Serverless 应用引擎的概念, 为开发者带来的实际价值, 以及让您了解常见的 Serverless 架构模式
相关文章
|
1月前
|
Java 应用服务中间件
SpringBoot获取项目文件的绝对路径和相对路径
SpringBoot获取项目文件的绝对路径和相对路径
107 1
SpringBoot获取项目文件的绝对路径和相对路径
|
1月前
|
分布式计算 关系型数据库 MySQL
SpringBoot项目中mysql字段映射使用JSONObject和JSONArray类型
SpringBoot项目中mysql字段映射使用JSONObject和JSONArray类型 图像处理 光通信 分布式计算 算法语言 信息技术 计算机应用
57 8
|
1月前
|
存储 运维 安全
Spring运维之boot项目多环境(yaml 多文件 proerties)及分组管理与开发控制
通过以上措施,可以保证Spring Boot项目的配置管理在专业水准上,并且易于维护和管理,符合搜索引擎收录标准。
45 2
|
1月前
|
XML Java 数据库连接
SpringBoot集成Flowable:打造强大的工作流管理系统
在企业级应用开发中,工作流管理是一个核心组件,它能够帮助我们定义、执行和管理业务流程。Flowable是一个开源的工作流和业务流程管理(BPM)平台,它提供了强大的工作流引擎和建模工具。结合SpringBoot,我们可以快速构建一个高效、灵活的工作流管理系统。本文将探讨如何将Flowable集成到SpringBoot应用中,并展示其强大的功能。
267 1
|
1月前
|
JavaScript 前端开发 Java
SpringBoot项目的html页面使用axios进行get post请求
SpringBoot项目的html页面使用axios进行get post请求
59 2
|
1月前
|
JSON Java 数据库
SpringBoot项目使用AOP及自定义注解保存操作日志
SpringBoot项目使用AOP及自定义注解保存操作日志
53 1
|
1月前
|
JavaScript 前端开发 Java
SpringBoot项目的html页面使用axios进行get post请求
SpringBoot项目的html页面使用axios进行get post请求
40 0
|
1月前
|
JavaScript NoSQL Java
CC-ADMIN后台简介一个基于 Spring Boot 2.1.3 、SpringBootMybatis plus、JWT、Shiro、Redis、Vue quasar 的前后端分离的后台管理系统
CC-ADMIN后台简介一个基于 Spring Boot 2.1.3 、SpringBootMybatis plus、JWT、Shiro、Redis、Vue quasar 的前后端分离的后台管理系统
49 0
|
Java 应用服务中间件 Maven
传统maven项目和现在spring boot项目的区别
Spring Boot:传统 Web 项目与采用 Spring Boot 项目区别
509 0
传统maven项目和现在spring boot项目的区别
|
XML Java 数据库连接
创建springboot项目的基本流程——以宠物类别为例
创建springboot项目的基本流程——以宠物类别为例
157 0
创建springboot项目的基本流程——以宠物类别为例