之前一篇博客记录了SpringBoot把我们以前的web.xml、server.xml这些配置文件都"砍掉"了,由于SpringBoot默认是以jar包的方式启动嵌入式的Servlet容器来启动SpringBoot的web应用,没有web.xml文件。那如果我们需要自定义一些filter、listener、servlet该怎么办呢?这一篇就来记录一下.
SpringBoot为咱们提供了三个组件,分别来注册servlet、filter、listener。
1. ServletRegistrationBean
2. FilterRegistrationBean
3. ServletListenerRegistrationBean
由于基本原理都一样,我们这边就举注册servlet的例子。
首先编写一个自己的servlet
类:
public class Myservlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.getWriter().write("hello demoServlet"); //用于测试能否返回字符串
super.doGet(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doPost(req, resp);
}
}
接下来编写ServletRegistrationBean
,因为这个组件需要在容器中,所以我们就需要在Spring的配置类中编写,这里配置类的代码省略,只贴出关键代码:
//注册三大组件
@Bean
public ServletRegistrationBean myServlet(){
ServletRegistrationBean registrationBean = new ServletRegistrationBean(new MyServlet(),"/myServlet");
return registrationBean;
}
其中ServletRegistrationBean
这个构造方法需要传两个参数,一个是servlet的实例,另外一个是映射路径.
测试能否访问servlet
:
成功访问
filter和listener的原理也差不多,我们这边贴出配置类中的代码,感兴趣的话可以自己编写去配置。
filter:
@Bean
public FilterRegistrationBean myFilter(){
FilterRegistrationBean registrationBean = new FilterRegistrationBean();
registrationBean.setFilter(new MyFilter()); //指定注册的filter
registrationBean.setUrlPatterns(Arrays.asList("/hello","/myServlet")); //指定映射路径
return registrationBean;
}
listener:
@Bean
public ServletListenerRegistrationBean myListener(){
ServletListenerRegistrationBean<MyListener> registrationBean = new ServletListenerRegistrationBean<>(new MyListener()); //指定要拦截的listener
return registrationBean;
}
接下来又是源码时间,SpringBoot
帮咱们自动配置SpringMVC的dispatcherServlet
组件的时候,也是这样注册Servlet的。
DispatcherServletAutoConfiguration中:
@Bean(name = DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME)
@ConditionalOnBean(value = DispatcherServlet.class, name = DEFAULT_DISPATCHER_SERVLET_BEAN_NAME)
public ServletRegistrationBean dispatcherServletRegistration(
DispatcherServlet dispatcherServlet) {
ServletRegistrationBean registration = new ServletRegistrationBean(
dispatcherServlet, this.serverProperties.getServletMapping());
//默认拦截: / 所有请求;包静态资源,但是不拦截jsp请求; /*会拦截jsp
//可以通过server.servletPath来修改SpringMVC前端控制器默认拦截的请求路径
registration.setName(DEFAULT_DISPATCHER_SERVLET_BEAN_NAME);
registration.setLoadOnStartup(
this.webMvcProperties.getServlet().getLoadOnStartup());
if (this.multipartConfig != null) {
registration.setMultipartConfig(this.multipartConfig);
}
return registration;
}
觉得不错的话多多关注一下哦,大家共勉加油。