Python 官方文档:入门教程 => 点击学习
本文实例为大家分享了Servlet实现统计页面访问次数的具体代码,供大家参考,具体内容如下 实现思路: 1.新建一个CallServlet类继承httpservlet,重写doGet
本文实例为大家分享了Servlet实现统计页面访问次数的具体代码,供大家参考,具体内容如下
1.新建一个CallServlet类继承httpservlet,重写doGet()和doPost()方法;
2.在doPost方法中调用doGet()方法,在doGet()方法中实现统计网站被访问次数的功能,用户每请求一次servlet,使得访问次数times加1;
3.获取ServletContext,通过它的功能记住上一次访问后的次数。
在WEB.xml中进行路由配置:
<!-- 页面访问次数 -->
<servlet>
<servlet-name>call</servlet-name>
//CallServlet为处理前后端交互的后端类
<servlet-class>CallServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>call</servlet-name>
<url-pattern>/call</url-pattern>
</servlet-mapping>
CallServlet类:
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.Http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
//获得网站被访问的次数
public class CallServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html;charset=utf-8");
ServletContext context = getServletContext();
Integer times = (Integer) context.getAttribute("times");
if (times == null) {
times = new Integer(1);
} else {
times = new Integer(times.intValue() + 1);
}
PrintWriter out= resp.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);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req,resp);
}
}
--结束END--
本文标题: Servlet实现统计页面访问次数功能
本文链接: https://lsjlt.com/news/123112.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2024-03-01
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0