IDEA_BAIMG5f506968e7bce7620521f2bb.jpg

本片博客记录新增登录注册页面,以及前端后台的数据校验
整个项目的博客在下方【从零到一】

一、用户表【存储用户注册信息】

在这里插入图片描述

二、首页

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>首页</title>
    <link href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
    <style>
      h1{
        width: 280px;
        height: 120px;
        line-height: 120px;
        margin: 200px auto;
        text-align: center;
        font-family: "新宋体";
        background-color: cadetblue;
        border-radius: 10px;
      }

      a{
        text-decoration: none;
        }

      body {
        background-image: url("img/img5.jpg");
        background-size: cover;
      }
    </style>
  </head>
  <body style="overflow:-Scroll;overflow-x:hidden">

  <nav class="navbar navbar-inverse">
    <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="${pageContext.request.contextPath}/index.jsp">可星图书管理系统V3.0</a>
      </div>

      <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
        <ul class="nav navbar-nav navbar-right">
          <li><a href="${pageContext.request.contextPath}/login/gologin">登录</a></li>
          <li><a href="${pageContext.request.contextPath}/register/goregister">注册</a></li>
        </ul>
      </div>
    </div>
  </nav>

</html>

页面
在这里插入图片描述

三、实现注册功能

1、pojo

package cn.kexing.pojo;

public class User {
    private String username;
    private String sex;
    private String password;
    private String email;
    private String status;

    public User() {
    }

    public User(String username, String sex, String password, String email, String status) {
        this.username = username;
        this.sex = sex;
        this.password = password;
        this.email = email;
        this.status = status;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    @Override
    public String toString() {
        return "User{" +
                "username='" + username + '\'' +
                ", sex='" + sex + '\'' +
                ", password='" + password + '\'' +
                ", email='" + email + '\'' +
                ", status='" + status + '\'' +
                '}';
    }
}

2、mapper接口

package cn.kexing.dao;
import cn.kexing.pojo.User;
import org.apache.ibatis.annotations.Param;

public interface RegisterMapper {
    //新增用户
    int addUser(User user);
    //查询用户名
    String checkUsername(@Param("username") String username);
}

3、mapper映射文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="cn.kexing.dao.RegisterMapper">
    <insert id="addUser" parameterType="user">
        INSERT INTO `user` VALUES(#{username},#{sex},#{password},#{email},"1")
    </insert>

    <select id="checkUsername" resultType="String" parameterType="String">
        select status from user where username=#{username}
    </select>
</mapper>

4、mapper实现类

package cn.kexing.dao;

import cn.kexing.pojo.User;
import org.mybatis.spring.SqlSessionTemplate;

public class RegisterMapperImpl implements RegisterMapper {
    private SqlSessionTemplate sqlSession;

    public void setSqlSession(SqlSessionTemplate sqlSession) {
        this.sqlSession = sqlSession;
    }

    @Override
    public int addUser(User user) {
        RegisterMapper mapper = sqlSession.getMapper(RegisterMapper.class);
        return mapper.addUser(user);
    }

    @Override
    public String checkUsername(String username) {
        RegisterMapper mapper = sqlSession.getMapper(RegisterMapper.class);
        return mapper.checkUsername(username);
    }
}

5、注册mapper

    <bean class="cn.kexing.dao.RegisterMapperImpl" id="registerMapper">
        <property name="sqlSession" ref="sqlSession"></property>
    </bean>

6、service接口

package cn.kexing.service;

import cn.kexing.pojo.User;

public interface RegisterService {
    int addUser(User user);
    String checkUsername(String username);
}

7、service实现类

package cn.kexing.service;

import cn.kexing.dao.RegisterMapperImpl;
import cn.kexing.pojo.User;

public class RegisterServiceImpl implements RegisterService {
    private RegisterMapperImpl registerMapper;

    public void setRegisterMapper(RegisterMapperImpl registerMapper) {
        this.registerMapper = registerMapper;
    }

    @Override
    public int addUser(User user) {
        return registerMapper.addUser(user);
    }

    @Override
    public String checkUsername(String username) {
        return registerMapper.checkUsername(username);
    }
}

8、Register controller

package cn.kexing.contoller;

import cn.kexing.pojo.User;
import cn.kexing.service.RegisterServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/register")
public class RegisterController {
    @Autowired
    @Qualifier(value = "registerService")
    private RegisterServiceImpl registerService;

    @RequestMapping("/goregister")
    public String goRegister(){
        return "register";
    }

    @RequestMapping("/addregister")
    public String addRegister(User user,String passwordAgain){
        int res = 0;
//        验证了密码和重复密码
        if(user.getPassword().length()>=6 && user.getPassword().equals(passwordAgain)){
            res = registerService.addUser(user);
        }

        if(res == 1){
            return "redirect:/login/gologin";
        }else{
            return "redirect:/register/goregister";
        }
    }

    @ResponseBody
    @RequestMapping("/checkusername")
    public String checkUsername(String username){
        if("1".equals(registerService.checkUsername(username))){
            return "false";
        }
        return "true";
    }
}

9、注册页面

表单验证用了js+ajax ,没有用原生ajax , 下方引入了JQuery

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <link rel="shortcut icon" href="#" />
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- 上述3个meta标签*必须*放在最前面,任何其他内容都*必须*跟随其后! -->
    <title>注册</title>
    <link href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
    <script src="${pageContext.request.contextPath}/JQuery-js/jquery-3.3.1.js" charset="utf-8"></script>
    <style>
        #front {
            width: 1000px;
            height: 600px;
            background-color: black;
            opacity: 0.4;
            position: relative;
            left: 230px;
            border-radius: 10px;
        }

