1. 程式人生 > >spring boot爬坑之旅途--MyWebAppConfigurer(應用上下文配置)(3)

spring boot爬坑之旅途--MyWebAppConfigurer(應用上下文配置)(3)

應用上下文配置:

package com.zm.blog.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import com.zm.blog.config.interceptor.Interceptor;

@Configuration
public class MyWebAppConfigurer extends WebMvcConfigurerAdapter {
	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		// 多個攔截器組成一個攔截器鏈
		// addPathPatterns 用於新增攔截規則
		// excludePathPatterns 使用者排除攔截
		registry.addInterceptor(new Interceptor()).addPathPatterns("/**");
		super.addInterceptors(registry);
	}
	//靜態資源對映
	@Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**").addResourceLocations("classpath:/uib/hui/");
        super.addResourceHandlers(registry);
    }
}

1.註冊自定義攔截器

package com.zm.blog.config.interceptor;

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

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

public class Interceptor implements HandlerInterceptor {

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

	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object obj, ModelAndView mv) throws Exception {
		long startTime = (Long) request.getAttribute("startTime");
		request.removeAttribute("startTime");
		long endTime = System.currentTimeMillis();
		String  uri=request.getRequestURI();
		System.out.println("本次《"+uri+"》請求的處理時間為:" + new Long(endTime - startTime)+"ms");
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object obj) throws Exception {
		long startTime = System.currentTimeMillis();
		request.setAttribute("startTime", startTime);
		return true;
	}

}

2.註冊靜態資源

@Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**").addResourceLocations("classpath:/uib/hui/");
        super.addResourceHandlers(registry);
    }