SpringBoot前后端交互、全局異常處理之后端異常信息拋到前端顯示彈窗
前提是前端必須有接收后端信息的載體:比如:ajax的異步接收等等。
后端:
編寫后端的統(tǒng)一返回信息類:
/**
* 后端統(tǒng)一返回結(jié)果
* @param <T>
*/
@Data
public class Result<T> implements Serializable {
private Integer code;//1成功,0和其他數(shù)字為失敗。
private String msg;//錯誤信息
private T data;//數(shù)據(jù)
public static <T> Result<T> success(){
Result<T> result = new Result<T>();
result.code=1;
return result;
}
public static <T> Result<T> success(T object){
Result<T> result = new Result<T>();
result.data=object;
result.code=1;
return result;
}
public static <T> Result<T> error(String msg){
Result<T> result = new Result<T>();
result.code=0;
result.msg=msg;
return result;
}
}異?;A類:
/**
* 業(yè)務異常
*/
public class BaseException extends RuntimeException{
public BaseException(String message) {
super(message);
}
public BaseException() {
}
}賬號不存在異常:
/**
* 賬號不存在異常
*/
public class AccountNotFoundException extends BaseException {
public AccountNotFoundException() {
}
public AccountNotFoundException(String msg) {
super(msg);
}
}賬號密碼為空異常:
/**
* 賬號密碼為空
*/
public class InputAccountAndPassword extends BaseException{
public InputAccountAndPassword(String message) {
super(message);
}
}
登錄失敗異常:
/**
* 登錄失敗
*/
public class LoginFailedException extends BaseException{
public LoginFailedException(String msg){
super(msg);
}
}密碼錯誤:
/**
* 密碼錯誤異常
*/
public class PasswordErrorException extends BaseException {
public PasswordErrorException() {
}
public PasswordErrorException(String msg) {
super(msg);
}
}全局異常類:
/**
* 全局異常處理
*/
//@ControllerAdvice(annotations = {RestController.class,Controller.class})
//@ResponseBody
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
/**
* 業(yè)務異常
* @param ex 異常信息
* @return 封裝、拋出給前端
*/
@ExceptionHandler
public Result<String> exceptionHandler(BaseException ex){
log.error(ex.getMessage());
return Result.error(ex.getMessage());
}
@ExceptionHandler
public Result<String> exceptionHandler(ExpiredJwtException ex){
String message=ex.getMessage();
if (message.contains("expired")){
return Result.error("登錄過期!");
}
return null;
}
}舉例:
登錄的服務
@Service
@Slf4j
public class LoginServiceImpl implements LoginService {
@Autowired(required = false)
private LoginMapper loginMapper;
/**
* 用戶登錄
* @param user 用戶
*/
public void userLogin(User user) {
String email = user.getEmail();
String password = user.getPassword();
if (email.isEmpty() || password.isEmpty()) {
//賬號密碼為空
throw new InputAccountAndPassword(MessageConstant.ACCOUNT_PASSWORD_EMPTY);
}
//賬號密碼不為空
else {
//驗證賬號
int i = loginMapper.userExist(email);
//賬號存在
if (i > 0) {
//驗證密碼
int p = loginMapper.loginCheck(email, password);
//密碼正確
if (p == 1) {
//準許登錄 state==1
loginMapper.login(email);
}
else {
//密碼錯誤
throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
}
}
//賬號不存在
else {
throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
}
}
}
}
異常提示常量類MessageConstant:
/**
* 信息提示常量類
*/
public class MessageConstant {
public static final String PASSWORD_ERROR = "密碼錯誤";
public static final String ACCOUNT_NOT_FOUND = "賬號不存在";
public static final String LOGIN_FAILED = "登錄失敗";
public static final String ACCOUNT_PASSWORD_EMPTY="請輸入賬號和密碼";
}控制端:
@RestController
@RequestMapping("/login")
@Slf4j
public class LoginController {
@Autowired(required = false)
private LoginService loginService;
@Autowired
private JwtProperties jwtProperties;
@PostMapping("/userlogin")
public Result login(@RequestBody User user){
log.info("開始登錄:email:{},password:{}",user.getEmail(),user.getPassword());
log.info("{}",user);
loginService.userLogin(user);
//登錄成功后,生成jwt令牌
Map<String, Object>claims=new HashMap<>();
claims.put("userId",1L);
claims.put("email",user.getEmail());
String token= JwtUtil.createJWT(
jwtProperties.getUserSecretKey(),
jwtProperties.getUserTtl(),
claims);
UserDTO userDTO = new UserDTO();
userDTO.setToken(token);
log.info("生成的token是:{}",token);
return Result.success(userDTO);
}
}前端登錄頁面以及ajax的測試用例:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>歡迎登錄公司員工考勤管理平臺</title>
<link rel="shortcut icon" th:href="@{/images/icon.svg}" rel="external nofollow" >
<link rel="stylesheet" type="text/css" th:href="@{/css/bootstrap.css}" rel="external nofollow" >
<script th:src="@{/js/jquery-3.2.1.js}"></script>
<script th:src="@{/js/token.js}"></script>
<script type="text/javascript">
$(function () {
let token=null;
//登錄按鈕
$("#login").click(function () {
let email=$('#email').val();
let password=$('#password').val();
$.ajax({
type:"post",
url:"/login/userlogin",
contentType:"application/json",
data:JSON.stringify({"email":email,"password":password}),
success:function (result) {
if (result.code===1){
token=result.data.token;
alert("登錄成功");
// 收到Token,開始存儲token
localStorage.setItem('token',token);
alert("token值為:"+token+"!");
//返回Token給后端
//返回后端
location.href="/main" rel="external nofollow" ;//也會經(jīng)過攔截器
}else {
alert(result.msg);
}
}
});
});
$("#registry").click(function () {
location.href="/registry" rel="external nofollow"
})
})
</script>
</head>
<body style="position: absolute;
top: 20%;
left: 38%;
transform: translate(40%,40%);
margin: 0;padding: 0">
<div>
<h2>登錄頁面</h2>
</div>
<div>
<label for="email"></label><input type="text" id="email" name="email" placeholder="E-mail address">
</div>
<div>
<label for="password"></label><input type="password" id="password" name="password" placeholder="Password"/>
</div>
<button id="login">登錄</button>
<button id="registry">注冊</button>
</body>
</html>測試:
賬號密碼不為空:

