注册登录及全局异常处理
中国加油,武汉加油!
篇幅较长,请配合目录观看
项目准备
1. 注册页面数据获取
1.1 weixin新建weixin-entity(module-maven)
1.1.1 导包
<dependencies>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.8</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>2.3</version>
</dependency>
</dependencies>
1.1.2 编写User类
package com.wpj.entity;
import com.baomidou.mybatisplus.annotations.TableField;
import com.baomidou.mybatisplus.annotations.TableId;
import com.baomidou.mybatisplus.annotations.TableName;
import com.baomidou.mybatisplus.enums.IdType;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
import java.util.Date;
@Data
@AllArgsConstructor
@NoArgsConstructor
@TableName("t_user")
public class User implements Serializable{
@TableId(type = IdType.AUTO)
private Integer id;
private String username;
private String password;
private String phone;
private String nickname;
@TableField(value = "create_time")
private Date createTime;
@TableField(value = "max_head")
private String maxHead;
@TableField(value = "min_head")
private String minHead;
}
1.2 weixin新建weixin-common(module-maven)
1.2.1 导包
<dependencies>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.8</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.1.11.RELEASE</version>
</dependency>
</dependencies>
1.2.2 编写ResultEntity
package com.qf.entity.base;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class ResultEntity {
private static final String SUCCESS = "ok";
private static final String ERROR = "error";
private static final String NO_MSG = null;
private String code; // 提示信息码
private String msg; // 提示信息
private Object data;
/**
* 成功没有数据
* @return
*/
public static ResultEntity success(){
return new ResultEntity(SUCCESS,NO_MSG,null);
}
/**
* 成功有数据
* @param data
* @return
*/
public static ResultEntity success(Object data){
return new ResultEntity(SUCCESS,NO_MSG,data);
}
/**
* 错误有信息
* @param msg
* @return
*/
public static ResultEntity error(String msg){
return new ResultEntity(ERROR,msg,null);
}
}
1.3 weixin新建weixin-service-api(module-maven)
1.3.1 导包
<dependency>
<groupId>com.wpj</groupId>
<artifactId>base</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.wpj</groupId>
<artifactId>wx-entity</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
1.3.2 编写Service接口
package com.wpj.service;
import com.wpj.entity.User;
public interface IUserService extends IBaseService<User> {
int register(User user);
}
1.4 weixin-web新建项目weixin-user(module-springboot)
1.4.1 导包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>com.wpj</groupId>
<artifactId>wx-common</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.wpj</groupId>
<artifactId>wx-entity</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.wpj</groupId>
<artifactId>weixin-service-api</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
1.4.2 编写Mapper接口
package com.wpj.mapper;
import com.baomidou.mybatisplus.mapper.BaseMapper;
import com.wpj.entity.User;
public interface IUserMapper extends BaseMapper<User> {
}
1.4.3 编写ServiceImpl实现类
package com.wpj.service.impl;
import com.baomidou.mybatisplus.mapper.BaseMapper;
import com.wpj.entity.User;
import com.wpj.mapper.IUserMapper;
import com.wpj.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserServiceImpl extends BaseServiceImpl<User> implements IUserService {
@Autowired
private IUserMapper userMapper;
@Override
public BaseMapper<User> getMapper() {
return userMapper;
}
@Override
public int register(User user) {
// 判断用户是否存在
if (isExits("username", user.getUsername())) {
return 1; // 用户名存在
} else if(isExits("phone", user.getPhone())) {
return 2; // 手机号码存在
} else {
userMapper.insert(user);
return 3;
}
}
/**
* 根据属性判断用户是否存在
* @param column 列名称
* @param value 值
* @return 返回true则存在
*/
public Boolean isExits(String column, String value){
EntityWrapper wrapper = new EntityWrapper();
wrapper.eq(column, value);
return userMapper.selectCount(wrapper) != 0;
}
}
1.4.4 编写bootstrap.yml
spring:
cloud:
config:
uri: http://localhost:8081
name: application
profile: user
1.4.5 weixin-config-server的config目录下编写application-user.yml
server:
port: 8082
spring:
application:
name: wx-user
datasource:
driver-class-name: com.mysql.jdbc.Driver
username: root
password: 123456
url: jdbc:mysql://localhost:3306/nz1904-springcloud-weixin
mybatis-plus:
type-aliases-package: com.wpj.entity
eureka:
client:
register-with-eureka: false
fetch-registry: false
service-url:
defaultZone: http://localhost:8080/eureka
1.4.6 编写Controller
package com.wpj.controller;
import com.wpj.entity.User;
import com.wpj.entity.base.ResultEntity;
import com.wpj.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private IUserService userService;
@RequestMapping("/register")
public ResultEntity register(User user){
int insert = userService.register(user);
if (insert == 1) {
return ResultEntity.error("用户名存在");
} else if (insert == 2) {
return ResultEntity.error("手机号码存在");
}
return ResultEntity.success();
}
}
1.4.7 修改稿程序入口
package com.wpj;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
@EnableEurekaClient
@SpringBootApplication(scanBasePackages = "com.wpj")
@MapperScan(basePackages = "com.wpj.mapper")
public class WeixinUserApplication {
public static void main(String[] args) {
SpringApplication.run(WeixinUserApplication.class, args);
}
}
1.4.8 启动三个程序入口使用postman测试
2. 搭建路由网关
2.1 weixin-web新建weixin-getway(module-springboot)
2.2 导包
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-client</artifactId>
</dependency>
2.3 编写bootstrap.yml
spring:
cloud:
config:
uri: http://localhost:8081
name: application
profile: gateway
2.4 weixin-config-server的config目录下编写application-gateway.yml
server:
port: 8888
spring:
cloud:
gateway:
routes:
- id: wx-user
uri: lb://WX-USER
predicates:
- Path=/user/**
eureka:
client:
service-url:
defaultZone: http://localhost:8080/eureka
2.5 重启Config的程序入口,启动gateway程序入口使用postman测试
3. 抽取Eureka的配置
3.1 weixin-config-server的config目录下编写application-euclient.yml
eureka:
client:
service-url:
defaultZone: http://localhost:8080/eureka
3.2 删除application-gateway.yml和application-user.yml的eureka配置
3.2 weixin-user和weixin-gateway配置euclient
spring:
cloud:
config:
uri: http://localhost:8081
name: application
profile: user,euclient
3.4 重启4个程序入口使用postman测试
4. 注册实现
4.1 前端项目编写weixin-utils.js
window.util={
ajax:function(param){
mui.ajax(param.url,{
data:param.data,
dataType:'json',//服务器返回json格式数据
type:'post',//HTTP请求类型
success:function(data){
param.success(data);
},
error:function(xhr,type,errorThrown){
//异常处理;
plus.nativeUI.toast("服务端出现异常。");
}
});
},
setUser:function(user){
plus.storage.setItem("login_user",JSON.stringify(user)); // 设置value的是字符串
},
getUser:function(){
return JSON.parse(plus.storage.getItem("login_user")); // 方便后期操作 取出时转成JSON对象
}
}
// cmd --> ipconfig --> IPv4地址 192.168.xx.xx
window.ip={
serverip:"http://192.168.xx.xx:8888/"
}
window.url={
register_url:ip.serverip + "user/register",
login_url:ip.serverip+"user/login"
}
4.2 register页面编写ajax请求注册
<script src="js/weixin-utils.js"></script>
// cmd --> ipconfig --> IPv4地址 192.168.91.1
util.ajax({
url:url.register_url,
data:param,
success:function(data){
//服务器返回响应,根据响应结果,分析是否登录成功;
if(data.code == "ok"){
plus.nativeUI.toast("注册成功。");
// 注册成功,跳转到登录页面
plus.webview.open("login.html","login.html");
plus.webview.currentWebview().close();
} else {
plus.nativeUI.toast(data.msg);
}
}
});
4.3 注册测试
5. 登录实现
5.1 Service接口定义方法
User getUserByUsername(String username);
5.2 ServiceImpl重写方法
@Override
public User getUserByUsername(String username) {
User user = new User();
user.setUsername(username);
return userMapper.selectOne(user);
}
5.3 Controller编写方法
@RequestMapping("/login")
public ResultEntity login(String username, String password){
User user = userService.getUserByUsername(username);
if(user != null && user.getPassword().equals(password)) {
user.setPassword(null); // 密码不能写到手机里
return ResultEntity.success(user);
} else{
return ResultEntity.error("用户名或密码错误");
}
}
5.4 前端login页面引入weixin-utils.js,编写触屏事件
document.getElementById("login_but").addEventListener("tap", function(){
// 先获取用户输入的值
var username = document.getElementById("username").value;
var password= document.getElementById("password").value;
util.ajax({
url:url.login_url,
data:{
"username":username,
"password":password
},
success:function(data){
if(data.code == "ok") {
// 提示信息
data.msg = "登录成功";
// 把用户对象保存到本机的数据库中
var user = data.data;
util.setUser(user)
// 跳转到首页
plus.webview.open("index.html","index.html");
plus.webview.currentWebview().close();
}
plus.nativeUI.toast(data.msg);
}
})
})
5.5 重启User的程序入口登录测试
6. 全局异常处理
6.1 wx-common导包
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.1.11.RELEASE</version>
</dependency>
6.2 wx-common编写BusinessException
package com.wpj.entity.base;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class BusinessException extends RuntimeException {
private String code; //错误码
private String msg; // 错我信息
}
6.3 编写全局异常处理
package com.wpj.entity.exception;
import com.wpj.entity.base.BusinessException;
import com.wpj.entity.base.ResultEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
@ControllerAdvice
public class GlobeExceptionHandler {
@ExceptionHandler(value = Exception.class)
@ResponseBody
public ResultEntity systemEx(Exception e){
System.out.println("系统异常:"+e.getMessage());
return ResultEntity.error(e.getMessage());
}
@ExceptionHandler(value = BusinessException.class)
@ResponseBody
public ResultEntity systemBusiness(BusinessException e){
System.out.println("业务异常:"+e.getMsg());
return ResultEntity.error(e.getMsg());
}
}