最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

SpringBoot前后端交互、全局異常處理之后端異常信息拋到前端顯示彈窗

 更新時(shí)間:2024年08月09日 10:48:33   作者:我恨我癡心Jack  
Spring Boot是一個(gè)用于構(gòu)建獨(dú)立的、基于生產(chǎn)級(jí)別的Spring應(yīng)用程序的框架,下面這篇文章主要給大家介紹了關(guān)于SpringBoot前后端交互、全局異常處理之后端異常信息拋到前端顯示彈窗的相關(guān)資料,需要的朋友可以參考下

前提是前端必須有接收后端信息的載體:比如:ajax的異步接收等等。

后端:

編寫(xiě)后端的統(tǒng)一返回信息類(lèi):

/**
 * 后端統(tǒng)一返回結(jié)果
 * @param <T>
 */
@Data
public class Result<T> implements Serializable {
    private Integer code;//1成功,0和其他數(shù)字為失敗。
    private String msg;//錯(cuò)誤信息
    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;
    }
}

異常基礎(chǔ)類(lèi):

/**
 * 業(yè)務(wù)異常
 */
public class BaseException extends RuntimeException{
    public BaseException(String message) {
        super(message);
    }
    public BaseException() {
    }
}

 賬號(hào)不存在異常:

/**
 * 賬號(hào)不存在異常
 */
public class AccountNotFoundException extends BaseException {

    public AccountNotFoundException() {
    }

    public AccountNotFoundException(String msg) {
        super(msg);
    }

}

賬號(hào)密碼為空異常: 

/**
 * 賬號(hào)密碼為空
 */
public class InputAccountAndPassword extends BaseException{
    public InputAccountAndPassword(String message) {
        super(message);
    }
}

 登錄失敗異常:

/**
 * 登錄失敗
 */
public class LoginFailedException extends BaseException{
    public LoginFailedException(String msg){
        super(msg);
    }
}

 密碼錯(cuò)誤:

/**
 * 密碼錯(cuò)誤異常
 */
public class PasswordErrorException extends BaseException {

    public PasswordErrorException() {
    }

    public PasswordErrorException(String msg) {
        super(msg);
    }

}

全局異常類(lèi):

/**
 * 全局異常處理
 */
//@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("登錄過(guò)期!");
        }
        return null;
    }
}

舉例:

登錄的服務(wù)

@Service
@Slf4j
public class LoginServiceImpl implements LoginService {
    @Autowired(required = false)
    private LoginMapper loginMapper;

    /**
     * 用戶(hù)登錄
     * @param user 用戶(hù)
     */
    public void userLogin(User user) {
        String email = user.getEmail();
        String password = user.getPassword();
        if (email.isEmpty() || password.isEmpty()) {
            //賬號(hào)密碼為空
            throw new InputAccountAndPassword(MessageConstant.ACCOUNT_PASSWORD_EMPTY);
        }
        //賬號(hào)密碼不為空
        else {
            //驗(yàn)證賬號(hào)
            int i = loginMapper.userExist(email);
            //賬號(hào)存在
            if (i > 0) {
                //驗(yàn)證密碼
                int p = loginMapper.loginCheck(email, password);
                //密碼正確
                if (p == 1) {
                    //準(zhǔn)許登錄 state==1
                    loginMapper.login(email);
                }
                else {
                    //密碼錯(cuò)誤
                    throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
                }
            }
            //賬號(hào)不存在
            else {
                throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
            }
        }
    }
}

異常提示常量類(lèi)MessageConstant:

/**
 * 信息提示常量類(lèi)
 */
public class MessageConstant {
    public static final String PASSWORD_ERROR = "密碼錯(cuò)誤";
    public static final String ACCOUNT_NOT_FOUND = "賬號(hào)不存在";
    public static final String LOGIN_FAILED = "登錄失敗";
    public static final String ACCOUNT_PASSWORD_EMPTY="請(qǐng)輸入賬號(hào)和密碼";
}

控制端:

@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("開(kāi)始登錄: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);
    }
}

前端登錄頁(yè)面以及ajax的測(cè)試用例:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>歡迎登錄公司員工考勤管理平臺(tái)</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,開(kāi)始存儲(chǔ)token
                            localStorage.setItem('token',token);
                            alert("token值為:"+token+"!");
                            //返回Token給后端
                            //返回后端
                            location.href="/main" rel="external nofollow" ;//也會(huì)經(jīng)過(guò)攔截器
                        }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>登錄頁(yè)面</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">注冊(cè)</button>
</body>
</html>

測(cè)試:

賬號(hào)密碼不為空:

