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(chǔ)類:
/** * 業(yè)務(wù)異常 */ 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è)務(wù)異常 * @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; } }
舉例:
登錄的服務(wù)
@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)文章希望大家以后多多支持腳本之家!
相關(guān)文章
SpringCloud Eureka服務(wù)的基本配置和操作方法
Eureka是Netflix開源的一個基于REST的服務(wù)治理框架,主要用于實現(xiàn)微服務(wù)架構(gòu)中的服務(wù)注冊與發(fā)現(xiàn),Eureka是Netflix開源的服務(wù)發(fā)現(xiàn)框架,用于在分布式系統(tǒng)中實現(xiàn)服務(wù)的自動注冊與發(fā)現(xiàn),本文介紹SpringCloud Eureka服務(wù)的基本配置和操作方法,感興趣的朋友一起看看吧2023-12-12玩轉(zhuǎn)spring boot MVC應(yīng)用(2)
玩轉(zhuǎn)spring boot,如何快速搭建一個MCV程序?這篇文章為大家詳細主要介紹了一個MCV程序的快速搭建過程,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-01-01Java經(jīng)典算法匯總之選擇排序(SelectionSort)
選擇排序也是比較簡單的一種排序方法,原理也比較容易理解,選擇排序在每次遍歷過程中只記錄下來最小的一個元素的下標,待全部比較結(jié)束之后,將最小的元素與未排序的那部分序列的最前面一個元素交換,這樣就降低了交換的次數(shù),提高了排序效率。2016-04-04Java數(shù)據(jù)庫連接池之proxool_動力節(jié)點Java學院整理
Proxool是一種Java數(shù)據(jù)庫連接池技術(shù)。方便易用,便于發(fā)現(xiàn)連接泄漏的情況2017-08-08使用SpringBoot和JPA實現(xiàn)批量處理新增、修改
最近項目需要在JPA中使用ID進行批量更新,所以下面這篇文章主要給大家介紹了關(guān)于使用SpringBoot和JPA實現(xiàn)批量處理新增、修改的相關(guān)資料,文中通過實例代碼介紹的非常詳細,需要的朋友可以參考下2023-06-06