Spring MVC 全局异常拦截器 HandlerExceptionResolver
我这里只对部分请求做验证,无登录时,抛出此异常,拦截后自动跳转到登录页面,具体可以根据自己的业务来具体实现。
@Order 注解一定要加,保证优先级
@Configuration 不做过多解释
如果不加,抛出的异常不会被此拦截,直接会被工程配置的 404、500 之类的异常拦截到。
废话不说,直接上代码!!请自行查阅!
/**
* 默认是最低优先级,值越小优先级越高
*/
@Order(-1000)
@Configuration
public class NewsLoginException implements HandlerExceptionResolver {
private static final Logger LOGGER = LoggerFactory.getLogger(NewsLoginException.class);
@Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object o, Exception e) {
LOGGER.error(e.getMessage(),e);
if (e instanceOf RuntimeException) {
//TODO do something
}
return new ModelAndView("/modules/front/login");
}
}
项目中的使用 Demo
@GetMapping("/activity/registered")
public String goActivityRegistered(HttpServletRequest request, HttpServletResponse response, Model model) throws RuntimeException {
Object ticketId = request.getSession().getAttribute(NewsConstants.MEDIA_LOGIN_TICKET_ID);
if (ticketId == null) throw new RuntimeException("无效请求!");
return "";
}
如果有不明白的小伙伴,可以私信我!!