SPRing Boot提供了 ServletRegistrationBean
,FilterRegistrationBean
,ServletListenerRegistrationBean
这3个东西来进行配置Servlet、Filter、Listener。
通过自定义配置文件WebConfig.java注册Servlet、Filter、Listener。
import java.util.ArrayList;import java.util.EventListener;import java.util.List; import org.springframework.boot.context.embedded.FilterRegistrationBean;import org.springframework.boot.context.embedded.ServletListenerRegistrationBean;import org.springframework.boot.context.embedded.ServletRegistrationBean;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import com.tianshouzhi.springbootstudy.web.filter.DemoFilter;import com.tianshouzhi.springbootstudy.web.listener.DemoListener;import com.tianshouzhi.springbootstudy.web.servlet.DemoServlet; @Configurationpublic class WebConfig extends WebMvcConfigurerAdapter{ @Bean public FilterRegistrationBean getDemoFilter(){ DemoFilter demoFilter = new DemoFilter(); FilterRegistrationBean registrationBean = new FilterRegistrationBean(); registrationBean.setFilter(demoFilter); List<String> urlPatterns = new ArrayList<String>(); urlPatterns.add("/*");//拦截路径,可以添加多个 registrationBean.setUrlPatterns(urlPatterns); registrationBean.setOrder(1); return registrationBean; } @Bean public ServletRegistrationBean getDemoServlet(){ DemoServlet demoServlet = new DemoServlet(); ServletRegistrationBean registrationBean = new ServletRegistrationBean(); registrationBean.setServlet(demoServlet); List<String> urlMappings=new ArrayList<String>(); urlMappings.add("/demoservlet");////访问,可以添加多个 registrationBean.setUrlMappings(urlMappings); registrationBean.setLoadOnStartup(1); return registrationBean; } @Bean public ServletListenerRegistrationBean<EventListener> getDemoListener(){ ServletListenerRegistrationBean<EventListener> registrationBean = new ServletListenerRegistrationBean<>(); registrationBean.setListener(new DemoListener()); //registrationBean.setOrder(1); return registrationBean; }
新闻热点
疑难解答