1、创建过滤器MyFilter 实现 Filter。
1)、@Slf4j//日志注解。
2)、@WebFilter(urlPatterns = {“/css/“,”/imsges/“})//Filter过滤器注解。urlPatterns = {“/css/“,”/imsges/“} 是要过滤的路径。
3)、@WebServlet用在Servlet类上 要与 启动类上扫描注解 @ServletComponentScan 注解,一起使用。
package com.wzy.springbootweb02.servlet;import lombok.extern.slf4j.Slf4j;import javax.servlet.*;import javax.servlet.annotation.WebFilter;import java.io.File;import java.io.IOException;@Slf4j//日志注解@WebFilter(urlPatterns = {"/css/*","/imsges/*"})//Filter过滤器注解public class MyFilter implements Filter {//初始化方法。@Overridepublic void init(FilterConfig filterConfig) throws ServletException {log.info("MyFilter初始化完成。");}//过滤逻辑@Overridepublic void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {log.info("MyFilter运行。");filterChain.doFilter(servletRequest,servletResponse);//Filter放行}//销毁方法@Overridepublic void destroy() {log.info("MyFilter销毁了。");}}
2、在启动类上面加上扫描注解 @ServletComponentScan``(basePackages = ``"com.wzy.springbootweb02.servlet"``) 扫描Servlet程序。
package com.wzy.springbootweb02;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.boot.web.servlet.ServletComponentScan;@ServletComponentScan(basePackages = "com.wzy.springbootweb02.servlet")@SpringBootApplicationpublic class SpringbootWeb02Application {public static void main(String[] args) {SpringApplication.run(SpringbootWeb02Application.class, args);}}
