Web服务启动时自动加载Servlet,并执行service处理
自动加载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容器,在控制台可以看到"initt1..."这么一行信息。
然后修改我们的代码,让这个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("yourServiceId");
List list = service.getList();
// list就是从数据库取到的内容,你可以做相关的处理
}
}
yourServiceId就是在applicationContext.xml文件里面配置的<beanid="yourServiceId">。
相关推荐
lantingyue 2020-07-30
CoderBoy 2019-12-09
JudeJoo 2020-08-21
meleto 2020-08-15
zyjj 2020-07-27
pengpengflyjhp 2020-07-19
htofly 2020-07-09
三动 2020-06-21
hyxinyu 2020-06-08
洗尽铅华 2020-06-07
shayuchaor 2020-06-07
xiamubawei 2020-06-04
方志朋 2020-05-30
一片荷叶 2020-05-27
spring艳 2020-05-16
zhangdy0 2020-05-06
80304053 2020-05-04
neweastsun 2020-05-04
shuiluobu 2020-05-01