我有一個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'並返回基於頭部的信息? –