庄生晓梦

庄生晓梦迷蝴蝶

博客园 首页 新随笔 联系 订阅 管理
启动Tomcat7的代码
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());
		}
	}
}

编写的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");
	}

}

运行的效果

测试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();
		}
	}
}
posted on 2010-05-31 00:39  qwop  阅读(108)  评论(0编辑  收藏  举报