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

系列文章目录

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

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

文章目录

  • 系列文章目录
  • 前言
  • 一、工程图片
  • 二、使用步骤
    • 1.新建springboot项目
      • 1.1 修改pom.xml文件
      • 1.2修改application.properties文件
    • 2.新建数据库
  • 3.实体层填写
  • 4.三层架构
    • 1.dao层
    • 2.userdao.xml实现数据库查询
    • 3.service层
      • 4.seriviceimpl 层实现service层方法
    • 5.controller 层
  • 6.前端html代码及ajax
  • 7.工具包填写
    • constants(异常数据)
    • Result(结果)
    • Resultgenerator(结果生成器)
    • 密码加密工具MD5
  • 效果图


前言

初学springboot做简单的登录注册


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

一、工程图片

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

二、使用步骤

1.新建springboot项目

1.1 修改pom.xml文件



<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.1.0.RELEASEversion>
        <relativePath/> 
    parent>
    <groupId>com.examplegroupId>
    <artifactId>demoartifactId>
    <version>0.0.1-SNAPSHOTversion>
    <name>demoname>
    <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.springframework.bootgroupId>
            <artifactId>spring-boot-starter-jdbcartifactId>
        dependency>

        <dependency>
            <groupId>org.mybatis.spring.bootgroupId>
            <artifactId>mybatis-spring-boot-starterartifactId>
            <version>1.3.2version>
        dependency>

        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
        dependency>

        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
        dependency>
        <dependency>
            <groupId>org.junit.jupitergroupId>
            <artifactId>junit-jupiterartifactId>
            <version>5.5.0version>
            <scope>testscope>
        dependency>
    dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-maven-pluginartifactId>
            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实现数据库查询




<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


<html lang="en" xmlns="http://www.w3.org/1999/html">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
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"};
}


效果图

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

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

你可能感兴趣的:(springboot,java,spring)