后臺:

賬號不存在:

后臺:

密碼錯誤:

后臺:

還有很多其他的情況......
Tips:其實有些情況可以直接在前端判斷,沒有必要全部都給到后臺判斷,這樣會造成后臺壓力比較大;比如密碼賬號不為空,賬號格式等等。
總結(jié)
到此這篇關(guān)于SpringBoot前后端交互、全局異常處理之后端異常信息拋到前端顯示彈窗的文章就介紹到這了,更多相關(guān)SpringBoot后端異常信息拋到前端彈窗內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- 前端如何調(diào)用后端接口進行數(shù)據(jù)交互詳解(axios和SpringBoot)
- 微信小程序完整項目實戰(zhàn)記錄(前端+SpringBoot后端)
- SpringBoot前端傳遞數(shù)組后端接收兩種常用的方法
- vue2前端使用axios發(fā)起post請求后端(springboot)接收不到值解決辦法
- SpringBoot整合WebSocket實現(xiàn)后端向前端主動推送消息方式
- springboot項目中后端接收前端傳參的方法示例詳解
- SpringBoot的前后端聯(lián)調(diào):表單提交、AJAX登錄與狀態(tài)管理、以及JSON數(shù)據(jù)交互
相關(guān)文章
Java的StringBuilder在高性能場景下的正確用法
StringBuilder?對字符串的操作是直接改變字符串對象本身,而不是生成新的對象,所以新能開銷小.與StringBuffer相比StringBuilder的性能略高,StringBuilder則沒有保證線程的安全,從而性能略高于StringBuffer,需要的朋友可以參考下2023-05-05
淺談SpringBoot 中關(guān)于自定義異常處理的套路
這篇文章主要介紹了淺談SpringBoot 中關(guān)于自定義異常處理的套路,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-04-04
SpringBoot 整合 Lettuce Redis的實現(xiàn)方法
這篇文章主要介紹了SpringBoot 整合 Lettuce Redis的實現(xiàn)方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-07-07
SpringBoot整合SpringDataRedis的示例代碼
這篇文章主要介紹了SpringBoot整合SpringDataRedis的示例代碼,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2021-05-05

