/*
* 文件: E:\work\Tomcat\webapps\myapp\WEB-INF\src\MainLoopService.java
* 说明: 在主类MainLoopService的init方法中, 启动一个定时线程, 在该线程中
* 可以实现用户自定义的后台服务.
*
*/
package com.main;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MainLoopService extends HttpServlet {
private static Thread threadOut = null;
public void init() throws ServletException {
if (threadOut == null) {
threadOut = new Thread(new TestOut());
threadOut.setDaemon(true);
threadOut.start();
TestOut.isRunning = true;
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out=response.getWriter();
out.println("<html><body><h1>This is a servlet test.</h1></body></html>");
out.flush();
}
}
/*
* 文件: E:\work\Tomcat\webapps\myapp\WEB-INF\src\TestOut.java
* 说明: 该类可以实现用户自定义的后台服务.
*
*/
package com.main;
import com.main.TestOut;
public class TestOut implements Runnable
{
public static boolean isRunning = false;
public void run()
{
while(true)
{
// TODO add your service here!
System.out.println("-----" + System.currentTimeMillis());
try {
Thread.sleep(1000);
}
catch (InterruptedException ex) {
ex.printStackTrace();
}
if (!isRunning)
{
break;
}
}
}
}
<!--
@@
@@ 文件: E:\work\Tomcat\webapps\myapp\WEB-INF\web.xml
@@ 描述:
@@ 1) <servlet-class>com.main.MainLoopService</servlet-class>
@@ 对应MainLoopService.java
@@
-->
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app>
<display-name>Hello World</display-name>
<description>
Welcome to myapp
</description>
<!--
-- 在浏览器中输入localhost:8080/Test, 即可启动MainLoopService
-->
<servlet>
<servlet-name>Test</servlet-name>
<display-name>Test</display-name>
<description>A test Servlet</description>
<servlet-class>com.main.MainLoopService</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Test</servlet-name>
<url-pattern>/Test</url-pattern>
</servlet-mapping>
<!--(begin) sevelet for ajax-->
<!--
-- /AjaxServlet对应于E:\work\Tomcat\webapps\myapp\index.jsp文件中
-- xmlHttpRequest.open("GET", "AjaxServlet", true);
-->
<!--
<servlet-class>AjaxServlet</servlet-class> 类名对应servlet文件
AjaxServlet.java
-->
<!--
<servlet>
<servlet-name>AjaxServlet</servlet-name>
<display-name>AjaxServlet</display-name>
<servlet-class>AjaxServlet</servlet-class>
</servlet>
-->
<!--
-- /AjaxServlet对应于E:\work\Tomcat\webapps\myapp\index.jsp文件中
-- xmlHttpRequest.open("GET", "AjaxServlet", true);
-->
<!--
<servlet-mapping>
<servlet-name>AjaxServlet</servlet-name>
<url-pattern>/AjaxServlet</url-pattern>
</servlet-mapping>
-->
<!--(end) sevelet for ajax-->
</web-app>