<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>
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();
}
}