        body {
            background: url("/img/img4.jpg") no-repeat;
            background-size: cover;
        }

        .form-control {
            width: 400px;
        }

        #first {
            position: relative;
            bottom: 560px;
            left: 330px;
            width: 800px;
            height: 450px;
            background-color: white;
            opacity: 0.6;
            border-radius: 10px;
            padding-top: 40px;
        }

        label {
            color: black;
        }

        #make {
            font-size: 20px;
            position: relative;
            left: 300px;
            top: 10px;

        }

        #registered {
            color: white;
            position: relative;
            bottom: 590px;
            left: 260px;
            font-style: italic;
            font-family: Verdana;
            font-size: 28px;
        }
    </style>


</head>

<body style="overflow:-Scroll;overflow-x:hidden;overflow:-Scroll;overflow-y:hidden">
<nav class="navbar navbar-inverse">
    <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="${pageContext.request.contextPath}/index.jsp">可星图书管理系统V3.0</a>
        </div>

        <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
            <ul class="nav navbar-nav navbar-right">
                <li><a href="${pageContext.request.contextPath}/login/gologin">登录</a></li>
                <li><a href="${pageContext.request.contextPath}/register/goregister">注册</a></li>
            </ul>
        </div>
    </div>
</nav>

<div id="front"> </div>
<div id="registered">registered</div>
<div id="first">

    <form class="form-horizontal" style="position: relative; top: 30px; left: 40px;"action="${pageContext.request.contextPath}/register/addregister" method="post">
        <div class="form-group">
            <label class="col-sm-2 control-label">用户名:</label>
            <div class="col-sm-10">
                <input type="text" class="form-control" name="username" id="username" placeholder="Log-in name"
                       style="float: left;">
                <span id="span_log" style=" position: relative; top: 5px; left: 10px;"></span>
            </div>
        </div>

        <div class="form-group">
            <label class="col-sm-2 control-label">性别:</label>
            <div class="col-sm-10">
                <select class="form-control" name="sex" id="sel1" style="width: 70px;">
                    <option name="sex">男</option>
                    <option name="sex">女</option>
                </select>
            </div>
        </div>

        <div class="form-group">
            <label class="col-sm-2 control-label">密码:</label>
            <div class="col-sm-10">
                <input type="password" class="form-control" name="password" id="password" placeholder="Password"
                       style="float: left;">
                <span id="span_pwd" style=" position: relative; top: 5px; left: 10px;"></span>
            </div>
        </div>

        <div class="form-group">
            <label class="col-sm-2 control-label">再次输入密码:</label>
            <div class="col-sm-10">
                <input type="password" class="form-control" name="passwordAgain" id="passwordAgain" placeholder="Password Again"
                       style="float: left;">
                <span id="span_agn" style=" position: relative; top: 5px; left: 10px;"></span>
            </div>
        </div>

        <div class="form-group">
            <label class="col-sm-2 control-label">电子邮箱:</label>
            <div class="col-sm-10">
                <input type="email" class="form-control" name="email" id="email" placeholder="Email"
                       style="float: left;">
                <span id="span_email" style=" position: relative; top: 5px; left: 10px;"></span>
            </div>
        </div>



        <div class="form-group">
            <label class="col-sm-2 control-label"></label>
            <input type="submit" class="btn btn-success" id="submit" value="提交">
            <input type="reset" class="btn btn-warning" value="重置">
        </div>

        <div id="make">By 国服冰&copy;</div>
    </form>
