Spring 拦截器

為{幸葍}努か 提交于 2019-11-30 11:53:11

示例

(1)编写拦截器

 

package learnspring.learnspring.interceptor;
 
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
/**
 * @author 肖政宇
 * @date 2019-09-24 15:13
 * 说明:拦截器
 * 一个简单的拦截器,计算每一次请求的处理时间
 */
@Component
public class DemoInterceptor extends HandlerInterceptorAdapter {
 
    /**
     * 在请求发生前执行
     */
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object object) throws Exception {
        long startTime = System.currentTimeMillis();
        System.out.println("拦截器接收到请求的时间:" + new Long(startTime));
        request.setAttribute("startTime", startTime);
        return true;
    }
 
    /**
     * 在请求发生之后执行
     */
    @Override
    public void postHandle(HttpServletRequest request,
                           HttpServletResponse response,
                           Object object,
                           ModelAndView modelAndView) throws Exception {
        long startTime = (Long) request.getAttribute("startTime");
        request.removeAttribute("startTime");
        long endTime = System.currentTimeMillis();
        System.out.println("本此请求的处理时间为:" + endTime + " - " + startTime + " = " +
                new Long(endTime - startTime) + "ms");
        request.setAttribute("handlingTime", endTime - startTime);
    }
}

(2)在配置类中注册拦截器

package learnspring.learnspring.interceptor;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.*;
 
/**
 * @author 肖政宇
 * @date 2019-09-24 15:27
 * 说明:配置
 */
@Configuration
@EnableWebMvc
public class MyMvcConfig implements WebMvcConfigurer {
 
    DemoInterceptor demoInterceptor;
 
    @Autowired
    public void setDemoInterceptor(DemoInterceptor demoInterceptor) {
        this.demoInterceptor = demoInterceptor;
    }
 
    /**
     * 注册拦截器
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(demoInterceptor);
    }
}

(3)简单的控制器

package learnspring.learnspring.interceptor;
 
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
 
/**
 * @author 肖政宇
 * @date 2019-09-24 15:38
 * 说明:
 */
@RestController
@RequestMapping("/test")
public class TestController {
    @GetMapping("hello")
    public String sayHello() {
        return "Hello";
    }
}

(4)测试结果

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!