首页 > 编程知识 正文

idea怎么创建servlet,获得spring容器

时间:2023-05-04 19:41:54 阅读:41572 作者:258

文章1、servlet生命周期2、servlet上下文加载spring context,servlet在spring context中的对象/bean、springboot加载方式代码启动类中加载@ servlet

一. servlet生命周期

servlet的整个生命周期由servlet容器处理。

如果是特意放在Spring容器中创建的,servlet对象是由Spring容器创建的,但servlet容器不知道此servlet存在,因此可能不在容器中。

所以,servlet只能交给web服务器管理,不要交给spring管理。

在web Server容器中,servlet、Filter和监听器都不由Spring容器管理,因此不能在这些类中直接使用Spring注释将其注入到Bean中

二、servlet上下文加载spring context。 servlet可以使用spring context对象/bean,在使用spring容器的web APP应用程序中,在spring-context.xml文件中配置业务对象之间的依赖关系

要在servlet中使用spring容器管理业务对象,通常, 必须使用webapplicationcontextutils.getrequiredwebapplicationcontext (getservletcontext ) )获取webapplicationtext ) ) 这实际上是使用依赖查找检索对象,并将APP应用程序对象的bean名称硬编码到servlet代码中。

这相当于将spring容器中的bean加载到servlet容器中,也就是说,将spring容器中的bean放置在web.xml中的bean中

三、springboot加载方式代码编写类实现ServletContextListener接口

servletcontext监听器接口。 监听ServletContext对象的生命周期,即web APP应用程序的生命周期。

当servlet容器启动或退出web APP应用程序时,将触发ServletContextEvent事件并由ServletContextListener处理。 ServletContextListener接口定义了两种处理ServletContextEvent事件的方法。

import com.example.demo.service; import com.example.demo.config; 导入javax.servlet.servletcontextevent; import javax.servlet.servletcontextlistener; import javax.servlet.annotation.weblistener; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import Java.net.inet地址; 导入Java.net.socket exception; @ slf4j @ weblistenerpublicclassmylistenerimplementsservletcontextlistener { privatebusinessservicebusinessssservice; 私有系统配置系统配置; /**实现其中的初始化函数,在事件发生时*@paramsce*/启动publicvoidcontextinitialized (servletcontexteventsce ) { businesssservicebusinesssservice=webapplicationcontextutils.gggggggtution rvletcontext ) ).get this.business service=business service; sys config sys config=webapplication contextutils.getwebapplication context (SCE.getservletcontext ) ).getbean ) sys confff } /** *实现其中销毁函数的* @ params ce */publicvoidcontextdestroyed (servletcontexteventsce (system.out.println ) this is is

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。