文末有下载链接
本文使用springboot+mybatis注解方式,完成简单的注册和登录功能。且前后端分离,向前端返回json字符串。
最终效果如下:
注册:
如果用户名重复:返回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”}}
步骤:-----------------------------------------------------------------------------------------------------------------
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. 配置文件
整体文件结构
在resource下创建application.yml, 内容:
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”}}