SpringBoot注册Web组件: Servlet、Filter、Listener
由于SpringBoot没web.xml文件,无法在web.xml注册web组件,可用SpringBoot的方式注册。
一、Servlet
Servlet注册方式一:
package com.example.demo.servlet;import jakarta.servlet.annotation.WebServlet;import jakarta.servlet.http.HttpServlet;import jakarta.servlet.http.HttpServletRequest;import jakarta.servlet.http.HttpServletResponse;
@WebServlet("/first")public class Servlet1 extends HttpServlet {
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp){
System.out.println("这是Servlet1");
}
}
运行程序,在浏览器输入 http://127.0.0.1:8080/first
可看到控制台打印日志
Servlet注册方式二:
通过配置类注册的方式
package com.example.demo;import com.example.demo.servlet.Servlet2;import org.springframework.boot.web.servlet.ServletRegistrationBean;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;
@Configurationpublic class ServletConfig {
// ServletRegistrationBean注册Servlet组件,放入Spring容器即可
@Bean
public ServletRegistrationBean getServletRRegistrationBean (){
// 注册Servlet组件 ServletRegistrationBean bean= new ServletRegistrationBean(new Servlet2());
// 添加Servlet访问路径
bean.addUrlMappings("/second");
return bean;
}}
运行代码,在浏览器输入 http://127.0.0.1:8080/second
二、Filter
三、Listener
方式一:
编写代码
package com.example.demo.Listener;import jakarta.servlet.ServletContextEvent;import jakarta.servlet.ServletContextListener;import jakarta.servlet.annotation.WebListener;
@WebListenerpublic class listener1 implements ServletContextListener { @Override
public void contextInitialized(ServletContextEvent sce){
System.out.println("调用listener1 contextInitialized ");
}
@Override
public void contextDestroyed(ServletContextEvent sce){
}
}
编译运行,效果如下图:
方式二:
写上代码:
package com.example.demo;import com.example.demo.Listener.listener2;
import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configurationpublic class ListenerConfig {
@Bean public ServletListenerRegistrationBean getServletListenerRegistrationBean(){
ServletListenerRegistrationBean bean = new ServletListenerRegistrationBean(new listener2());
return bean;
}
}
运行代码,效果(控制台打印)如下: