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)

posted @ 2017-01-11 22:15  pengshuangbao  阅读(9570)  评论(1编辑  收藏  举报