SpringBoot实现登陆注册功能【Demo】

文末有下载连接

本文使用springboot+mybatis注解方式,完成简单的注册和登陆功能。且先后端分离,向前端返回json字符串。html

最终效果以下:前端

注册:java

        若是用户名重复返回json串    {"msg":"用户名已存在","success":false,"detail":null}mysql

        若是正常{"msg":"注册成功","success":true,"detail":{"id":9,"username":"test","password":"1"}}git

登陆用以前注册的帐户登陆github

        若是正常{"msg":"登陆成功","success":true,"detail":{"id":1,"username":"user1","password":"a"}}web

 

步骤:-----------------------------------------------------------------------------------------------------------------spring

1. 创建javabean和表结构对应

//用户信息
public class User {
    private Long id;
    private String username;
    private String password;
    //... getter and setter
}
//sql
CREATE TABLE `user` (
  `id` bigint(32) NOT NULL AUTO_INCREMENT,
  `username` varchar(255) DEFAULT NULL,
  `password` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

2. 建立maven工程, 并添加spring-boot及相关依赖

<properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.10.RELEASE</version>
    </parent>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--mybatis-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.1</version>
        </dependency>
        <!--整合mysql-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <!--json @responseBody/@requestBody-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.54</version>
        </dependency>
    </dependencies>

3. 配置文件

 总体文件结构sql

在resource下建立application.yml, 内容:json

server:
  port: 9090
spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/login?useUnicode=true&characterEncoding=utf-8&useSSL=false
    username: root
    password: 123456
  resources:
    static-locations: classpath:/templates  #访问静态页面

4. 页面

        注册页面: regist.html

<head>
    <meta charset="UTF-8">
    <title>用户注册</title>
</head>
<body>
    <form action="/user/regist" method="post">
        用户名:<input name="username" type="text"/><br>
        密码:<input name="password" type="password"> <br>
        <input type="submit" value="注册">
    </form>
</body>

        登陆页面 login.html

<head>
    <meta charset="UTF-8">
    <title>用户登陆</title>
</head>
<body>
    <form action="/user/login" method="post">
        用户名:<input name="username" type="text"/><br>
        密码:<input name="password" type="password"> <br>
        <input type="submit" value="登陆">
    </form>
</body>

5. 后端代码

    (1). 定义向前端返回的json

/**
 * 向前端返回信息封装
 * @param <T> 可变类型
 */
public class Result<T> {
    //返回信息
    private String msg;
    //数据是否正常请求
    private boolean success;
    //具体返回的数据
    private T detail;
    //... getter and setter
}

    (2). 在外层包(全部类和接口所在包的外层)建立springBoot启动入口

/**
 * @SpringBootApplication至关于3个注解
 * 1. @Configuration  定义一个配置类
 * 2. @EnableAutoConfiguration spring boot自动根据jar包的依赖来自动配置项目
 * 3. @ComponentScan  spring自动扫描类上的注解, 并注入spring容器
 */
@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class,args);
    }
}

    (3). controller

@RestController    //至关于@Controller+@RequestBody
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;
    /**
     * 注册
     * @param user 参数封装
     * @return Result
     */
    @PostMapping(value = "/regist")
    public Result regist(User user){
        return userService.regist(user);
    }
    /**
     * 登陆
     * @param user 参数封装
     * @return Result
     */
    @PostMapping(value = "/login")
    public Result login(User user){
        return userService.login(user);
    }
}

    (4). service

@Service
@Transactional(rollbackFor = RuntimeException.class)
public class UserService {

    @Autowired
    private UserMapper userMapper;
    /**
     * 注册
     * @param user 参数封装
     * @return Result
     */
    public Result regist(User user) {
        Result result = new Result();
        result.setSuccess(false);
        result.setDetail(null);
        try {
            User existUser = userMapper.findUserByName(user.getUsername());
            if(existUser != null){
                //若是用户名已存在
                result.setMsg("用户名已存在");

            }else{
                userMapper.regist(user);
                //System.out.println(user.getId());
                result.setMsg("注册成功");
                result.setSuccess(true);
                result.setDetail(user);
            }
        } catch (Exception e) {
            result.setMsg(e.getMessage());
            e.printStackTrace();
        }
        return result;
    }
    /**
     * 登陆
     * @param user 用户名和密码
     * @return Result
     */
    public Result login(User user) {
        Result result = new Result();
        result.setSuccess(false);
        result.setDetail(null);
        try {
            Long userId= userMapper.login(user);
            if(userId == null){
                result.setMsg("用户名或密码错误");
            }else{
                result.setMsg("登陆成功");
                result.setSuccess(true);
                user.setId(userId);
                result.setDetail(user);
            }
        } catch (Exception e) {
            result.setMsg(e.getMessage());
            e.printStackTrace();
        }
        return result;
    }
}

    (5). mapper

/**
 * mapper的具体表达式
 */
@Mapper //标记mapper文件位置,不然在Application.class启动类上配置mapper包扫描
@Repository
public interface UserMapper {

    /**
     * 查询用户名是否存在,若存在,不容许注册
     * 注解@Param(value) 若value与可变参数相同,注解可省略
     * 注解@Results  列名和字段名相同,注解可省略
     * @param username
     * @return
     */
    @Select(value = "select u.username,u.password from user u where u.username=#{username}")
    @Results
            ({@Result(property = "username",column = "username"),
              @Result(property = "password",column = "password")})
    User findUserByName(@Param("username") String username);
    
    /**
     * 注册  插入一条user记录
     * @param user
     * @return
     */
    @Insert("insert into user values(#{id},#{username},#{password})")
    //加入该注解能够保存对象后,查看对象插入id
    @Options(useGeneratedKeys = true,keyProperty = "id",keyColumn = "id")
    void regist(User user);
    
    /**
     * 登陆
     * @param user
     * @return
     */
    @Select("select u.id from user u where u.username = #{username} and password = #{password}")
    Long login(User user);
}

6. 效果

注册:

        若是用户名重复返回json串    {"msg":"用户名已存在","success":false,"detail":null}

        若是正常{"msg":"注册成功","success":true,"detail":{"id":9,"username":"test","password":"1"}}

登陆用以前注册的帐户登陆

        若是正常{"msg":"登陆成功","success":true,"detail":{"id":1,"username":"user1","password":"a"}}

7. 下载连接

github连接:https://github.com/laoyog/springboot-login

CSDN连接:https://download.csdn.net/download/bytearr/11136431