spring boot+mybatis 实现用户注册接口

上一次写了怎么用IDEA建立spring boot项目,接下来从0开始实现添加用户的接口

先来看一下最终的目录结构


目录结构

创建数据库和准备用户表

CREATE TABLE `user` (
  `id` int(8) NOT NULL AUTO_INCREMENT,
  `name` varchar(20) NOT NULL,
  `password` varchar(255) NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `user_name_uindex` (`name`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8mb4;

添加 fastjson 依赖 和 spring boot dev tool 依赖

打开 pom.xml, 在 dependencies 节点下面添加

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.22</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
        </dependency>

编写User.java

目前 User 只有 idnamepassword 三个属性

public class User {
    private Integer id; 
    private String name;
    private String password;

  // 下面是 getter 和 setter 方法。。。
}

注意 id 用 Integer 而不用 int, 因为 int 自动初始化为0,mybatis mapper 文件 就不能使用 <if test="id!=null"> 了,而 Integer 可以为 null

编写 UserApi.java

@RestController
@RequestMapping("/api/user")
public class UserApi {
    private UserService userService;

    @Autowired
    public UserApi(UserService userService) {
        this.userService = userService;
    }

    @PostMapping("")
    public Object add(@RequestBody User user) {
        if (userService.findByName(user.getName()) != null) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("message","用户名已被使用");
            return jsonObject;
        }
        return userService.add(user);
    }
}

api这一层主要是调用service层的方法, 返回JSON数据。我用 @RestController 代替了 @Controller,表示该类里面的方法都是返回 JSON 数据, 而不用再给每个方法添加@ResponseBody注解。add 方法 @PostMapping("") 对应的路由为

POST /api/user

编写 UserService.java

@Service
public class UserService {
    private UserMapper userMapper;

    @Autowired
    public UserService(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    public User add(User user) {
        userMapper.add(user);
        return findById(user.getId());
    }

    public User findById(int id) {
        User user = new User();
        user.setId(id);
        return userMapper.findOne(user);
    }

    public User findByName(String name) {
        User param = new User();
        param.setName(name);
        return userMapper.findOne(param);
    }
}

service这一层处理主要的业务逻辑,比如说添加用户, api层传过来了一个 user对象, 具体怎么添加在这里处理。目前逻辑比较简单,直接调用mapper层的方法,保存到数据库即可。

编写 UserMapper.java

public interface UserMapper {
    int add(User user);
    User findOne(User user);
}

一个添加接口和一个查询接口

编写 UserMapper.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.hpm.blog.mapper.UserMapper">
    <insert id="add" useGeneratedKeys="true" keyProperty="id">
        insert into user(name, password) values (#{name},#{password})
    </insert>

    <select id="findOne" resultType="User">
        select * from user
      <where>
      <!-- 重复说一下,id 不能是 int,int 默认是 0,不可能是 null, 而 Integer 可以是 null-->
          <if test="id!=null">  
              id=#{id}
          </if>
          <if test="name!=null">
              and name=#{name}
          </if>
      </where>
    </select>

</mapper>

insert 标签中的 useGeneratedKeys 作用是获取由数据库生成的id,注意mapper xml文件要和mapper java文件同名, 并且包名一致,不同的是xml文件要放在 resource目录之下。xml文件所在的包是一个多级目录结构,要建完一个目录再建另外一个,不能一下子新建一个名为xxx.yyy.zzz的目录。到这里, 我们的代码基本写完了。

编写Mybatis配置文件

  1. 在 resource目录下面新建一个名为mybatis.xml 的文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <settings>
        <!-- 开启驼峰命名转换 Table(create_time) -> Entity(createTime) -->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
</configuration>
  1. 打开application.yml文件, 添加以下内容
mybatis:
    type-aliases-package: com.hpm.blog.model
    config-location: classpath:mybatis.xml

type-aliases-package, 根据你的包结构修改为User.java文件所在的包

  1. 使spring boot扫描 mapper文件。打开SpringBootBlogApplication.java, 添加mybatis扫描注解,参数为mapper文件所在的包名
@MapperScan("com.hpm.blog.mapper")

SpringBootBlogApplication.java内容最终如下

@SpringBootApplication
@MapperScan("com.hpm.blog.mapper")
public class SpringBootBlogApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringBootBlogApplication.class, args);
    }
}

测试访问接口

代码编写完毕,接下来运行项目,添加一个用户试试。下面使用curl发起一个POST请求。(如果你用的是Windows系统,没有curl这个命令,那么我推荐你安装一个git客户端,用软件带的git bash代替 cmd,将拥有Linux系统下面的包括curl在内的很多有用的命令)。

curl -X POST -H "Content-Type: application/json" -d '{"name": "xiaohong","password": "123456"}' "http://localhost:8080/api/user/"

windows系统下 curl 不能用单引号,要用双引号转义

curl -X POST -H "Content-Type: application/json" -d "{\"name\": \"xiaohong\",\"password\": \"123456\"}" "http://localhost:8080/api/user/"

得到如下输出,添加用户成功。

{"id":10,"name":"xiaohong","password":"123456"}

使用 hash 来保存用户密码

目前为止,数据库中的用户密码还是原文存储的,很不安全,改用 hash 值来存储用户密码。哈希算法很多种,以下使用 SHA-256
打开 UserService.java 文件

  1. 修改 add 方法
    public User add(User user) {
        String passwordHash =  passwordToHash(user.getPassword());
        user.setPassword(passwordHash);
        userMapper.add(user);
        return findById(user.getId());
    }
  1. 添加 passwordToHash 方法
    private String passwordToHash(String password) {
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            digest.update(password.getBytes());
            byte[] src = digest.digest();
            StringBuilder stringBuilder = new StringBuilder();
            // 字节数组转16进制字符串
            // https://my.oschina.net/u/347386/blog/182717
            for (byte aSrc : src) {
                String s = Integer.toHexString(aSrc & 0xFF);
                if (s.length() < 2) {
                    stringBuilder.append('0');
                }
                stringBuilder.append(s);
            }
            return stringBuilder.toString();
        } catch (NoSuchAlgorithmException ignore) {
        }
        return null;
    }

重启服务器,再测试一下

curl -X POST -H "Content-Type: application/json" -d "{\"name\": \"xiaoming\",\"password\": \"123456\"}" "http://localhost:8080/api/user/"

输出:

{"id":11,"name":"xiaoming","password":"8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92"}

好了,密码已经由原文存储变为hash存储了。

查看项目完整代码

项目地址: https://github.com/hyrijk/spring-boot-blog
克隆项目到本地

git clone https://github.com/hyrijk/spring-boot-blog.git

checkout 到当前版本

git checkout 324933e88dbf22368b8cc250c57f895fd836e0d8

完。

参考链接

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,253评论 19 139
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 46,999评论 6 342
  • 1. 简介 1.1 什么是 MyBatis ? MyBatis 是支持定制化 SQL、存储过程以及高级映射的优秀的...
    笨鸟慢飞阅读 5,849评论 0 4
  • 这里首先要说到windows了 ,很尴尬的是我还是用win10的时候偶然发现分屏功能的,现在用了Mac还是很怀念这...
    0ne0ne阅读 650评论 0 1
  • 20171029
    湛蓝语语阅读 128评论 0 0