</div>

<script>
    window.onload = function () {
        function loginName() {
            var loginName = document.getElementById("username").value;
            var reg = /^[0-9a-zA-Z]{2,}$/;
            var span = document.getElementById("span_log");
            if (!reg.test(loginName)) {
                span.style.color = "red";
                span.innerHTML = "登录名无效!";
            } else {
                span.style.color = "#33CC99";
                span.innerHTML = "输入正确√";
            }

            $.ajax({
                url:"${pageContext.request.contextPath}/register/checkusername",
                data:{'username':$("#username").val()},
                type:"post",
                success:function (data) {
                    if("false" == data){
                        span.style.color = "red";
                        span.innerHTML = "用户名已存在!";
                    }
                }
            })
        }
        document.getElementById("username").onblur = loginName;
        document.getElementById("username").onfocus = function () {
            var span_name = document.getElementById("span_log");
            span_name.style.color = "#330099";
            span_name.innerHTML = "请输入登录名(仅包含数字和字母)";
        }

        function Password() {
            var pwd = document.getElementById("password").value;
            var reg = /^[a-zA-Z0-9]{6,}$/;
            var span = document.getElementById("span_pwd");
            if (!reg.test(pwd)) {
                span.style.color = "red";
                span.innerHTML = "密码必须多于或等于6个字符!";
            } else {
                span.style.color = "#33CC99";
                span.innerHTML = "输入正确√";
            }
        }
        document.getElementById("password").onblur = Password;
        document.getElementById("password").onfocus = function () {
            var span_name = document.getElementById("span_pwd");
            span_name.style.color = "#330099";
            span_name.innerHTML = "请输入密码(多于或等于6个字符!)";
        }

        function PasswordAgain() {
            var pwd = document.getElementById("password").value;
            var ag = document.getElementById("passwordAgain").value;
            var span = document.getElementById("span_agn");
            if (pwd != ag) {
                span.style.color = "red";
                span.innerHTML = "两次输入不一致!";
            } else {
                span.style.color = "#33CC99";
                span.innerHTML = "输入正确√";
            }
        }
        document.getElementById("passwordAgain").onblur = PasswordAgain;
        document.getElementById("passwordAgain").onfocus = function () {
            var span_name = document.getElementById("span_agn");
            span_name.style.color = "#330099";
            span_name.innerHTML = "请重复输入一次密码";
        }

        function Email() {
            var email = document.getElementById("email").value;
            var reg = /^(\w)+(\.\w+)*@(\w)+((\.\w{2,3}){1,3})$/;
            var span = document.getElementById("span_email");
            if (!reg.test(email)) {
                span.style.color = "red";
                span.innerHTML = "Email地址不合法!";
            } else {
                span.style.color = "#33CC99";
                span.innerHTML = "输入正确√";
            }
        }
        document.getElementById("email").onblur = Email;
        document.getElementById("email").onfocus = function () {
            var span_name = document.getElementById("span_email");
            span_name.style.color = "#330099";
            span_name.innerHTML = "请输入电子邮箱";
        }
    }

    function submit() {
        var username = document.getElementById("span_log");
        var password = document.getElementById("span_pwd");
        var passwordAgain = document.getElementById("span_agn");
        var email = document.getElementById("span_email");
        if(username.style.color === "red" || password.style.color === "red" || passwordAgain.style.color ==="red" || email.style.color ==="red"){
            alert("请正确输入注册信息!");
            location.reload();
        }
    }
    document.getElementById("submit").onclick = submit;
</script>

</body>

</html>

在这里插入图片描述

四、实现登录功能(dao和service和上面差不多就不放了)

1、controller

package cn.kexing.contoller;
import cn.kexing.pojo.Login;
import cn.kexing.service.RegisterService;
import cn.kexing.service.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/login")
public class LoginController {
    @Autowired
    @Qualifier(value = "userService")
    private UserServiceImpl userService;
    @Autowired
    @Qualifier(value = "registerService")
    private RegisterService registerService;

    @RequestMapping("/gologin")
    public String goLogin(){
        return "login";
    }

    @RequestMapping("checklogin")
    public String checkLogin(Login login,HttpSession session){
        String username = userService.checkLogin(login.getUsername(), login.getPassword());
        session.setAttribute("username",login.getUsername());
        if(username != null){
            return "redirect:/book/selectbookforpage";
        }
        return "redirect:/login/gologin";
    }

