欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

springmvc中实现拦截器

程序员文章站 2022-05-10 13:10:11
...
  • Interceptor拦截器实现对每一个请求处理前后进行相关的业务,类似于servlet的Filter
  • 普通的Bean去继承HandlerInterceptorAdapter或实现HandlerInterceptor来自定义拦截器
  • 通过重写WebMvcConfigurerAdapter的addInterceptors方法来注册自定义的拦截器

示例如下:

在“springmvc简单构建一个项目(一)”的基础上增加以下这些:

 

1.自定义拦截器

package com.zgw.springmvc;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * 实现HandlerInterceptor接口或继承HandlerInterceptorAdapter
 * 来实现自定义拦截器
 * @author zan
 *
 */
public class InterceptorDemo implements HandlerInterceptor{

	//请求前执行
	@Override
	public boolean preHandle(HttpServletRequest request, 
			HttpServletResponse response, Object handler) throws Exception {
		long startTime = System.currentTimeMillis();
		request.setAttribute("startTime", startTime);
		return true;
	}

	//请求发生后执行
	@Override
	public void postHandle(HttpServletRequest request, 
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		long startTime = (Long) request.getAttribute("startTime");
		request.removeAttribute("startTime");
		long endTime = System.currentTimeMillis();
		System.out.println("本次请求时间为:" + new Long(endTime - startTime)+"ms");
		request.setAttribute("handlingTime", endTime - startTime);
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {

	}

}

 2.配置,在MySpringmvcConfig类中添加:

 

/*
	 * 配置拦截器的Bean
	 */
	@Bean
	public InterceptorDemo interceptor() {
		return new InterceptorDemo();
	}

	/*
	 * 重写addInterceptors方法,注册一个拦截器
	 */
	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		registry.addInterceptor(interceptor());
	}

 

3.运行,访问http://localhost:8080/springmvc_withoutwebxml/index,结果如下:

 


springmvc中实现拦截器
            
    
    博客分类: springmvc springmvc拦截器java