package com.tan.util; import org.apache.catalina.startup.Bootstrap; /**Tomcat util for start or stop the tomcat.*/ public class TomcatUtil { public static void main(String[] args) { if (args.length == 0) { info("Starting up the tomcat 7!"); Bootstrap.main(args); } else if ("stop".equalsIgnoreCase((args[0]))) { info("Stopping the tomcat 7!"); Bootstrap.main(new String[]{"stop"}); } } private final static void info(Object o) { if (o != null) { System.out.println(o.toString()); } } }
![](http://dl.iteye.com/upload/attachment/257386/78b70826-0596-3e37-85ac-fe6361dc33b8.png)
编写的Servlet
package com.tan.servlet3; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * * @author administrator * * 2010-5-29 上午10:44:27 */ @WebServlet("/firstservlet3") public class FirstServlet3 extends HttpServlet{ private static final long serialVersionUID = 1L; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doPost(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { PrintWriter out = resp.getWriter(); out.println("The first web application for the servlet 3"); } }
运行的效果
![](http://dl.iteye.com/upload/attachment/257388/fa56e5cb-16fb-3fdd-9ac3-6d7ec15c9113.png)
测试AsyncContext
@WebServlet(urlPatterns="/second", asyncSupported=true) public final class SecondServlet3 extends HttpServlet{ private static final long serialVersionUID = -7545111408599552911L; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/html;charset=utf-8"); PrintWriter out = resp.getWriter(); out.println("进入servlet的时间是:" + format(new Date()) + "<br/>"); out.flush(); AsyncContext ctx = req.startAsync(); new Thread(new Executor(ctx)).start(); out.println("结束Servlet的时间:" + format(new Date()) + "<br/>"); out.flush(); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doGet(req, resp); } }
public class Executor implements Runnable{ private AsyncContext ctx = null; public Executor(AsyncContext ctx) { this.ctx = ctx; } public void run() { try { // 等待三秒钟,模拟业务方法执行. Thread.sleep(3000); PrintWriter out = ctx.getResponse().getWriter(); out.println("<span style=\"background-color: #006600; color: #FFFFFF\">业务处理完毕的时间:" + format(new Date()) + "</span>"); out.println("<a href=\"javascript:history.go(-1);\">返回</a>"); out.flush(); ctx.complete(); } catch (Exception e) { e.printStackTrace(); } } }
![](http://dl.iteye.com/upload/attachment/257614/f80872d4-d0ea-3dc9-910e-b4b5f24d2a9a.jpg)