@ControllerAdvice
spring官方文档上解释:
Indicates the annotated class assists a "Controller".
Serves as a specialization of @Component
, allowing forimplementation classes to be autodetected through classpath scanning.
It is typically used to define @ExceptionHandler
,@InitBinder
, and @ModelAttribute
methods that apply to all @RequestMapping
methods.
One of annotations()
, basePackageClasses()
,basePackages()
or its alias value()
may be specified to define specific subsets of Controllersto assist. When multiple selectors are applied, OR logic is applied -meaning selected Controllers should match at least one selector.
The default behavior (i.e. if used without any selector),the @ControllerAdvice
annotated class willassist all known Controllers.
Note that those checks are done at runtime, so adding many attributes and usingmultiple strategies may have negative impacts (complexity, performance).
翻译:
指示带注释的类帮助一个“控制器”。
作为一个专业化的“组件,允许实现类是通过类路径自动扫描。
它通常用于定义@ ExceptionHandler,@和@ modelattributemethods initBinder,适用于所有“requestmapping方法。
一个annotations(),basepackageclasses(),basepackages()或其别名value()可能规定的特定子集,协助controllersto。当多个选择器的应用,或逻辑意义选择的控制器应与至少一个选择器应用。
默认的行为(即如果没有使用任何选择器),“controlleradvice注释将帮助所有已知的控制器类。
请注意,这些检查是在运行时完成的,所以加入了许多属性和多个策略可能有负面影响(复杂性、性能)。
对于作为异常处理的情况下,可以把它当做一个@contorller理解
@ControllerAdvice
public class RestExceptionHandler extends ResponseEntityExceptionHandler {
@Autowired
private HttpServletRequest httpRequest;
@ExceptionHandler(value = { InnerHandleException.class })
public final String handleVMWareException(InnerHandleException ex, WebRequest request) {
return "/error";
}
@ExceptionHandler(value = { UserNotFoundException.class })
public final ModelAndView handlePowerException(UserNotFoundException ex, WebRequest request) {
//如果出现UserNotFoundException异常,则返回登录页,用于记录页面跳转情况下的登录过期处理
return new ModelAndView(new RedirectView("/login"));
}
@ExceptionHandler(value = { UserNotFoundAjaxException.class })
public final ResponseEntity<?> handleVMWareException(UserNotFoundAjaxException ex, WebRequest request) {
//如果出现UserNotFoundAjaxException 异常,则返回httpstatus=401,用于记录ajax请求情况下的登录过期处理
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.parseMediaType("application/json;charset=UTF-8"));
return handleExceptionInternal(ex, ex.getMessage(), headers, HttpStatus.UNAUTHORIZED, request);
}
}
两个异常的定义
public class UserNotFoundException extends RuntimeException {
public UserNotFoundException(String message) {
super(message);
}
public UserNotFoundException() {
}
}
public class UserNotFoundAjaxException extends RuntimeException {
public UserNotFoundAjaxException(String message) {
super(message);
}
public UserNotFoundAjaxException() {
}
}
在service层抛出UserNotFoundException异常并在对应业务的controller层不做catch处理,即可进入@ControllerAdvice标记的异常处理方法。对于页面跳转直接做转到登录页处理,对于ajax请求则通过jquery做处理。
$.ajax({
type: "get",
url: "/courses/deljoin",
data:{
data:data
},
dataType:"json",
error: function(jqXHR, error, errorThrown) {
var status_code = jqXHR.status
if(status_code==401)//判断是否接收到401状态码
{
//返回登录处理
var curWwwPath = window.document.location.href;
var pathName = window.document.location.pathname;
var pos = curWwwPath.indexOf(pathName);
var localhostPath = curWwwPath.substring(0, pos);
var url = localhostPath+"/login";
window.location.href=url;
}
},
success: function(data) {
//成功刷新当前页面
window.location.reload();
}