springcloud篇】九. springcloud項目 二 註冊登錄及全局異常處理

註冊登錄及全局異常處理


中國加油,武漢加油!

篇幅較長,請配合目錄觀看

項目準備

  1. 本案例基於 springcloud篇】九. springcloud項目 一 環境搭建

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());
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章