详细解释已在注释中给出
package 统计网站被访问次数;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Main_Class extends HttpServlet{
private static final long seriaVersionUid = 1L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html; charset=GB2312"); //设置中文编码,否则会乱码
ServletContext context = getServletContext(); //唯一接口,封装了web应用的信息
PrintWriter out = resp.getWriter(); //设置输出函数
Integer times = (Integer)context.getAttribute("times"); //记录网站的访问次数
if(times == null)
times = new Integer(1);
else
times = new Integer(times.intValue()+1);
out.println("<html><head><title>"); //通过html中的编码设置字体
out.println("页面访问统计~"); //页面标题
out.println("</title></head><body>"); //页面正文
out.println("当前页面被访问过了");
out.println("<font color = red size=20>"+times+"</font>次");
// 设置属性,将times保存到当前的上下文中
context.setAttribute("times", times);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
super.doPost(req, resp);
}
}