Spring MVC Interceptor HandlerInterceptorAdapter,HandlerInterceptor示例

Spring Interceptor用于拦截客户端请求并处理它们。有时我们想拦截HTTP请求并在将其交给控制器处理程序方法之前进行一些处理。这就是Spring MVC拦截器派上用场的地方。

目录[ 隐藏 ]

  • 1 Spring拦截器
  • 2 Spring Interceptor - HandlerInterceptor
    • 2.1弹簧拦截器 - 控制器类
    • 2.2 Spring MVC Interceptor - HandlerInterceptorAdapter实现
    • 2.3 Spring MVC拦截器配置
    • 2.4 Spring MVC拦截器应用程序测试

Spring 拦截器

就像我们有Struts2拦截器一样,我们可以通过实现org.springframework.web.servlet.HandlerInterceptor接口或覆盖org.springframework.web.servlet.handler.HandlerInterceptorAdapter提供HandlerInterceptor接口基本实现的抽象类来创建自己的Spring拦截器。

Spring Interceptor - HandlerInterceptor

Spring HandlerInterceptor根据我们想拦截HTTP请求的位置声明三种方法。

  1. boolean preHandle(HttpServletRequest请求,HttpServletResponse响应,对象处理程序):此方法用于在请求移交给处理程序方法之前拦截请求。这个方法应该返回'true'让Spring知道通过另一个Spring拦截器处理请求,或者如果没有其他弹簧拦截器则将它发送到处理程序方法。

    如果此方法返回'false',则Spring框架假定请求已由spring拦截器本身处理,并且不需要进一步处理。在这种情况下,我们应该使用响应对象来向客户端请求发送响应。

    对象处理程序是处理请求的选定处理程序对象。此方法也可以抛出异常,在这种情况下,Spring MVC异常处理对于将错误页面作为响应发送应该很有用。

  2. void postHandle(HttpServletRequest请求,HttpServletResponse响应,Object处理程序,ModelAndView modelAndView):当HandlerAdapter调用处理程序但DispatcherServlet尚未呈现视图时,将调用此HandlerInterceptor拦截器方法。此方法可用于向要在视图页面中使用的ModelAndView对象添加其他属性。我们可以使用这个spring拦截器方法来确定处理程序方法处理客户端请求所花费的时间。
  3. void afterCompletion(HttpServletRequest请求,HttpServletResponse响应,对象处理程序,Exception ex):这是一个HandlerInterceptor回调方法,一旦执行处理程序并呈现视图就会调用该方法。

如果配置了多个弹簧拦截器,则按配置顺序执行preHandle()方法,而以相反顺序调用postHandle()afterCompletion()方法。

让我们创建一个简单的Spring MVC应用程序,我们将配置一个Spring Interceptor来记录控制器处理程序方法的时序。

我们最终的Spring Interceptor示例项目将如下图所示,我们将研究我们感兴趣的组件。

Spring Interceptor - 控制器类


