我有一个HandlerInterceptorAdapter
,它拦截所有请求并执行用户授权检查。很基本:基于Accept头的Spring MVC - @ExceptionHandler
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
User user = ... // get user
checkIfAuthorized(user); // throws AuthorizationException
return true;
}
我再有那个AuthorizationException
一个@ExceptionHandler
。
@ExceptionHandler(value = AuthorizationException.class)
public ResponseEntity<String> handleNotAuthorized(AuthorizationException e) {
// TODO Custom EXCEPTION HANDLER for json/jsp/xml/other types, based on content type
ResponseEntity<String> responseEntity = new ResponseEntity<>("You are not authorized to access that page.", HttpStatus.UNAUTHORIZED);
return responseEntity;
}
这是细如果(未授权的)请求接受text/plain
(和可以容易地改变为JSON)。 如何为特定的Accept
标题制作不同的@ExceptionHandler
?
@RequestMapping
有produces()
。 @ExceptionHandler
有类似的东西吗?
在第二个例子中,HTML,它会使用[RequestToViewNameTranslator(HTTP://静态.springsource.org /弹簧/文档/ 3.2.x中/ Javadoc的API /组织/ springframework的/网络/ servlet的/ RequestToViewNameTranslator.html)。我有点不想以路径命名的jsp。用你的第一个例子,我不想为'text/html'返回一个视图名称,使用'ResponseEntity'可以吗? –
它看起来像ResponseEntity更加面向REST响应。你应该返回一个ModelAndView(或者只有一个View)。 – Luciano
你建议简单的使用返回类型'Object'并返回基于头部的信息? –