SpringMVC @ResponseStatus 的用法


     @ResponseStatus 用於修飾一個類或者一個方法,修飾一個類的時候,一般修飾的是一個異常類,如下,

  1. 聲明一個異常類在類上面加上ResponseStatus注解,就表明,在系統運行期間,拋出AuthException的時候,就會使用這里生命的 error code 和 error reasoon 返回給客戶端,提高可讀性。

package com.kolin.sample;

import org.springframework.http.HttpStatus;

import org.springframework.web.bind.annotation.ResponseStatus;

/**

* 自定義異常類

*

* @author Administrator

*

*/

@ResponseStatus(value = HttpStatus.FORBIDDEN, reason = "Are you okay?")

public class AuthException extends RuntimeException {

    private static final long serialVersionUID = 5759027883028274330L;

}

  1. 在 控制器方法中,拋出一個 AuthException異常。

package com.kolin.sample;

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.ResponseBody;

@Controller("/")

public class SampleControoler {

     @RequestMapping("/")

     @ResponseBody

     String home() {

           return "Hello World!";

     }

     /**

      * 測試拋出異常

      *

      * @return

      */

     @RequestMapping("/say")

     @ResponseBody

     String say() {

           throw new AuthException();

     }

}

  1. 運行系統,查看結果

Image(1)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM