Spring HandlerInterceptor的使用

Spring HandlerInterceptor的使用

标签: springexceptionobjectworkflowstringbean

2007-05-25 16:56 21133人阅读 评论(0) 收藏 举报

Spring(19)

版权声明:本文为博主原创文章,未经博主允许不得转载。

HandlerInterceptor翻译过来就是spring拦截器,它在某些功能应用上特别有用:

1. 用户是否登陆以及用户权限管理 (见http://www.ideawu.net/ideablog/category4/article174.html

2. 根据用户的选择来决定是用HTML还是用Excel来作为View (该应用后面会讲解)

3. blackboard building block的应用:在每一个controller之前都要生成context,在render view之后都要release context

HandlerInterceptor接口有几个重要的方法:

preHandleAction(ActionRequest request, ActionResponse response, Object handler):

该方法会在Controller的方法执行前会被调用,可以使用这个方法来中断或者继续执行链的处理,当返回true时,处理执行链会继续,当返回false时,则不会去执行Controller的方法。(验证用户是否登陆就是使用preHandleAction方法的最好例子)

afterActionCompletion(ActionRequest request, ActionResponse response, Object handler, Exception ex)

preHandleRender(RenderRequest request, RenderResponse response, Object handler)

postHandleRender(RenderRequest request, RenderResponse response, Object handler, ModelAndView modelAndView)

这3个方法会在在controller的方法执行之后,在DispatcherServlet类导向到view进行render之前依次执行。最有用的是使用postHandleRender方法,因为它有ModelAndView 传进来,那么我们就可以在render view之前往view中添加额外的model对象,或者对view的去处进行修改(例如下面的“用HTML还是用Excel来作为View ”例子就是对view进行了更改)

afterRenderCompletion(RenderRequest request, RenderResponse response, Object handler, Exception ex)

该方法会在render view完成后执行,也可以说在请求过程(request processing)完成之后执行。该方法可以用来清理资源(例如象blackboard building block release context)

总结一下HandlerInterceptor的流程:

  1. (DispatcherServlet maps a request to particular handler and assembles a handler execution chain consisting of the handler that is to be invoked and all of the HandlerInterceptor instances that apply to the request.)
  2. preHandleAction(..) is called; if the invocation of this method returns true then this workflow continues
  3. The target handler handles the action phase of the request (via HandlerAdapter.handleAction(..))
  4. afterActionCompletion(..) is called
  5. preHandleRender(..) is called; if the invocation of this method returns true then this workflow continues
  6. The target handler handles the render phase of the request (via HandlerAdapter.handleRender(..))
  7. postHandleRender(..) is called
  8. afterRenderCompletion(..) is called

我们自己写的拦截器可以不直接实现HandlerInterceptor,而是扩展实现了HandlerInterceptor接口的具体类HandlerInterceptorAdapter,这样的话我们不需要把上面5个方法都实现,而只需要override我们需要的方法就可以了!

下面举一个使用拦截器来实现“用HTML还是用Excel来作为View ”功能的例子(只列出关键代码):

search.html:

Search for: 
  <input type="text" name="query"><br>
Output in: 
  <input type="radio name="format" value="xls"/>Excel or 
  <input type="radio" name="format" value="html"/>Html<br>
   
<input type="submit"/>
 
 SearchController.Java:

protected ModelAndView handleRequestInternal(
  HttpServletRequest req, HttpServletResponse response {

  String query = RequestUtils.getRequiredStringParameter("query");
  List shows; // retrieve shows matching the query

  ModelAndView mav = new ModelAndView("listshows", "shows", shows);
  return mav;
}

OutputFormatModificationInterceptor.java:

public class OutputFormatModificationInterceptor
extends HandlerInterceptorAdapter {

  private String parameter;
  private String defaultSuffix = "";
  private Properties suffices;

  // setters and getters omitted 

  public void postHandler(
    HttpServletRequest request, HttpServletResponse response,
    Object handler, ModelAndView mav) throws Exception {

    String format = request.getParameter("format");
    String suffix = suffices.getProperty(format);
    // modify view name if exists
    if (suffix != null) {
      mav.setViewName(mav.getViewName() + suffix); //修改view达到使用不同的output格式的目的
    } else {
      mav.setViewName(mav.getViewName() + defaultSuffix);
  }
}

configure xml file:

<bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping">

<property name="interceptors">

<list>

<ref bean="formatInterceptor"/>

</list>

</property>

</bean>

<bean id="formatInterceptor" class="org.springframework.prospring.web.OutputFormatModificationInterceptor">

<property name="suffices">

<props>

<entry key="xls">-xls</entry>

<entry key="html">-html</entry>

</props>

</property>

<property name="parameter"><value>format</value></property>

<property name="defaultSuffix"><value>-html</value></property>

</bean>

<bean name="/listShows.action" class="org.springframework.prospring.web.controller.ListShowsController">

...

</bean>

那么在blackboard building block里可以使用下面的代码:

public class BbContextInterceptor extends HandlerInterceptorAdapter {

public boolean preHandle(HttpServletRequest request,

HttpServletResponse response, Object handler)

throws Exception {

Context ctx = BbServiceManager.getContextManager().setContext(request);

request.setAttribute(requestAttributeKeyForBbContext, ctx);

//check user is login or not is admin or not. if not, return false

return true;

}

public void afterCompletion(HttpServletRequest request,

HttpServletResponse response, Object handler, Exception ex)

throws Exception {

request.removeAttribute(requestAttributeKeyForBbContext);

BbServiceManager.getContextManager().purgeContext();

}

}

时间: 2024-08-09 22:14:53

Spring HandlerInterceptor的使用的相关文章

Spring HandlerInterceptor

1.Spring HandlerInterceptor 可以组成一个chain. 这个接口有三个方法: public interface HandlerInterceptor { /** * Intercept the execution of a handler. Called after HandlerMapping determined * an appropriate handler object, but before HandlerAdapter invokes the handle

【Spring】7、拦截器HandlerInterceptor

处理器拦截器简介 Spring Web MVC的处理器拦截器(如无特殊说明,下文所说的拦截器即处理器拦截器) 类似于Servlet开发中的过滤器Filter,用于对处理器进行预处理和后处理.   常见应用场景 1.日志记录:记录请求信息的日志,以便进行信息监控.信息统计.计算PV(Page View)等. 2.权限检查:如登录检测,进入处理器检测检测是否登录,如果没有直接返回到登录页面: 3.性能监控:有时候系统在某段时间莫名其妙的慢,可以通过拦截器在进入处理器之前记录开始时间,在处理完后记录结

[十四]SpringBoot 之 Spring拦截器(HandlerInterceptor)

过滤器属于Servlet范畴的API,与spring 没什么关系. Web开发中,我们除了使用 Filter 来过滤请web求外,还可以使用Spring提供的HandlerInterceptor(拦截器). HandlerInterceptor 的功能跟过滤器类似,但是提供更精细的的控制能力:在request被响应之前.request被响应之后.视图渲染之前以及request全部结束之后.我们不能通过拦截器修改request内容,但是可以通过抛出异常(或者返回false)来暂停request的执

Spring自定义一个拦截器类SomeInterceptor,实现HandlerInterceptor接口及其方法的实例

利用Spring的拦截器可以在处理器Controller方法执行前和后增加逻辑代码,了解拦截器中preHandle.postHandle和afterCompletion方法执行时机. 自定义一个拦截器类SomeInterceptor,实现HandlerInterceptor接口及其方法. 然后在spring-mvc.xml中添加拦截器配置,来指定拦截哪些请求. 步骤一: 创建SomeInterceptor拦截器组件 新建一个com.souvc.interceptor包,在该包中新建一个SomeI

22. Spring Boot 拦截器HandlerInterceptor【从零开始学Spring Boot】

转:http://blog.csdn.net/linxingliang/article/details/52069495 上一篇对过滤器的定义做了说明,也比较简单.过滤器属于Servlet范畴的API,与spring 没什么关系.     Web开发中,我们除了使用 Filter 来过滤请web求外,还可以使用Spring提供的HandlerInterceptor(拦截器). HandlerInterceptor 的功能跟过滤器类似,但是提供更精细的的控制能力:在request被响应之前.req

(021)Spring Boot之拦截器HandlerInterceptor

 拦截器的使用步骤: 第一步,实现HandlerInterceptor接口,该接口有三个方法preHandle .postHandle .afterCompletion (1)preHandle在controller执行之前调用 (2)postHandle在controller执行之后,页面渲染之前调用 (3)afterCompletion在页面渲染之后调用,一般用于资源清理操作 第二步,继承WebMvcConfigurationSupport或者实现WebMvcConfigurer,重写他们的

spring mvc拦截器HandlerInterceptor

本文主要介绍springmvc中的拦截器,包括拦截器定义和的配置,然后演示了一个链式拦截的测试示例,最后通过一个登录认证的例子展示了拦截器的应用 拦截定义 定义拦截器,实现HandlerInterceptor接口.接口中提供三个方法. public class HandlerInterceptor1 implements HandlerInterceptor{ //进入 Handler方法之前执行 //用于身份认证.身份授权 //比如身份认证,如果认证通过表示当前用户没有登陆,需要此方法拦截不再

spring mvc

<dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId

Spring MVC @RequestMapping Annotation Example with Controller, Methods, Headers, Params, @RequestPar

Spring MVC @RequestMapping Annotation Example with Controller, Methods, Headers, Params, @RequestParam, @PathVariable Pankaj July 4, 2014 Spring @RequestMapping is one of the most widely used Spring MVC annotation.org.springframework.web.bind.annotat