在数据库中建立t_user表
在idea中建立jianyue-api项目
- 添加pom依赖
<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>
- 配置文件
## 数据源配置
spring.datasource.url=jdbc:mysql://localhost:3306/db_jianyue?useUnicode=true&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
#指定实体类映射的包
mybatis.type-aliases-package=com.spring.jianyueapi.entity
#swagger配置
swagger.enabled=true
swagger.title=jianyue api project
swagger.description=Starter for swagger 2.x
swagger.license=Apache License, Version 2.0
swagger.licenseUrl=https://www.apache.org/licenses/LICENSE-2.0.html
swagger.termsOfServiceUrl=https://github.com/dyc87112/spring-boot-starter-swagger
swagger.contact.name=wjl
swagger.contact.url=https://www.jianshu.com/u/a32873d23481
swagger.contact.email=1433686098@qq.com
swagger.base-package=com.spring.jianyueapi.controller
swagger.base-path=/**
swagger.exclude-path=/error, /ops/**
- User.java实体类
@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;
}
- UserDTO数据传输对象类
@Data
public class UserDTO {
private String mobile;
private String password;
}
-
Util工具包
public class MsgConst {
public static final String SUCCESS="请求成功";
public static final String USER_ID_NOT_FOUND="id不存在";
public static final String USER_MOBILE_NOT_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 = "验证码错误";
}
@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;
}
}
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;
}
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();
}
public static String getVerifyCode(){
Random random=new Random();
StringBuilder stringBuilder=new StringBuilder();
for(int i=0;i<6;i++){
stringBuilder.append(String.valueOf(random.nextInt(10)));
}
return stringBuilder.toString();
}
}
- UserMapper接口
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 = "regtime",column = "regtime"),
@Result(property = "token",column = "token")
})
@Select("SELECT * FROM t_user WHERE mobile = #{mobile} ")
User getUserByMobile(String mobile);
@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 = "regtime",column = "regtime"),
@Result(property = "token",column = "token")
})
@Select("SELECT * FROM t_user WHERE id = #{id} ")
User getUserById(Integer id);
@Update("UPDATE t_user SET password= #{password},nickname= #{nickname},avatar= #{avatar},status= #{status},token= #{token} WHERE id= #{id} ")
void update(User user);
@Insert("INSERT INTO t_user(mobile,password,nickname,avatar,regtime,status) VALUES(#{mobile},#{password},#{nickname},#{avatar},#{regtime},#{status})")
void insert(User user);
}
- UserService接口
public interface UserService {
User getUserByMobile(String mobile);
int signIn(UserDTO userDTO);
User getUserById(Integer id);
void update(User user);
/**
* 用户注册方法
* @param userDTO
* @return int
*/
void signUp(UserDTO userDTO);
}
- Service实现类
@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;
}
}
@Override
public User getUserById(Integer id) {
return userMapper.getUserById(id);
}
@Override
public void update(User user) {
userMapper.update(user);
}
@Override
public void signUp(UserDTO userDTO) {
User user1=new User();
user1.setMobile(userDTO.getMobile());
user1.setPassword(StringUtil.getBase64Encoder(userDTO.getPassword()));
user1.setNickname("新用户");
user1.setAvatar("http://ppeto2k90.bkt.clouddn.com/avatar/default.png");
user1.setRegtime(new Date());
user1.setStatus((short)1);
userMapper.insert(user1);
}
}
- 单元测试类
package com.spring.jianyueapi.service.impl;
import com.spring.jianyueapi.entity.User;
import com.spring.jianyueapi.entity.dto.UserDTO;
import com.spring.jianyueapi.service.UserService;
import com.spring.jianyueapi.util.StatusConst;
import com.spring.jianyueapi.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 javax.swing.*;
import static org.junit.Assert.*;
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserServiceImplTest {
@Resource
private UserService userService;
@Test
public void getUserByMobile() {
User user=userService.getUserByMobile("18852009609");
System.out.println(user);
}
@Test
public void getUSerById(){
User user=userService.getUserById(1);
System.out.println(user);
}
@Test
public void signIn() {
UserDTO loginUser=new UserDTO();
loginUser.setMobile("18852009609");
String base64pass= StringUtil.getBase64Encoder("1234");
loginUser.setPassword(base64pass);
int status=userService.signIn(loginUser);
assertEquals(StatusConst.SUCCESS,status);
}
@Test
public void signUp() {
UserDTO userDTO = new UserDTO();
userDTO.setMobile("139****1489");
userDTO.setPassword("1112");
userService.signUp(userDTO);
}
}
- UserController
@RestController
@RequestMapping(value = "/api/user")
public class UserController {
@Resource
private UserService userService;
@Resource
private RedisService redisService;
@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_NOT_FOUND);
}else{
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);
}
}
}
- config下跨域配置
@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");
}
};
}
}
- 启动主类
@SpringBootApplication
@MapperScan("com.spring.jianyueapi.mapper")
@EnableSwagger2Doc
public class JianyueApiApplication {
public static void main(String[] args) {
SpringApplication.run(JianyueApiApplication.class, args);
}
}
- swagger测试(显示200通过)
前端
- signin.vue
<template>
<view class="uni-flex uni-column container">
<view v-if="codeshow" style="width: 100%;">
<view class="psd-register">账号密码登录</view>
<input class="uni-input" type="number" placeholder="请输入手机号或邮箱" v-model="userDTO.mobile" required="required" />
<input class="uni-input" password type="text" placeholder="请输入密码" v-model="userDTO.password" required="required" />
<button @tap="signIn(userDTO)" v-if="userDTO.password.length>=4" class="login">登录</button>
<button v-if="userDTO.password.length<4" class="login-false">登录</button>
<view class="login-method">
<view class="psd-login" @tap="changePages1()">手机验证码登录</view>
<view class="problem">登录遇到问题?</view>
</view>
<view class="other"><text class="inline"></text><text class="other-means">社交账号直接登录</text><text class="inline1"></text></view>
<view class="means1">
<view class="means" v-for="(mean,index) in means" :key="index">
<image :src="mean.img" class="img"></image>
<view class="name">{{mean.name}}</view>
</view>
</view>
<view class="footer-info">登录代表已经同意<navigator class="nav">用户协议</navigator>和<navigator class="nav">隐私政策</navigator>
</view>
</view>
<view v-if="psdshow">
<view class="psd-register">手机验证码登录</view>
<input class="uni-input" type="number" placeholder="请输入手机号" v-model="mobile1" required="required" />
<view class="codeverify">
<input class="uni-input" style="flex: 1 1 55%;" password type="text" placeholder="请输入验证码" v-model="verifycode"
required="required" />
<button class="receive" v-show="mobile1.length>0">获取验证码</button>
<button class="receive" disabled="true" v-show="mobile1.length==0">获取验证码</button>
</view>
<button v-if="verifycode.length>=6" class="login" style="position: relative;top: 50upx;">登录</button>
<button v-if="verifycode.length<6" class="login-false" style="position: relative;top: 50upx;">登录</button>
<view class="login-method" style="top: 90upx;">
<view class="psd-login" @tap="changePages()">账号密码登录</view>
<view class="problem">登录遇到问题?</view>
</view>
<view class="other"><text class="inline"></text><text class="other-means">社交账号直接登录</text><text class="inline1"></text></view>
<view class="means1">
<view class="means" v-for="(mean,index) in means" :key="index">
<image :src="mean.img" class="img"></image>
<view class="name">{{mean.name}}</view>
</view>
</view>
<view class="footer-info1">未注册的手机号登录时将自动注册,且<navigator style="display: flex;justify-content: center;">代表已经同意<navigator
class="nav">用户协议</navigator>和<navigator class="nav">隐私政策</navigator>
</navigator>
</view>
</view>
</view>
</template>
<script>
export default {
data() {
return {
userDTO: {
mobile: '',
password: '',
},
verifycode: '',
mobile1:'',
means: [{
img: '../../static/wx.png',
name: '微信'
},
{
img: '../../static/qq.png',
name: 'QQ'
},
{
img: '../../static/weibo.png',
name: '微博'
},
{
img: '../../static/more.png',
name: '其他'
}
],
codeshow: true,
psdshow: false
};
},
onLoad() {
uni.setNavigationBarTitle({
title: '登录'
});
},
methods: {
changePages: function() {
this.codeshow = true;
this.psdshow = false;
},
changePages1: function() {
this.psdshow = true;
this.codeshow = false;
},
signIn: function(userDTO) {
var _this = this;
// console.log(userDTO.mobile + ',' + userDTO.password);
uni.request({
url: 'http://localhost:8080/api/user/sign_in',
method: 'POST',
data: {
mobile: userDTO.mobile,
password: userDTO.password
},
header: {
'content-type': 'application/json'
},
success: res => {
// console.log(res.data.data);
if (res.data.code == 0) {
//将用户数据记录在本地存储
uni.setStorageSync('login_key', {
userId: res.data.data.id,
nickname: res.data.data.nickname,
avatar: res.data.data.avatar,
token: res.data.data.token,
login: true
});
uni.showToast({
title: '登录成功'
});
uni.navigateBack();
}
//登录失败,弹出各种原因
else {
uni.showModal({
title: '提示',
content: res.data.msg
});
}
}
});
}
}
};
</script>
- setting.vue
<template>
<view class="content">
<text class="info">消息推送</text>
<view class="block1">
<view class="item" v-for="(item,index) in item1" :key="index">
<view class="name">{{item.name}}</view>
<view class="status">{{item.status}}</view>
</view>
</view>
<text class="info">通用设置</text>
<view class="block1">
<view class="item">
<navigator url="../user_info/user_info" class="name">编辑个人资料</navigator>
</view>
<view class="item" v-for="(item,index) in item2" :key="index">
<view class="name">{{item.name}}</view>
<view class="status">{{item.status}}</view>
</view>
<view class="item" style="border: none;">
<view class="name">移动网络下加载图片</view>
<view><switch checked="checked" color="#EA6F5A"/></view>
</view>
</view>
<text class="info">其他</text>
<view class="block1">
<view class="item" v-for="(other,index) in others" :key="index">
<view class="name">{{other.name}}</view>
<view class="status">{{other.status}}</view>
</view>
</view>
<button class="out" @tap="logout()">退出当前帐号</button>
</view>
</template>
<script>
export default {
data() {
return {
item1:[{
name:'文章更新推送',
status:'已开启'
},
{
name:'新消息推送'
}
],
item2:[
{
name:'默认编辑器',
status:'富文本'
},
{
name:'添加写文章到桌面'
},
{
name:'赞赏设置'
},
{
name:'字号设置'
},
{
name:'黑名单设置'
},
],
others:[{
name:'回收站'
},
{
name:'简阅&Yhouse 品质生活卡'
},
{
name:'FDAA授权'
},
{
name:'清除缓存',
status:'当前缓存18.2Mb'
},
{
name:'版本更新'
},
{
name:'分享简阅'
},
{
name:'给简阅评分'
},
{
name:'关于我们'
}
]
};
},
onLoad() {
uni.setNavigationBarTitle({
title: '设置'
});
},
methods: {
logout: function() {
console.log('log out');
uni.removeStorageSync('login_key');
uni.showToast({
title: '已经退出当前账号'
});
uni.navigateBack();
}
}
};
</script>