1. 程式人生 > >servlet實現統計網站被訪問次數功能

servlet實現統計網站被訪問次數功能

public class Test1 extends HttpServlet {

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html;charset=utf-8");
PrintWriter out=response.getWriter();
ServletContext sc = request.getServletContext();
Object o = sc.getAttribute("access");
if (o != null && o instanceof Integer) {
o = ((Integer) o) + 1;
out.print("網站共"+o+"次訪問");
sc.setAttribute("access", o);
} else {
sc.setAttribute("access", 1);
out.print("網站共1次訪問");
}
}