一、背景
一个错误的url请求springboot会根据请求是从浏览器发出来的还是不是浏览器发出来的发出来的出现不同的返回:
浏览器发出来的:返回html代码
不是浏览器发出来的:返回json
二、原因
为什么会出现这种状况呢?看springboot源码中 org.springframework.boot.autoconfigure.web.BasicErrorController
:它是springboot中默认错误的处理器。该类上面有两个注解:
@Controller
@RequestMapping("${server.error.path:${error.path:/error}}")
说明:它本身是controller,处理/error 这种请求,而它下面有两个requestMapping注解的方法:
@RequestMapping(produces = "text/html")
public ModelAndView errorHtml(HttpServletRequest request,
HttpServletResponse response) {
HttpStatus status = getStatus(request);
Map<String, Object> model = Collections.unmodifiableMap(getErrorAttributes(
request, isIncludeStackTrace(request, MediaType.TEXT_HTML)));
response.setStatus(status.value());
ModelAndView modelAndView = resolveErrorView(request, response, status, model);
return (modelAndView != null ? modelAndView : new ModelAndView("error", model));
}
@RequestMapping
@ResponseBody
public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
Map<String, Object> body = getErrorAttributes(request,
isIncludeStackTrace(request, MediaType.ALL));
HttpStatus status = getStatus(request);
return new ResponseEntity<Map<String, Object>>(body, status);
}
从上面的代码可以看出,前一个questMapping中有produces = "text/html"
表示:请求头中的Content-Type参数包含text/html的时候,进入该方法,若没有包含,则进入另一个方法。
前一个方法会返回一个HTML, 后一个方法加了@ResponseBody注解,把一个map转换为json返回。
这就是springboot对浏览器和非浏览器发出请求出现异常,返回不同的原因。