利用springboot框架及Ajax制作一个简易的注册系统(连接数据库)

系列文章目录

利用springboot框架及Ajax制作一个简易的登录系统(连接数据库)(2).

简单的注册(账号密码)并实现密码加密


前言

初学springboot做简单的登录注册


提示:以下是本篇文章正文内容,下面案例可供参考

一、工程图片

在这里插入图片描述

二、使用步骤

1.新建springboot项目

1.1 修改pom.xml文件


<?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.1.0.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</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.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>

        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.2</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter</artifactId>
            <version>5.5.0</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

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

</project>


1.2修改application.properties文件

# datasource config
spring.datasource.url=jdbc:mysql://localhost:3306/(数据库名称)?useUnicode=true&serverTimezone=Asia/Shanghai&characterEncoding=utf8&autoReconnect=true&useSSL=false
spring.datasource.username=数据库名
spring.datasource.password=密码
# mybatis config
mybatis.mapper-locations=classpath:mapper/*Dao.xml



代码如下(示例):

2.新建数据库

代码如下(示例):

CREATE TABLE test1 (
`id` BIGINT(11)UNSIGNED NOT NULL AUTO_INCREMENT,
`userName` VARCHAR(50)   NOT NULL DEFAULT'',
`password` VARCHAR(50) NOT NULL DEFAULT '',
PRIMARY KEY(`id`)
)ENGINE=INNODB DEFAULT CHARSET=UTF8;

数据表名称为test1


3.实体层填写

package com.springboot.regist.demo.entity;

public class User {
    private String password;
    private String userName;

    public String getPassword() {
        return password;
    }

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

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    @Override
    public String toString() {
        return "User{" +
                "password='" + password + '\'' +
                ", userName='" + userName + '\'' +
                '}';
    }
}

4.三层架构

1.dao层

package com.springboot.regist.demo.dao;

import com.springboot.regist.demo.entity.User;
import org.apache.ibatis.annotations.Param;

public interface Userdao {
    User selectuserName(@Param("userName") String userName);
    int insertuser(@Param("userName") String userName,@Param("password") String password);

}


2.userdao.xml实现数据库查询

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

<mapper namespace="com.springboot.regist.demo.dao.Userdao">
    <resultMap type="com.springboot.regist.demo.entity.User" id="UserResult">
        <id property="id" column="id" jdbcType="BIGINT"/>
        <result property="userName" column="username" jdbcType="VARCHAR"/>
        <result property="password" column="password" jdbcType="VARCHAR"/>
    </resultMap>


    <select id="selectuserName" resultMap="UserResult">
        select username from test1 where username = #{userName}
    </select>
    <!-- 注册时 -->
    <insert id="insertuser" parameterType="com.springboot.regist.demo.entity.User">
        insert into test1(username,password)
        values(#{userName},#{password})
    </insert>

</mapper>

3.service层

package com.springboot.regist.demo.service;

import com.springboot.regist.demo.entity.User;

public interface UserService {
    User  userregist(String userName,String password);
}

4.seriviceimpl 层实现service层方法

package com.springboot.regist.demo.service.ServiceImpl;

import com.springboot.regist.demo.dao.Userdao;
import com.springboot.regist.demo.entity.User;
import com.springboot.regist.demo.service.UserService;
import com.springboot.regist.demo.utils.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private Userdao userdao;

    @Override
    public User userregist(String userName, String password) {
        //判断用户名是否存在若存在
        if(userdao.selectuserName(userName)!=null){
            User user = new User();
            user.setUserName("用户名已存在");
            return user;
        }
        //如果不存在就插入 并对密码进行加密
        if(userdao.selectuserName(userName) == null){
            User user = new User();
            user.setUserName("用户名不存在");
            int a = userdao.insertuser(userName, MD5Util.MD5Encode(password, "UTF-8"));
            return user;
        }
        return null;
    }
}

5.controller 层


package com.springboot.regist.demo.controller;


import com.springboot.regist.demo.common.Result;
import com.springboot.regist.demo.common.ResultGenerator;
import com.springboot.regist.demo.entity.User;
import com.springboot.regist.demo.service.ServiceImpl.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController


public class UserController {
   @Autowired
   private UserServiceImpl UserService;

   @RequestMapping(value = "/users/regist", method = RequestMethod.POST)
   public Result regist(@RequestBody User user) {

       Result result = ResultGenerator.genFailResult("注册失败");
       if (StringUtils.isEmpty(user.getUserName()) || StringUtils.isEmpty(user.getPassword())) {
           result.setMessage("请填写注册信息!");
           return result;
       }
       User registUser = (User) UserService.userregist(user.getUserName(), user.getPassword());
       if (registUser.getUserName().equals("用户名已存在") ) {
           result = ResultGenerator.genFailUser("用户名已存在");
           return result;
       }
       if (registUser.getUserName().equals("用户名不存在")) {
           result = ResultGenerator.genSuccessResult(registUser);
           return result;
       }
       return result;
   }
}


6.前端html代码及ajax

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/html">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
用户名<input id="userName">
<br>
密码<input id="password">
<br>
<button onclick="login()" >注册</button>
<script type="text/javascript" src="jquery.min.js"></script>
<script>
    function login() {
        var userName = $("#userName").val();
        var password = $("#password").val();
        var data = {"userName":userName,"password":password}
        $.ajax({
            type: "POST",
            dataType: "json",
            url: "users/regist",
            contentType: "application/json; charset=utf-8",
            data:JSON.stringify(data),
            success: function (result) {
                if (result.resultCode == 200) {
                    alert("注册成功")
                }
                ;
                if (result.resultCode == 500) {
                    alert("注册失败!请检查账号和密码!");
                    return;
                }
                if(result.resultCode == 201){
                    alert("注册失败,用户名已存在!")
                    return;
                }
            },
            error: function () {
                alert("接口异常,请联系管理员!");
                return;
            }
        });
    }
</script>
</body>

</html>


7.工具包填写

constants(异常数据)

package com.springboot.regist.demo.common;

/**
 *
 */
