JSP+Servlet+JavaBean统计页面在线访问次数

统计页面浏览次数:使用的是servlet实现统计次数传递给JSP页面

说明:我做的都比较接地气,意思就是比较简单!

效果图如下:

JSP+Servlet+JavaBean统计页面在线访问次数

上代码

counter.java(它真的好简单,啥事不干,只是定义一个访问次数的基值):

 package util;

 public class Counter {
public static int COUNT_ONLINE=1;
}

Count.java(servlet):它负责处理业务逻辑,获取访问次数并传递给JSP页面

特别注意:
ServletContext servletContext =this.getServletContext();
Object count = servletContext.getAttribute("count");
 package servlet;
import java.io.IOException;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import util.Counter;
public class Count extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// 一般servlet容器启动时便会初始化一个ServleContext 他是被所有servlet共享的.,
//二ServletConfig是当前Servlet的"配置类:,但是ServletConfig中会维护这ServletContex
//这里它的作用相当于JSP页面的application
ServletContext servletContext =this.getServletContext();
Object count = servletContext.getAttribute("count");
if(count ==null){
servletContext.setAttribute("count", Counter.COUNT_ONLINE);
}else{
servletContext.setAttribute("count", Counter.COUNT_ONLINE++);
}
req.getRequestDispatcher("/count.jsp").forward(req, resp);
} @Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(req, resp);
}
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// TODO Auto-generated method stub
super.service(req, resp);
} }

web.xml

  <servlet>
<servlet-name>count</servlet-name>
<servlet-class>servlet.Count</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>count</servlet-name>
<url-pattern>/servlet/count</url-pattern>
</servlet-mapping>

count.jsp:很简单,就只是EL表达式获取下servlet传过来的count变量值

 <%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
Object message = session.getAttribute("sucess"); if(message!=null && !"".equals(message)){ %>
<script type="text/javascript">
alert("<%=message%>");
</script>
<%} %> <%
Object username = session.getAttribute("username");
if(username!=null && !"".equals(username)){ %>
<%=username.toString() %>,欢迎你!<%} %>
hello word! 页面被访问:${count }
</body>
</html>
上一篇:云数据库 Bmob


下一篇:Could not publish server configuration for Tomcat v6.0 Server at localhost.