几种Servlet加载方式以及在servlet中调用bean对象

来源:互联网 发布:淘宝上哪家燕窝是正品 编辑:程序博客网 时间:2024/06/03 23:38
自动加载Servlet的方法介绍:

在web.xml这样定义一个servlet:
<servlet> <servlet-name>t1</servlet-name> <servlet-class>com.base.test.T1</servlet-class> <!-- 如果需要自动加载,加下面一句 --> <load-on-startup>1</load-on-startup> </servlet> 


<load-on-startup>标记web容器是否在启动的时候就加载这个servlet

当值为0或者大于0时,表示web容器在应用启动时就加载这个servlet;

当是一个负数时或者没有指定时,则指示容器在该servlet被调用时才加载;

正数的值越小,启动该servlet的优先级越高。


在写这个Servlet里,需要重写init()方法:
package com.base.test; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; public class T1 extends HttpServlet { public T1() { super(); } public void init() throws ServletException { System.out.println("init t1 ... "); } } 


重启web容器,在控制台可以看到"init t1 ... "这么一行信息。

然后修改我们的代码,让这个Servlet可以读取数据库的内容,并进行相关的处理。
如果操作数据库用的是spring的HibernateTemplate和JdbcTemplate,访问数据库是以bean注入的方式,在action里注入service的实现,读取数据库数据,其实现在的关键就是得到这个service的实例化对象。

修改后的servlet:
package com.base.test; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.WebApplicationContextUtils; import com.abc.test.Service1; public class T1 extends HttpServlet { public T1() { super(); } public void init() throws ServletException { ServletContext sc = getServletContext(); WebApplicationContext ac = WebApplicationContextUtils.getRequiredWebApplicationContext(sc); Service1 service = (Service1) ac.getBean("yourBeanId"); List list = service.getList(); // list就是从数据库取到的内容,你可以做相关的处理 } } 



yourBeanId就是在applicationContext.xml文件里面配置的<bean id="yourServiceId">

0 0