Eclipse開發Servlet+jsp模式的簡單計數器
1,點選File->TomcatProject,輸入工程名;
2,在工程下新建一個index.jsp的頁面作為首頁
3,在WEB-INF目錄下新建一個web.xm的檔案,寫入以下內容
<?xml version=”1.0″ encoding=”UTF-8″?>
<web-app version=”2.5″ xmlns=”http://java.sun.com/xml/ns/javaee”
xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance” xsi:schemaLocation=”http://java.sun.com/xml/ns/javaee     http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd”>

<servlet>  
    <servlet-name>CountServlet</servlet-name>
    <servlet-class>cn.sdut.chenqiang.CountServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>CountServlet</servlet-name>
    <url-pattern>/CountServlet</url-pattern>
</servlet-mapping>
<welcome-file-list>
  <welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>

4,在src目錄下新建類CountServlet,繼承HttpServlet
package cn.sdut.chenqiang;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CountServlet extends HttpServlet {
  public static final String CONTENT_TYPE=“text/html;charset=UTF-8”;

  @Override
  public void init(ServletConfig config) throws ServletException {
    // TODO Auto-generated method stub
    super.init(config);
  }

  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    // TODO Auto-generated method stub
    doPost(req, resp);
  }

  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    // TODO Auto-generated method stub
    ServletContext context = getServletContext();
    Integer count = (Integer)context.getAttribute(“count”);
    
    if (count==null)
    {
      count = new Integer(0);
      context.setAttribute(“count”, new Integer(0));
    }
    resp.setContentType(CONTENT_TYPE);
    PrintWriter out = resp.getWriter();
    out.println(“<HTML>”);
    out.println(“<HEAD><TITLE>點選計數</TITLE></HEAD>”);
    out.println(“<BODY>”);
    out.println(“<p>當前計數為:”+count+“</p>”);
    out.println(“</BODY></HEAD>”);
    count = new Integer(count.intValue()+1);
    context.setAttribute(“count”, count);
  }

  @Override
  public void destroy() {
    // TODO Auto-generated method stub
    super.destroy();
  }
  
}

5,執行即可