    @ResponseBody
    @RequestMapping("/checkUsername")
    public String checkUsername(String username){
        if("1".equals(registerService.checkUsername(username))){
            return "true";
        }
            return "false";
    }
}

2、登录页面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <link href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>用户登录</title>
    <script src="${pageContext.request.contextPath}/JQuery-js/jquery-3.3.1.js" charset="utf-8"></script>
    <style>
        body {
            background-image: url("/img/img3.jpg");
            background-size: cover;
        }

        #bg {
            width: 1000px;
            height: 480px;
            background-color: black;
            opacity: 0.4;
            margin: auto;
            margin-top: 20px;
            border-radius: 10px;
        }

        #login {
            width: 500px;
            height: 250px;
            background-color: white;
            position: relative;
            left: 500px;
            bottom: 380px;
            opacity: 0.6;
            border-radius: 10px;
        }

        form {
            padding-top: 45px;
            padding-left: 20px;
        }

        input {
            margin-left: 10px;
        }

        .bn {
            padding-left: 17px;
            bottom: 30px;
        }

        #first {
            font-size: 30px;
            position: relative;
            left: 610px;
            top: 90px;
            color: white;
        }

        #userid {
            float: left;
            padding-left: 20px;
        }

        #pwd {
            float: left;
            padding-left: 20px;
        }

        #copyright {
            position: relative;
            color: white;
            top: 110px;
        }
    </style>
</head>

<body style="overflow:-Scroll;overflow-y:hidden">

<nav class="navbar navbar-inverse">
    <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="${pageContext.request.contextPath}/index.jsp">可星图书管理系统V3.0</a>
        </div>

        <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
        <ul class="nav navbar-nav navbar-right">
            <li><a href="${pageContext.request.contextPath}/login/gologin">登录</a></li>
            <li><a href="${pageContext.request.contextPath}/register/goregister">注册</a></li>
        </ul>
    </div>
    </div>
</nav>
<!-- 导航条 -->

<div id="first" class="glyphicon glyphicon-hand-down"> login here</div>
<div id="bg"></div>

<div id="login">
    <form class="form-horizontal col-xs-11" action="${pageContext.request.contextPath}/login/checklogin" method="POST">
        <div class="form-group">
            <label for="username" class="col-sm-2 control-label">用户名</label>
            <div class="col-sm-10">
                <input type="text" class="form-control col-xs-4 " id="username" name="username" placeholder="&nbsp;请输入用户名">
                <span id="span_username" style=" position: relative; top: 5px; left: 10px;"></span>
            </div>
        </div>
        <div class="form-group">
            <label for="pwd" class="col-sm-2 control-label">密码</label>
            <div class="col-sm-10">
                <input type="password" class="form-control" id="pwd" name="password" placeholder="&nbsp;请输入密码">
            </div>
        </div>

        <div class="form-group" style="position: relative;top: 40px;left: 6px;">
            <div class="col-sm-offset-2 col-sm-10 bn">
                <button type="submit" class="btn btn-default" id="submit">登录</button>
            </div>
        </div>

        <div id="copyright">
            <div style="text-align: center;">By 国服冰</div>
            <div style="text-align: center;">Copyright(C) 2019-2020 guofu_bing All Rights Reserved.</div>
        </div>
    </form>
</div>

<script>
    window.onload= function(){
        function checkUsername() {
            var span = document.getElementById("span_username");
            $.ajax({
                url:"${pageContext.request.contextPath}/login/checkUsername",
                data:{'username':$("#username").val()},
                type:"post",
                success:function (data) {
                    if("false" == data){
                        span.style.color = "red";
                        span.innerHTML = "用户名不存在!";
                    }else{
                        span.innerHTML = "";
                    }
                }
            })
        }
        document.getElementById("username").onblur = checkUsername;
        function submit() {
            var username = document.getElementById("span_username");
            if(username.style.color === "red"){
                alert("用户名不存在!请重新输入");
                location.reload();
            }
        }

        document.getElementById("submit").onclick = submit;

    }
</script>
</body>
</html>

在这里插入图片描述

在这里插入图片描述

**ps:前端是我某次课的课堂作业 这里改了下实现了代码复用,90%的代码都在博客里

       想要全部源码的童鞋私聊我**
最后修改:2021 年 11 月 15 日 05 : 20 PM
如果觉得我的文章对你有用,请随意赞赏