- 创建过滤器
package com.goldnurse.commons.filter;
import lombok.extern.slf4j.Slf4j;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.text.DecimalFormat;
/**
* @author fengrz
*/
@Slf4j
@WebFilter(urlPatterns = "/*",filterName = "logCostFilter")
public class LogCostFilter implements Filter {
private HttpServletRequest request;
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
this.request = (HttpServletRequest) servletRequest;
String path = request.getRequestURI();
long startTime = System.currentTimeMillis();
filterChain.doFilter(servletRequest,servletResponse);
long endTime = System.currentTimeMillis();
DecimalFormat df=new DecimalFormat("0.000");
log.debug(path + " "+ df.format((float)(endTime-startTime)/1000) +"m ");
}
}
- 主函数添加 @ServletComponentScan
主函数上添加@ServletComponentScan后,就可以在过滤器上使用@WebFilter 标记过滤器
package com.goldnurse;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.transaction.annotation.EnableTransactionManagement;
/**
* 主函数
* @author fengrz
* @since 2020-05-01
*/
@EnableTransactionManagement
@SpringBootApplication
@EnableAsync
@ServletComponentScan
public class SurveyWebApplication {
public static void main(String[] args) {
SpringApplication.run(SurveyWebApplication.class, args);
}
}
- 访问Controller 并查看方法执行时间,如果所示