public class Constants {

    public static final int RESULT_CODE_SUCCESS = 200;  // 成功处理请求
    public static final int RESULT_CODE_BAD_REQUEST = 412;  // 请求错误
    public static final int RESULT_CODE_NOT_LOGIN = 402;  // 未登录
    public static final int RESULT_CODE_PARAM_ERROR = 406;  // 传参错误
    public static final int RESULT_CODE_SERVER_ERROR = 500;  // 服务器错误
    public static final int UserExists = 201;//用户名已存在错误
}

Result(结果)

package com.springboot.regist.demo.common;

import java.io.Serializable;

/**
 *
 */
public class Result<T> implements Serializable {
    private static final long serialVersionUID = 1L;
    private int resultCode;
    private String message;
    private T data;

    public Result() {
    }

    public Result(int resultCode, String message) {
        this.resultCode = resultCode;
        this.message = message;
    }

    public int getResultCode() {
        return resultCode;
    }

    public void setResultCode(int resultCode) {
        this.resultCode = resultCode;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

    public Result failure(String code) {
        return new Result(500, "服务错误");
    }

    public Result userexist(String code) {
        return new Result(201, "用户名已存在");
    }

    @Override
    public String toString() {
        return "Result{" +
                "resultCode=" + resultCode +
                ", message='" + message + '\'' +
                ", data=" + data +
                '}';
    }
}

Resultgenerator(结果生成器)

package com.springboot.regist.demo.common;

import org.springframework.util.StringUtils;

/**
 *
 */
public class ResultGenerator {
    private static final String DEFAULT_SUCCESS_MESSAGE = "SUCCESS";
    private static final String DEFAULT_FAIL_MESSAGE = "FAIL";

    public static Result genSuccessResult() {
        Result result = new Result();
        result.setResultCode(Constants.RESULT_CODE_SUCCESS);
        result.setMessage(DEFAULT_SUCCESS_MESSAGE);
        return result;
    }

    public static Result genSuccessResult(String message) {
        Result result = new Result();
        result.setResultCode(Constants.RESULT_CODE_SUCCESS);
        result.setMessage(message);
        return result;
    }

    public static Result genSuccessResult(Object data) {
        Result result = new Result();
        result.setResultCode(Constants.RESULT_CODE_SUCCESS);
        result.setMessage(DEFAULT_SUCCESS_MESSAGE);
        result.setData(data);
        return result;
    }

    public static Result genFailResult(String message) {
        Result result = new Result();
        result.setResultCode(Constants.RESULT_CODE_SERVER_ERROR);
        if (StringUtils.isEmpty(message)) {
            result.setMessage(DEFAULT_FAIL_MESSAGE);
        } else {
            result.setMessage(message);
        }
        return result;
    }

    public static Result genNullResult(String message) {
        Result result = new Result();
        result.setResultCode(Constants.RESULT_CODE_BAD_REQUEST);
        result.setMessage(message);
        return result;
    }

    public static Result genErrorResult(int code, String message) {
        Result result = new Result();
        result.setResultCode(code);
        result.setMessage(message);
        return result;
    }

    //用户名已存在错误
    public static Result genFailUser(String message) {
        Result result = new Result();
        result.setResultCode(201);
        result.setMessage(message);
        return result;
    }
}


密码加密工具MD5

package com.springboot.regist.demo.utils;

import java.security.MessageDigest;

/**
 *
 */
public class MD5Util {

    private static String byteArrayToHexString(byte b[]) {
        StringBuffer resultSb = new StringBuffer();
        for (int i = 0; i < b.length; i++) {
            resultSb.append(byteToHexString(b[i]));
        }

        return resultSb.toString();
    }

    private static String byteToHexString(byte b) {
        int n = b;
        if (n < 0) {
            n += 256;
        }
        int d1 = n / 16;
        int d2 = n % 16;
        return hexDigits[d1] + hexDigits[d2];
    }

    public static String MD5Encode(String origin, String charsetname) {
        String resultString = null;
        try {
            resultString = new String(origin);
            MessageDigest md = MessageDigest.getInstance("MD5");
            if (charsetname == null || "".equals(charsetname)) {
                resultString = byteArrayToHexString(md.digest(resultString
                        .getBytes()));
            } else {
                resultString = byteArrayToHexString(md.digest(resultString
                        .getBytes(charsetname)));
            }
        } catch (Exception exception) {
        }
        return resultString;
    }

    private static final String hexDigits[] = {"0", "1", "2", "3", "4", "5",
            "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};
}


效果图

在这里插入图片描述

在这里插入图片描述

  • 6
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 16
    评论
评论 16
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值