在03-springboot-web的Filter包下,创建HeFilter类
代码示例:
package com.bjpowernode.springboot.filter;
import javax.servlet.*;
import java.io.IOException;
public class HeFilter implements Filter {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
System.out.println("您已经进入HeFilter过滤器……");
filterChain.doFilter(servletRequest,servletResponse);
}
}
在配置包config下的servlet配置类中添加对filter的配置
在03-springboot-web的config包的ServletConfig配置类中添加如下代码
代码如下:
package com.bjpowernode.springboot.config;
import com.bjpowernode.springboot.filter.HeFilter;
import com.bjpowernode.springboot.servlet.HeServlet;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.servlet.ServletRegistration;
@Configuration
public class ServletConfig {
@Bean
public ServletRegistrationBean heServletRegisterBen() {
ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(
new HeServlet(), "/servlet/heservlet"
);
return servletRegistrationBean;
}
@Bean
public FilterRegistrationBean heFilterRegisterBen(){
FilterRegistrationBean filterRegistrationBean=new FilterRegistrationBean();
filterRegistrationBean.setFilter(new HeFilter());
filterRegistrationBean.addUrlPatterns("/*");
return filterRegistrationBean;
}
}
启动springboot项目使用postman访问:http://localhost:8080/servlet/heservlet
在控制台上会看到过滤器里面的输出文字。