package com.journaldev.spring;import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;/*** Handles requests for the application home page.*/
@Controller
public class HomeController {private static final Logger logger = LoggerFactory.getLogger(HomeController.class);@RequestMapping(value = "/home", method = RequestMethod.GET)public String home(Locale locale, Model model) {logger.info("Welcome home! The client locale is {}.", locale);//adding some time lag to check interceptor executiontry {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}Date date = new Date();DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);String formattedDate = dateFormat.format(date);model.addAttribute("serverTime", formattedDate );logger.info("Before returning view page");return "home";}}

我只是在执行处理程序方法时添加一些处理时间来检查我们的spring拦截器方法。

Spring MVC Interceptor - HandlerInterceptorAdapter实现

为简单起见,我正在扩展抽象类HandlerInterceptorAdapter。HandlerInterceptorAdapter是HandlerInterceptor接口的抽象适配器类,用于简化pre-only / post-only拦截器的实现。


package com.journaldev.spring;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;public class RequestProcessingTimeInterceptor extends HandlerInterceptorAdapter {private static final Logger logger = LoggerFactory.getLogger(RequestProcessingTimeInterceptor.class);@Overridepublic boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) throws Exception {long startTime = System.currentTimeMillis();logger.info("Request URL::" + request.getRequestURL().toString()+ ":: Start Time=" + System.currentTimeMillis());request.setAttribute("startTime", startTime);//if returned false, we need to make sure 'response' is sentreturn true;}@Overridepublic void postHandle(HttpServletRequest request,HttpServletResponse response, Object handler,ModelAndView modelAndView) throws Exception {System.out.println("Request URL::" + request.getRequestURL().toString()+ " Sent to Handler :: Current Time=" + System.currentTimeMillis());//we can add attributes in the modelAndView and use that in the view page}@Overridepublic void afterCompletion(HttpServletRequest request,HttpServletResponse response, Object handler, Exception ex)throws Exception {long startTime = (Long) request.getAttribute("startTime");logger.info("Request URL::" + request.getRequestURL().toString()+ ":: End Time=" + System.currentTimeMillis());logger.info("Request URL::" + request.getRequestURL().toString()+ ":: Time Taken=" + (System.currentTimeMillis() - startTime));}}

逻辑非常简单,我只是记录处理程序方法执行的时间和处理请求所花费的总时间,包括渲染视图页面。

Spring MVC拦截器配置

我们必须将spring拦截器连接到请求,我们可以使用mvc:interceptors元素来连接所有拦截器。在通过mapping元素包含请求的spring拦截器之前,我们还可以提供匹配的URI模式。

我们的最终spring bean配置文件(spring.xml)如下所示。


<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"xmlns:context="http://www.springframework.org/schema/context"xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsdhttp://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"><!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure --><!-- Enables the Spring MVC @Controller programming model --><annotation-driven /><!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory --><resources mapping="/resources/**" location="/resources/" /><!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory --><beans:beanclass="org.springframework.web.servlet.view.InternalResourceViewResolver"><beans:property name="prefix" value="/WEB-INF/views/" /><beans:property name="suffix" value=".jsp" /></beans:bean><!-- Configuring interceptors based on URI --><interceptors><interceptor><mapping path="/home" /><beans:bean class="com.journaldev.spring.RequestProcessingTimeInterceptor"></beans:bean></interceptor></interceptors><context:component-scan base-package="com.journaldev.spring" /></beans:beans>

我不会解释Web应用程序的所有其他组件,因为我们对它们不感兴趣,并且它们没有任何特定的弹簧拦截器相关配置。

Spring MVC拦截器应用程序测试

只需在servlet容器中部署应用程序并调用主控制器,您将看到如下所示的记录器输出。


INFO : com.journaldev.spring.RequestProcessingTimeInterceptor - Request URL::http://localhost:9090/SpringInterceptors/home:: Start Time=1396906442086
INFO : com.journaldev.spring.HomeController - Welcome home! The client locale is en_US.
INFO : com.journaldev.spring.HomeController - Before returning view page
Request URL::http://localhost:9090/SpringInterceptors/home Sent to Handler :: Current Time=1396906443098
INFO : com.journaldev.spring.RequestProcessingTimeInterceptor - Request URL::http://localhost:9090/SpringInterceptors/home:: End Time=1396906443171
INFO : com.journaldev.spring.RequestProcessingTimeInterceptor - Request URL::http://localhost:9090/SpringInterceptors/home:: Time Taken=1085

输出确认弹簧拦截器方法按定义的顺序执行。

这就是使用弹簧拦截器的全部内容,您可以从下面的链接下载Spring Interceptor示例项目,并尝试使用多个拦截器并按不同的配置顺序进行检查。

下载Spring Interceptors项目

转载来源:https://www.journaldev.com/2676/spring-mvc-interceptor-example-handlerinterceptor-handlerinterceptoradapter

Spring MVC Interceptor Handler InterceptorAdapter HandlerInterceptor示例相关推荐

  1. Spring MVC Hibernate MySQL集成CRUD示例教程

    Spring MVC Hibernate MySQL集成CRUD示例教程 我们在上一篇教程中学习了如何集成Spring和Hibernate.今天,我们将继续前进,并将Spring MVC和Hibern ...

  2. Spring MVC 无XML配置入门示例

    Spring MVC 无XML(纯 Java)配置入门示例 本示例是从<Spring in Action, Fourth Edition>一书而来,涉及的是书中5.1节部分内容,书中其实说 ...

  3. 一步步完成jsRender + Spring MVC + Nginx前后端分离示例

    2019独角兽企业重金招聘Python工程师标准>>> 本篇博文的目标是使用前端页面渲染插件jsRender做前后端分离,后端采用Spring MVC给出REST API,并结合Ng ...

  4. Spring MVC Hibernate验证器使用示例

    下面的示例演示如何使用Spring Web MVC框架在表单中使用错误处理和验证器. 首先使用Eclipse IDE,并按照以下步骤使用Spring Web Framework开发基于动态表单的Web ...

  5. 中input标签赋值_Java程序员:Spring MVC JSP表单标签示例

    Spring MVC的表单标签为Java程序员提供了许多额外的支持.例如数据绑定,允许自动设置数据并从Java对象中检索数据. 从2.0版本开始,Spring提供了一组全面的数据绑定感知标记,用于在使 ...

  6. Spring mvc Interceptor 解决Session超时配置流程

    最近公司内部框架中对Session超时这一功能未实现,由于采用iframe结构,Session超时后,当点击左侧系统菜单时,会在iframe的右侧再次弹出登陆框. 该问题是由于没有设置拦截器造成. 添 ...

  7. Spring MVC Interceptor

    1 在spring-servlet.xml中进行如下配置 <mvc:interceptors><mvc:interceptor> <mvc:mapping path=&q ...

  8. Spring MVC生成PDF文件代码示例

    以下示例演示如何使用Spring Web MVC框架生成PDF格式的文件.首先使用Eclipse IDE,并按照以下步骤使用Spring Web Framework开发基于动态表单的Web应用程序: ...

  9. java 拦截器 排除_java – Spring MVC Interceptor排除HTTP方法的路径

    我有一些拦截器需要在我的API的一些请求中检查标头和授权.例如,某些请求应该要求用户身份验证(例如,从数据库更改用户详细信息),有些请求不需要身份验证(例如,创建用户).不幸的是,从拦截器中排除路径的 ...

最新文章

  1. 试编写一个将双向循环链表逆置的算法_循环双向链表在电路计算中的应用
  2. 深浅拷贝、函数、内置函数、文件处理、三元运算、递归
  3. Session 过期问题处理
  4. CSS3的弹性盒子flex详解(2)
  5. linux单个core的线程,正确使用Core Data多线程的3种方式
  6. 《四世同堂》金句摘抄(六)
  7. 国潮正当时——2021百度国货用户洞察
  8. 免费在线生成工具大全
  9. 【优先队列】HDU 1873——看病找医生
  10. wireshark 抓包分析 TCPIP协议的握手
  11. matlab调用kmeans_使用 K 均值聚类实现基于颜色的分割
  12. 冲动是魔鬼!国庆换机如何不花冤枉钱?
  13. 修改服务器编码和oracle编码,修改oracle 数据服务器编码
  14. SQL基础系列(八)——排序、分组排序(RANK)
  15. 在ARM开发板上安装OpenCV4.5.1
  16. js 鼠标滑轮控制左右横向滚动
  17. 杨卫华:新浪微博的架构发展历程(转)
  18. docker安装torna1.16.2
  19. 读杨绛先生的《我们仨》部分片段
  20. 集合 01集合的概念

热门文章

  1. 9:34 2009-7-28
  2. jQuery:无限循环两个或者多个事件 click / toggle between two functions
  3. HTML5+CSS3实现的响应式垂直时间轴
  4. 解决kindeditor在线编辑器 过滤dl、dd、dt的两种方法
  5. LeetCode刷题(Python)——每个节点的右向指针
  6. Ubuntu 修改 ssh远程端口号
  7. 包装类 java 1615210339
  8. 静态类 c# 1614532739
  9. 使用markdown语法记录笔记 1613957838
  10. 解决 吃货阶段02 0928