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

2021-08-16 17:17:44 浏览数 (1)

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

2.编写pom.xml文件

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

代码语言:javascript复制
<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.0modelVersion>
    <parent>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-parentartifactId>
        <version>2.3.3.RELEASEversion>
        <relativePath/> 
    parent>
    <groupId>comgroupId>
    <artifactId>student_systemartifactId>
    <version>0.0.1-SNAPSHOTversion>
    <name>student_systemname>
    <description>Demo project for Spring Bootdescription>

    <properties>
        <java.version>1.8java.version>
    properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>
        <dependency>
            <groupId>org.mybatis.spring.bootgroupId>
            <artifactId>mybatis-spring-boot-starterartifactId>
            <version>2.1.3version>
        dependency>

        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-devtoolsartifactId>
            <scope>runtimescope>
            <optional>trueoptional>
        dependency>
        <dependency>
            <groupId>org.apache.commonsgroupId>
            <artifactId>commons-lang3artifactId>
            <version>3.9version>
        dependency>
        <dependency>
            <groupId>jstlgroupId>
            <artifactId>jstlartifactId>
            <version>1.2version>
        dependency>
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <scope>runtimescope>
        dependency>
        <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>druidartifactId>
            <version>1.1.22version>
        dependency>
        <dependency>
            <groupId>log4jgroupId>
            <artifactId>log4jartifactId>
            <version>1.2.17version>
        dependency>
        <dependency>
            <groupId>org.apache.tomcat.embedgroupId>
            <artifactId>tomcat-embed-jasperartifactId>
        dependency>
        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
            <optional>trueoptional>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintagegroupId>
                    <artifactId>junit-vintage-engineartifactId>
                exclusion>
            exclusions>
        dependency>
    dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-maven-pluginartifactId>
            plugin>
        plugins>
    build>

project>

3.编写application.properties

代码语言:javascript复制
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.数据库设计

代码语言:javascript复制
/*用户表*/
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设计,让我这个后端的小白还是很喜欢的。

代码语言:javascript复制
<%@page contentType="text/html; UTF-8" pageEncoding="UTF-8" isELIgnored="false" %>

<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">
                
                <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>
                
                <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;">
                                    
                                    <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">记住密码  label>
                                    div>
                                div>
                            form>
                            <br>
                            <br>
                            <small>没有账号?small><a href="regist.jsp" class="signup"> 注册a>
                        div>
                    div>
                div>
            div>
        div>
    div>
div>
body>
html>


<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)

代码语言:javascript复制
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)

代码语言:javascript复制
package com.mapper;

import com.pojo.User;
import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface UserMapper {

   User  findByName(String name);
}

编写Mapper.xml(UserMapper)

代码语言:javascript复制
<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)

代码语言:javascript复制
package com.service;

import com.pojo.User;

public interface UserService {

    User login (User user);
}

顺便写了实现类(UserServiceImpl)

代码语言:javascript复制
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("用户名输入错误,请从新输入");
    }


}

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

代码语言:javascript复制
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)

代码语言:javascript复制
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.注册

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

代码语言:javascript复制
<%@page contentType="text/html; UTF-8" pageEncoding="UTF-8" isELIgnored="false" %>

<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Bootstrap Material Admintitle>
    <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="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">
                
                <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>
                
                <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"> 登录a>
                        form>
                        div>
                    div>
                div>
            div>
        div>
    div>
div>

<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接口

代码语言:javascript复制
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的名字要相同)

代码语言:javascript复制
<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接口

代码语言:javascript复制
package com.service;

import com.pojo.User;

public interface UserService {

    void register(User user);

    User login (User user);
}

编写ServiceImpl

代码语言:javascript复制
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的时候了

代码语言:javascript复制
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.跳转首页(略丑,轻喷)

头部jsp

代码语言:javascript复制
<%@ 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

代码语言:javascript复制
<%@ 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

代码语言:javascript复制
<%@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 morea>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% Completespan>
            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.0h3>
                    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.0h3>
                    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.0h3>
                    div>
                div>
            div>
        div>
    div>
div>

主页引用

代码语言:javascript复制
<%@page contentType="text/html; UTF-8" pageEncoding="UTF-8" isELIgnored="false" %>

<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>Documenttitle>
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,我会一直继续更新这个博客的

码云地址:https://gitee.com/XiaoLin_Java/student_system

0 人点赞