1.登录功能后端实现
1.1 创建数据库db_jianyue ,创建表t_user
自行添几个数据
1.2 IDEA中新建jianyue-api项目
1.3 添加pom依赖
<?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 http://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.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.soft1721</groupId>
<artifactId>jianyue-api</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>jianyue-api</name>
<description>JianYue API project</description>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.39</version>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.6</version>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.spring4all</groupId>
<artifactId>swagger-spring-boot-starter</artifactId>
<version>1.8.0.RELEASE</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
1.4 application.properties文件
1.5 entity包User.java实体类
package com.soft1721.jianyue.api.entity;
import lombok.Data;
import java.util.Date;
@Data
public class User {
private Integer id;
private String mobile;
private String password;
private String nickname;
private String token;
private Short status;
private Date regtime;
private String avatar;
}
1.6 entity包下dto子包UserDTO.java数据传输对象类
package com.soft1721.jianyue.api.entity.dto;
import lombok.Data;
@Data
public class UserDTO {
private String mobile;
private String password;
}
1.7 until包下几个工具类
![image.png](https://upload-images.jianshu.io/upload_images/16112273-de1916d8ac455c5e.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
- MsgConst
package com.soft1721.jianyue.api.util;
public class MsgConst {
public static final String SUCCESS = "请求成功";
public static final String USER_ID_NO_FOUND = "id不存在";
public static final String USER_MOBILE_NO_FOUND = "手机号不存在";
public static final String PASSWORD_ERROR = "密码错误";
public static final String USER_STATUS_ERROR = "账号异常";
public static final String MOBILE_EXIST = "手机号已被注册";
public static final String VERIFYCODE_ERROR = "验证码错误";
public static final String FOLLOWED = "已关注";
public static final String NO_FOLLOWED = "取消关注";
public static final String LIKE = "已喜欢";
public static final String NO_LIKE = "取消喜欢";
}
- ResponseResult
package com.soft1721.jianyue.api.util;
import lombok.Data;
/**
* 封装统一的响应体
* 调用 ResponseResult.success() 或 ResponseResult.success(Object data),
* 不需要返回数据时调用前者, 需要返回数据时调用后者
*/
@Data
public class ResponseResult {
private int code;
private String msg;
private Object data;
public static ResponseResult error(int code, String msg) {
ResponseResult responseResult = new ResponseResult();
responseResult.setCode(code);
responseResult.setMsg(msg);
return responseResult;
}
public static ResponseResult success() {
ResponseResult responseResult = new ResponseResult();
responseResult.setCode(StatusConst.SUCCESS);
responseResult.setMsg(MsgConst.SUCCESS);
return responseResult;
}
public static ResponseResult success(Object data) {
ResponseResult responseResult = new ResponseResult();
responseResult.setCode(StatusConst.SUCCESS);
responseResult.setMsg(MsgConst.SUCCESS);
responseResult.setData(data);
return responseResult;
}
}
- StausConst
package com.soft1721.jianyue.api.util;
public class StatusConst {
public static final int SUCCESS = 0;
public static final int USER_ID_NOT_FOUND = 1;
public static final int USER_MOBILE_NOT_FOUND = 2;
public static final int PASSWORD_ERROR = 3;
public static final int USER_STATUS_ERROR = 4;
public static final int MOBILE_EXIST = 5;
public static final int VERIFYCODE_ERROR = 6;
}
- StringUtil
package com.soft1721.jianyue.api.util;
import java.io.UnsupportedEncodingException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.Date;
import java.util.UUID;
public class StringUtil {
public static String getDateString(Date date) {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return df.format(date);
}
public static String getBase64Encoder(String srcString) {
String resultStr = "";
try {
resultStr = Base64.getEncoder().encodeToString(srcString.getBytes("utf-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return resultStr;
}
public static String getBase64Decoder(String srcString) {
byte[] bytes = Base64.getDecoder().decode(srcString);
return new String(bytes);
}
public static String getUUIDString() {
return UUID.randomUUID().toString();
}
}
1.8 mapper包UserMapper.java接口
package com.soft1721.jianyue.api.mapper;
import com.soft1721.jianyue.api.entity.User;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
public interface UserMapper {
@Results({
@Result(property = "id", column = "id"),
@Result(property = "mobile", column = "mobile"),
@Result(property = "password", column = "password"),
@Result(property = "nickname", column = "nickname"),
@Result(property = "avatar", column = "avatar"),
@Result(property = "status", column = "status"),
@Result(property = "regtime", column = "regtime"),
@Result(property = "token", column = "token")
})
@Select("SELECT * FROM t_user WHERE mobile = #{mobile} ")
User getUserByMobile(String mobile);
@Update("UPDATE t_user SET password=#{password},nickname=#{nickname},avatar=#{avatar},status=#{status},token=#{token} WHERE id =#{id}")
void update(User user);
}
1.9 service包UserService.java接口
package com.soft1721.jianyue.api.service;
import com.soft1721.jianyue.api.entity.User;
import com.soft1721.jianyue.api.entity.dto.UserDTO;
public interface UserService {
/**
* 根据手机号获取用户信息
*
* @param mobile
* @return
*/
User getUserByMobile(String mobile);
/**
* 登录方法
*
* @param userDTO
* @return boolean
*/
int signIn(UserDTO userDTO);
}
1.10 service下impl子包UserServiceImpl.java实现类
package com.soft1721.jianyue.api.service.impl;
import com.soft1721.jianyue.api.entity.User;
import com.soft1721.jianyue.api.entity.dto.UserDTO;
import com.soft1721.jianyue.api.mapper.UserMapper;
import com.soft1721.jianyue.api.service.UserService;
import com.soft1721.jianyue.api.util.StatusConst;
import com.soft1721.jianyue.api.util.StringUtil;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
@Service
public class UserServiceImpl implements UserService {
@Resource
private UserMapper userMapper;
@Override
public User getUserByMobile(String mobile) {
return userMapper.getUserByMobile(mobile);
}
@Override
public int signIn(UserDTO userDTO) {
User user = userMapper.getUserByMobile(userDTO.getMobile());
//手机号存在
if (user != null) {
//密码正确
if (userDTO.getPassword().equals(user.getPassword())) {
//账号正常
if (user.getStatus() == 1) {
user.setToken(StringUtil.getUUIDString());
userMapper.update(user);
return StatusConst.SUCCESS;
} else { //账号异常
return StatusConst.USER_STATUS_ERROR;
}
} else { //密码错误
return StatusConst.PASSWORD_ERROR;
}
} else { //手机号不存在
return StatusConst.USER_MOBILE_NOT_FOUND;
}
}
}
1.11 单元测试类
package com.soft1721.jianyue.api.service.impl;
import com.soft1721.jianyue.api.entity.User;
import com.soft1721.jianyue.api.entity.dto.UserDTO;
import com.soft1721.jianyue.api.service.UserService;
import com.soft1721.jianyue.api.util.StatusConst;
import com.soft1721.jianyue.api.util.StringUtil;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import javax.annotation.Resource;
import static org.junit.Assert.assertEquals;
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserServiceImplTest {
@Resource
private UserService userService;
@Test
public void getUserByMobile() {
User user = userService.getUserByMobile("13988889999");
System.out.println(user);
}
@Test
public void signIn() {
UserDTO loginUser = new UserDTO();
loginUser.setMobile("13951905171");
String base64Pass = StringUtil.getBase64Encoder("111");
loginUser.setPassword(base64Pass);
int status = userService.signIn(loginUser);
assertEquals(StatusConst.SUCCESS, status);
}
}
1.12 controller包下UserController
package com.soft1721.jianyue.api.controller;
import com.soft1721.jianyue.api.entity.User;
import com.soft1721.jianyue.api.entity.dto.UserDTO;
import com.soft1721.jianyue.api.service.UserService;
import com.soft1721.jianyue.api.util.ResponseResult;
import com.soft1721.jianyue.api.util.MsgConst;
import com.soft1721.jianyue.api.util.StatusConst;
import com.soft1721.jianyue.api.util.StringUtil;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
@RestController
@RequestMapping(value = "/api/user")
public class UserController {
@Resource
private UserService userService;
@PostMapping(value = "/sign_in")
public ResponseResult signIn(@RequestBody UserDTO userDTO) {
System.out.println(userDTO);
User user = userService.getUserByMobile(userDTO.getMobile());
if (user == null) {
return ResponseResult.error(StatusConst.USER_MOBILE_NOT_FOUND, MsgConst.USER_MOBILE_NO_FOUND);
} else {
//手机号存在,将明文密码转成Base64密文后进行登录
userDTO.setPassword(StringUtil.getBase64Encoder(userDTO.getPassword()));
int status = userService.signIn(userDTO);
if (status == StatusConst.SUCCESS) {
return ResponseResult.success(user);
} else if (status == StatusConst.PASSWORD_ERROR) {
return ResponseResult.error(status, MsgConst.PASSWORD_ERROR);
} else {
return ResponseResult.error(status, MsgConst.USER_STATUS_ERROR);
}
}
}
}
1.13 config包下跨域配置类
package com.soft1721.jianyue.api.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
public class WebMvcConfigurer extends WebMvcConfigurerAdapter {
//跨域配置
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
//重写父类提供的跨域请求处理的接口
public void addCorsMappings(CorsRegistry registry) {
//添加映射路径
registry.addMapping("/**")
//放行哪些原始域
.allowedOrigins("*")
//是否发送Cookie信息
.allowCredentials(true)
//放行哪些原始域(请求方式)
.allowedMethods("GET", "POST", "PUT", "DELETE")
//放行哪些原始域(头部信息)
.allowedHeaders("*")
//暴露哪些头部信息(因为跨域访问默认不能获取全部头部信息)
.exposedHeaders("Header1", "Header2");
}
}
}
1.14 启动主类
package com.soft1721.jianyue.api;
import com.spring4all.swagger.EnableSwagger2Doc;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("com.soft1721.jianyue.api.mapper")
@EnableSwagger2Doc
public class JianyueApiApplication {
public static void main(String[] args) {
SpringApplication.run(JianyueApiApplication.class, args);
}
}