springboot下使用servlet的 Servlet、Filter、Listener

servlet3.0开始支持注解。web.xml已经不是项目必须的配置。可以使用 @WebServlet,代码如下但

@WebServlet(name = "myTestServlet",urlPatterns = "/myServlet")
public class TestServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setCharacterEncoding("UTF-8");
        resp.getWriter().print("使用的ServlerTest");
        resp.getWriter().close();
    }
}
servlet 3.0说不适用web.xml需要在META-INF/services创建一个javax.servlet.ServletContainerInitializer引导文件,指定初始化配置类:
The implementation of JAX-WS runtime isn't typically bundled in each and every
war file. The implementation would bundle an implementation of the
ServletContainerInitializer (shown below) and the container would look
that up using the services API (the jar file will bundle in it's META-INF/services
directory a file called javax.servlet.ServletContainerInitializer that will
point to the JAXWSServletContainerInitializer shown below).
@HandlesTypes(WebService.class)
JAXWSServletContainerInitializer
implements ServletContainerInitializer
{
public void onStartup(Set<Class<?>> c, ServletContext ctx)
throws ServletException {
// JAX-WS specific code here to initialize the runtime
// and setup the mapping etc.
ServletRegistration reg = ctx.addServlet("JAXWSServlet",
"com.sun.webservice.JAXWSServlet");
reg.addServletMapping("/foo");
}
在springweb中就是这样实现的
@HandlesTypes(WebApplicationInitializer.class)
public class SpringServletContainerInitializer implements ServletContainerInitializer

实现了Servlet容器初始化接口,和加载 WebApplicationInitializer的所有实现

SpringBoot中使用Servlet
在SpringBootApplication上使用@ServletComponentScan注解后,Servlet、Filter、Listener可以直接通过@WebServlet、@WebFilter、@WebListener注解自动注册

例如:启动类指定servlet扫描路径

@SpringBootApplication(scanBasePackages="com.test")
@ServletComponentScan(value = {"com.test.web.listener"}) //指定Servlet扫描地址
public class OpensmsApp {

    public static void main(String[] args) {
        SpringApplication.run(OpensmsApp.class);
    }
}
@WebListener
public class SendCtccSmsListener implements ServletContextListener{
@Override
	public void contextInitialized(ServletContextEvent sce) {
		//servlet容器监听事件
		
	}

	@Override
	public void contextDestroyed(ServletContextEvent sce) {
		//servlet容器销毁时业务处理
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值