用Servlet实现统计网站被访问次数的功能

思路:

1.新建一个Servlet类继承HttpServlet,重写doGet()和doPost()方法;
2.在doPost方法中调用doGet()方法,在doGet()方法中实现统计网站被访问次数的功能,用户每请求一次servlet,使得访问次数times加1;
3.获取ServletContext,通过它的功能记住上一次访问后的次数。

实现代码:

package readPath;

import java.io.IOException;
import java.io.PrintWriter;

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 test001 extends HttpServlet {
	private static final long serialVersionUID = 1L;
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
	 response.setContentType("text/html;charset=GB2312");
	 //设置编码,不然中文会变成乱码
	 ServletContext context = this.getServletContext();
	 PrintWriter out = response.getWriter();
	 Integer times =(Integer)context.getAttribute("times");
	 if(times==null) {
		 times = new Integer(1);
	 }else {
		 times = new Integer(times.intValue()+1);
	 }
	 out.println(""</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
	 out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"页面访问统计~"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
	 out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"");
	 out.println("当前页面被访问过了");
	 out.println(""+times+"次");
	 //设置属性,将times保存到当前的上下文中
	 context.setAttribute("times", times);
	 
	}
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		this.doGet(req, resp);
	}

}

运行结果:

用Servlet实现统计网站被访问次数的功能_第1张图片

你可能感兴趣的:(JavaWeb开发入门,servlet,java,tomcat,后端)