1、 MyServlet
```java
package com.wzy.springbootweb02.servlet;
@WebServlet(name = “MyServlet”, value = “/myServlet”)//,urlPatterns = “/my” public class MyServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.getWriter().write(“111111”); }
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
<br />2、MyFilter 过滤器。
```java
package com.wzy.springbootweb02.servlet;
@Slf4j//日志注解
@WebFilter(urlPatterns = {"/css/*","/imsges/*"})//Filter过滤器注解
public class MyFilter implements Filter {
//初始化方法。
@Override
public void init(FilterConfig filterConfig) throws ServletException {
log.info("MyFilter初始化完成。");
}
//过滤逻辑
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
log.info("MyFilter运行。");
filterChain.doFilter(servletRequest,servletResponse);//Filter放行
}
//销毁方法
@Override
public void destroy() {
log.info("MyFilter销毁了。");
}
}
3、MyServletContextListener 监听器。
package com.wzy.springbootweb02.servlet;
@Slf4j
@WebListener
public class MyServletContextListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent sce) {
log.info("MyServletContextLister监听到项目初始化完成。");
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
log.info("MyServletContextLister监听到项目销毁。");
}
}
4、通过配置文件类的方式:@Configuration 要使用单实例方式。
@Configuration
public class MyRegistConfig {
//servlet
@Bean
public ServletRegistrationBean myServlet(){
MyServlet myServlet = new MyServlet();
return new ServletRegistrationBean(myServlet,"/my","/my02");//拦截路径
}
//过滤器
@Bean
public FilterRegistrationBean myFilter(){
MyFilter myFilter = new MyFilter();
//myServlet拦截哪些路径,myFilter就拦截哪些路径。
// return new FilterRegistrationBean(myFilter,myServlet());
//自定义拦截路径。
FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(myFilter);
filterRegistrationBean.setUrlPatterns(Arrays.asList("/my","/css/*"));
return filterRegistrationBean;
}
//监听器
@Bean
public ServletListenerRegistrationBean myList(){
MyServletContextListener myServletContextListener = new MyServletContextListener();
return new ServletListenerRegistrationBean(myServletContextListener);
}
}