后臺(tái):

賬號(hào)不存在:

后臺(tái):

密碼錯(cuò)誤:

后臺(tái):

還有很多其他的情況......

Tips:其實(shí)有些情況可以直接在前端判斷,沒(méi)有必要全部都給到后臺(tái)判斷,這樣會(huì)造成后臺(tái)壓力比較大;比如密碼賬號(hào)不為空,賬號(hào)格式等等。

總結(jié)

到此這篇關(guān)于SpringBoot前后端交互、全局異常處理之后端異常信息拋到前端顯示彈窗的文章就介紹到這了,更多相關(guān)SpringBoot后端異常信息拋到前端彈窗內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • java壓縮文件與刪除文件的示例代碼

    java壓縮文件與刪除文件的示例代碼

    這篇文章主要介紹了java壓縮文件與刪除文件的示例代碼,代碼簡(jiǎn)單易懂,對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2020-08-08
  • Java的StringBuilder在高性能場(chǎng)景下的正確用法

    Java的StringBuilder在高性能場(chǎng)景下的正確用法

    StringBuilder?對(duì)字符串的操作是直接改變字符串對(duì)象本身,而不是生成新的對(duì)象,所以新能開(kāi)銷(xiāo)小.與StringBuffer相比StringBuilder的性能略高,StringBuilder則沒(méi)有保證線程的安全,從而性能略高于StringBuffer,需要的朋友可以參考下
    2023-05-05
  • SWT(JFace) 簡(jiǎn)易瀏覽器 制作實(shí)現(xiàn)代碼

    SWT(JFace) 簡(jiǎn)易瀏覽器 制作實(shí)現(xiàn)代碼

    SWT(JFace) 簡(jiǎn)易瀏覽器 制作實(shí)現(xiàn)代碼
    2009-06-06
  • 簡(jiǎn)單了解Mybatis如何實(shí)現(xiàn)SQL防注入

    簡(jiǎn)單了解Mybatis如何實(shí)現(xiàn)SQL防注入

    這篇文章主要介紹了簡(jiǎn)單了解Mybatis如何實(shí)現(xiàn)SQL防注入,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-01-01
  • 淺談SpringBoot 中關(guān)于自定義異常處理的套路

    淺談SpringBoot 中關(guān)于自定義異常處理的套路

    這篇文章主要介紹了淺談SpringBoot 中關(guān)于自定義異常處理的套路,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2019-04-04
  • SpringBoot 整合 Lettuce Redis的實(shí)現(xiàn)方法

    SpringBoot 整合 Lettuce Redis的實(shí)現(xiàn)方法

    這篇文章主要介紹了SpringBoot 整合 Lettuce Redis的實(shí)現(xiàn)方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2019-07-07
  • jdbc中class.forname的作用

    jdbc中class.forname的作用

    這篇文章主要介紹了jdbc中class.forname的作用,使用示例說(shuō)明了他作用及使用方法,大家參考使用吧
    2014-01-01
  • java實(shí)現(xiàn)web實(shí)時(shí)消息推送的七種方案

    java實(shí)現(xiàn)web實(shí)時(shí)消息推送的七種方案

    這篇文章主要為大家介紹了java實(shí)現(xiàn)web實(shí)時(shí)消息推送的七種方案示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2022-07-07
  • Java Spring IOC圖文詳解

    Java Spring IOC圖文詳解

    IoC是一種讓服務(wù)消費(fèi)者不直接依賴(lài)于服務(wù)提供者的組件設(shè)計(jì)方式,是一種減少類(lèi)與類(lèi)之間依賴(lài)的設(shè)計(jì)原則。下面通過(guò)本文給大家分享spring中ioc的概念,感興趣的朋友一起看看吧
    2021-09-09
  • SpringBoot整合SpringDataRedis的示例代碼

    SpringBoot整合SpringDataRedis的示例代碼

    這篇文章主要介紹了SpringBoot整合SpringDataRedis的示例代碼,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2021-05-05

最新評(píng)論

台前县| 柯坪县| 峡江县| 略阳县| 祁东县| 行唐县| 鄂伦春自治旗| 磐石市| 碌曲县| 鄄城县| 体育| 千阳县| 论坛| 平远县| 合水县| 孟津县| 河源市| 开平市| 凤山市| 桦甸市| 富蕴县| 定州市| 盐津县| 会宁县| 西藏| 桦甸市| 崇信县| 吴江市| 旌德县| 伊通| 开封县| 读书| 新化县| 原阳县| 民县| 宁阳县| 义乌市| 阿鲁科尔沁旗| 镇原县| 长宁区| 襄垣县|