首页 > 代码库 > Tomcat启动时,自动访问本地servlet
Tomcat启动时,自动访问本地servlet
通过监听器来实现
1.自定义一个类 CallLocationServelt 实现 ServletContextListener
并覆盖其 contextInitialized(ServletContextEventarg0)方法
public void contextInitialized(ServletContextEvent arg0) { // TODO Auto-generated method stub System.out.println("CallLocationServelt监听器启动了"); //利用定时器来执行每3秒访问一次 Timer timer = new Timer(); timer.schedule(new TimerTask() { public void run() { //初始化http请求客户端 HttpClient httpClient =new DefaultHttpClient(); //使用get方法进行请求 HttpGet httpGet = new HttpGet("http://localhost:8080/CallLocationServelt/servlet/LocalServlet"); try { //执行请求,并将结果存入Http响应对象中 HttpResponse response = httpClient.execute(httpGet); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }, 0, 3*1000);
2. 在web.xml配置该监听器,让其在 tomcat 启动时便执行
<listener> <listener-class> CallLocationServelt </listener-class> </listener>
3. 编写一个简单的servlet ,供监听器来访问
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("访问LocalServlet次数:"+(calltime++)); }
完整的项目可以下载: http://download.csdn.net/detail/ch717828/8394573
参考文献:http://blog.csdn.net/cai5/article/details/7528888
http://download.csdn.net/detail/aaayongaaa/5300578
http://download.csdn.net/detail/linzhijia0612/4965858
Tomcat启动时,自动访问本地servlet
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。