>>分享流行的Java框架以及开源软件,对孙卫琴的《精通Spring:Java Web开发技术详解》提供技术支持 书籍支持  卫琴直播  品书摘要  在线测试  资源下载  联系我们
发表一个新主题 开启一个新投票 回复文章 您是本文章第 18574 个阅读者 刷新本主题
 * 贴子主题:  HandlerInterceptor与WebRequestInterceptor的异同 回复文章 点赞(0)  收藏  
作者:flybird    发表时间:2020-09-02 02:28:18     消息  查看  搜索  好友  邮件  复制  引用

相同点
两个接口都可用于Contrller层请求拦截,接口中定义的方法作用也是一样的。

//HandlerInterceptor
boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)throws Exception;
void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)throws Exception;
void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)throws Exception;

//WebRequestInterceptor
void preHandle(WebRequest request) throws Exception;
void postHandle(WebRequest request, ModelMap model) throws Exception;
void afterCompletion(WebRequest request, Exception ex) throws Exception;
WebRequestInterceptor间接实现了HandlerInterceptor,只是他们之间使用WebRequestHandlerInterceptorAdapter适配器类联系。

不同点
WebRequestInterceptor的入参WebRequest是包装了HttpServletRequest 和HttpServletResponse的,通过WebRequest获取Request中的信息更简便。
2.WebRequestInterceptor的preHandle是没有返回值的,说明该方法中的逻辑并不影响后续的方法执行,所以这个接口实现就是为了获取Request中的信息,或者预设一些参数供后续流程使用。
3.HandlerInterceptor的功能更强大也更基础,可以在preHandle方法中就直接拒绝请求进入controller方法。
使用场景
这个在上条已经说了,如果想更方便获取HttpServletRequest的信息就使用WebRequestInterceptor,当然这些HandlerInterceptor都能做,只不过要多写点代码

如何配置
配置类继承WebMvcConfigurationSupport或WebMvcConfigurerAdapter类,重写addInterceptors,InterceptorRegistry实例就可以直接添加。
顺便说下继承WebMvcConfigurationSupport或WebMvcConfigurerAdapter的区别,继承WebMvcConfigurationSupport不需要声明@EnableWebMvc注解,继承WebMvcConfigurerAdapter需要

作者:a乐乐_1234
转自:https://www.jianshu.com/p/25ea148edbc1



程序猿的技术大观园:www.javathinker.net
网站系统异常


系统异常信息
Request URL: http://www.javathinker.net/WEB-INF/lybbs/jsp/topic.jsp?postID=3506

java.lang.NullPointerException

如果你不知道错误发生的原因,请把上面完整的信息提交给本站管理人员