@ReponseStatus
Posted kikochz
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了@ReponseStatus相关的知识,希望对你有一定的参考价值。
@ResponseStatus
@ResponseBody
//方法正常执行但是状态码变成400
@ResponseStatus(HttpStatus.BAD_REQUEST)
@RequestMapping("/test1")
public String testRes() {
return "你好 世界";
}
//如果加了reason属性reason就一定会发出异常(sendError), 而异常的statusCode就是400
@ResponseStatus(value = HttpStatus.BAD_REQUEST, reason = "请求不可用")
@RequestMapping("/test3")
public String testSuccess() {
return "success";
}
//如果方法内部异常,状态码不会被改变
@ResponseBody
@ResponseStatus(HttpStatus.CONTINUE)//100
@RequestMapping("/test4")
public void testStatusCode() {
throw new RuntimeException();
}
与@ExceptionHandler一起使用, 抛出异常, 但是无法将map的值传递出去, 即使重写了org.springframework.boot.autoconfigure.web.servlet.error.AbstractErrorController#getErrorAttributes
@ResponseStatus(code = HttpStatus.INTERNAL_SERVER_ERROR, reason = "请求不可用")
@ExceptionHandler(UserNotExistException.class)
private ModelAndView handleUserNotExistException1(UserNotExistException e) {
HashMap<String, Object> map = new HashMap<>();
map.put("customer", "用户名不存在");
map.put("msg",e.getMessage());
return new ModelAndView("forward:/error", map);
可以通过指定javax.servlet.error.status_code
将值传递到request中
@ExceptionHandler(UserNotExistException.class)
private ModelAndView handleUserNotExistException2(UserNotExistException e, HttpServletRequest request) {
HashMap<String, Object> map = new HashMap<>();
map.put("customer", "用户名不存在");
request.setAttribute("javax.servlet.error.status_code", HttpStatus.INTERNAL_SERVER_ERROR);
return new ModelAndView("forward:/error", map);
}
public Map<String, Object> getErrorAttributes(WebRequest webRequest, boolean includeStackTrace) {
Object map = webRequest.getAttribute("customer", RequestAttributes.SCOPE_REQUEST);
//保留原有的attr
Map<String, Object> superAttr = super.getErrorAttributes(webRequest, includeStackTrace);
superAttr.put("map", map);
superAttr.put("info", "这是一条信息");
return superAttr;
}
以上是关于@ReponseStatus的主要内容,如果未能解决你的问题,请参考以下文章