Spring MVC 注解 @ResponseStatus 的使用

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/andy_zhang2007/article/details/88680628

Spring MVC应用中,通过使用注解@ResponseStatus,我们可以设置HTTP响应的状态。

具体的使用方式这里我们介绍两种 :

  1. 用在控制器方法上
  2. 用在异常类上

1. 用在控制器方法上

@RestController
@RequestMapping(value = "/test")
public class TestServiceController {
    @ResponseStatus(reason = "@ResponseStatus demo", value = HttpStatus.NOT_FOUND)
    @RequestMapping("/response-status-404")
    public void testResponseStatus404() {
        // 省略具体逻辑
    }
}	

定义了上面的控制器方法testResponseStatus404之后,启动应用,访问页面http://localhost:8080/test/response-status-404,你会看到如下页面展示 :
在这里插入图片描述
现在把上面例子中的reason属性设置去掉,也就是换成@ResponseStatus(value = HttpStatus.NOT_FOUND),再次访问页面,你会看到输出 :
在这里插入图片描述
关于背后的原理,可以参考Spring MVC的如下实现:

	// 类 ServletInvocableHandlerMethod 代码片段    
    /**
	 * Set the response status according to the ResponseStatus annotation.
	 */
	private void setResponseStatus(ServletWebRequest webRequest) throws IOException {
		HttpStatus status = getResponseStatus();
		if (status == null) {
			return;
		}

		HttpServletResponse response = webRequest.getResponse();
		if (response != null) {
			String reason = getResponseStatusReason();
			if (StringUtils.hasText(reason)) {
				response.sendError(status.value(), reason);
			}
			else {
				response.setStatus(status.value());
			}
		}

		// To be picked up by RedirectView
		webRequest.getRequest().setAttribute(View.RESPONSE_STATUS_ATTRIBUTE, status);
	}

2. 用在异常类上

@RestController
@RequestMapping(value = "/test")
public class TestServiceController {
    @ResponseStatus(code = HttpStatus.BAD_REQUEST)
    class DemoException extends RuntimeException {}

    @RequestMapping("/response-status-400")
    public void triggerDemoException() {
        // 模仿一个会抛出异常 DemoException 的业务逻辑
        throw new DemoException();
    }
}    

定义了上面的控制器方法triggerDemoException之后,启动应用,访问页面http://localhost:8080/test/response-status-400,你会看到如下页面展示 :
在这里插入图片描述

参考文章

Using Spring @ResponseStatus to Set HTTP Status Code
Error Handling for REST with Spring
response.sendError() vs response.setStatus()

猜你喜欢

转载自blog.csdn.net/andy_zhang2007/article/details/88680628
今日推荐