servlet實現統計網站被訪問次數功能
阿新 • • 發佈:2019-01-07
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次訪問");
}
}
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次訪問");
}
}