編寫一個servlet,實現統計網站被訪問次數的功能
阿新 • • 發佈:2018-12-15
import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class ShowTimesServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ServletContext context = getServletContext(); Integer times = (Integer) context.getAttribute("times"); if (times == null) { times = new Integer(1); } else { times = new Integer(times.intValue() + 1); } response.setContentType("text/html;charset=utf-8"); PrintWriter out= response.getWriter(); out.println("<html><head><title>"); out.println("頁面訪問統計"); out.println("</title></head><body>"); out.println("當前頁面被訪問了"); out.println("<font color=red size=20>"+times+"</font>次"); context.setAttribute("times",times); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response); } }