首页 > 学院 > 开发设计 > 正文

SpringBoot通过代码注册Servlet、Fillter、Listener

2019-11-10 20:07:49
字体:
来源:转载
供稿:网友

SPRing Boot提供了 ServletRegistrationBeanFilterRegistrationBeanServletListenerRegistrationBean这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;	}


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表