在线用户和访问记录管理

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/LiuY521/article/details/79156139

在线用户和访问记录管理

涉及到的技术:java基础,html,css,javascript,jquery,ajax,jsp,servlet,
listener,mysql等技术。

开始项目之前需要准备好的东西
1.java web开发环境已搭建好 eclipse ee版 tomcat
2.mysql数据库已安装
3.mysql的jdbc驱动程序已经下载好
4.jquery库已经下载好

5.dw cs6

第一天: 先创建一个新的Web项目 Online  需要配置 

  

要给这个项目单独配置一个tomcat服务器,遇到了一个问题 无法创建一个新的,于是百度了很多 按照网上说的 删了俩个文件,是能解决,可以创建新的服务器,但是会发送错误,正在改进 


在新建的服务器中把数据库配置的东西配置到


这样的好处是在配置文件中修改 类似于封装 把这个项目完全打包了,无需在程序里面改信息,直接在配置信息里面改就可以了 简单方便,比我上次写的项目方便多了,

第一步:连接数据库 和之前配置文件中的信息

public class DBLib {
	public static Connection getConnection() throws NamingException, SQLException
	{
		InitialContext initCtx = new InitialContext();   //初始化一个对象
		DataSource ds = (DataSource)initCtx.lookup("java:comp/env/liuyong"); //去查找这个资源   数据源DataSource 得到资源
		return ds.getConnection();					//返回链接
	}
}

关于!!!!!!!!!!!!!!!数据库错误问题一定要注意 (大多数不会遇到 但是我就是个例)

还记得我上次写图书管理项目时,创建数据库时遇到了很多问题,其实答案已经在上个写了,不过我又遇到了,突然忘了,又查了很多博客,怎么说呢 灵光一闪!我突然想到了!!!!!!!!!!!

[Err] 1366 - Incorrect string value: '\xE5\xBC\xA0\xE4\xB8\x89' for column 'UserName' at row 1
无法插入中文,因为我用sql语句创建时没设置UTF-8 默认的 所有在创建数据库时加上一句 
 drop database if exists Visitor;  //判断是否已有 有的话铲除
 create database Visitor //(遇到类似问题加上) DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;




main.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8" import="java.util.*,myhis.*,java.text.*"%>
<!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>
<link rel="stylesheet" type="text/css" href="librarian.css">
</head>
<body>
	<h2>访客记录</h2>
	<a href="main.jsp">主页面</a>
	<a href="login.jsp">登录页面</a>
	<a href="Online.jsp">在线用户</a>
	<a href="visitor.jsp">历史访客</a>
	<table border="1" class="altrowstable">
		<tr>
			<th>序号</th>
			<th>用户名</th>
			<th>在线时间</th>
			<th>URL</th>
		</tr>
		<%
			HistoryDAO dao = new HistoryDAO();
			dao.setPageSize(10); /*设置当前页数为10 */
			if (session.getAttribute("page") == null) {//第一次打开 
				dao.setPageNo(1); //设置为第一页 
				session.setAttribute("page", 1);//保存起来
			} else {
				dao.setPageNo(Integer.parseInt(session.getAttribute("page").toString()));//需要接收字符串 
			}
			//初始化计算多少页
			dao.computePageCount(); //一共多少页 
			ArrayList<History> al = dao.getPagedData();
			for (int i = 0; i < al.size(); i++) {
				History his = al.get(i);
				SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
				String date = df.format(his.getVisitTime());// new Date()为获取当前系统时间,也可使用当前时间戳
		%>
		<tr>
			<td><%=i + 1%></td>
			<td><%=his.getVisitId()%></td>
			<td><%=date%></td>
			<td><%=his.getUrl()%></td>
		</tr>
		<%
			}
		%>
	</table>
	<a href="PageServlet?op=prev">上一页 </a>
	<%=session.getAttribute("page")%>/<%=dao.getPageCount()%>
	<a href="PageServlet?op=next">下一页 </a>
</body>
</html>

Online.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" import="java.util.*,myvisit.*,java.text.*,myuser.*"%>
<!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><link rel="stylesheet" type="text/css" href="librarian.css">
</head>
<body>
<h2> 在线用户</h2>
<a href="main.jsp">主页面</a> 
<a href="login.jsp">登录</a> 
<a href="history1.jsp">访客记录</a>
<a href="visitor.jsp">历史访客</a>
<table border="1" class="altrowstable">
             
  <tr>
    <th>序号</th>
    <th>用户名</th>
    <th>IP</th>
    <th>在线时间</th>
    <th>URL</th>
  </tr>
<%  
 	@SuppressWarnings("unchecked")                        //压制警告
 	HashMap<String, Visitor> map=(HashMap<String, Visitor>) application.getAttribute("ONLINE");  //服务器启动时给空
	Set<String>ids=map.keySet();            //拿到所有的键
	Iterator<String> it=ids.iterator();
	int i=0;
	
	while(it.hasNext())
	{
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
		String date = df.format(new Date());// new Date()为获取当前系统时间,也可使用当前时间戳  
		 String id=it.next();
		 Visitor v=map.get(id);
		 i++;
		 String url="";
		 if(v.getComeFrom()!=null)
		 {
			 url=v.getComeFrom();
		 }
		 UserDAO udao=new UserDAO();
		 String username=udao.getNameById(v.getUserId());
%>
  <tr>
    <td><%=i %></td>
    <td><%=username%></td>
    <td><%=v.getIp()%></td>
    <td><%=date%></td>
    <td><%=url%></td>
  </tr>
  <%
	}
  %>
</table>

</body>
</html>

history1.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8" import="java.util.*,myhis.*,java.text.*"%>
<!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>
<link rel="stylesheet" type="text/css" href="librarian.css">
</head>
<body>
	<h2>访客记录</h2>
	<a href="main.jsp">主页面</a>
	<a href="login.jsp">登录页面</a>
	<a href="Online.jsp">在线用户</a>
	<a href="visitor.jsp">历史访客</a>
	<table border="1" class="altrowstable">
		<tr>
			<th>序号</th>
			<th>用户名</th>
			<th>在线时间</th>
			<th>URL</th>
		</tr>
		<%
			HistoryDAO dao = new HistoryDAO();
			dao.setPageSize(10); /*设置当前页数为10 */
			if (session.getAttribute("page") == null) {//第一次打开 
				dao.setPageNo(1); //设置为第一页 
				session.setAttribute("page", 1);//保存起来
			} else {
				dao.setPageNo(Integer.parseInt(session.getAttribute("page").toString()));//需要接收字符串 
			}
			//初始化计算多少页
			dao.computePageCount(); //一共多少页 
			ArrayList<History> al = dao.getPagedData();
			for (int i = 0; i < al.size(); i++) {
				History his = al.get(i);
				SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
				String date = df.format(his.getVisitTime());// new Date()为获取当前系统时间,也可使用当前时间戳
		%>
		<tr>
			<td><%=i + 1%></td>
			<td><%=his.getVisitId()%></td>
			<td><%=date%></td>
			<td><%=his.getUrl()%></td>
		</tr>
		<%
			}
		%>
	</table>
	<a href="PageServlet?op=prev">上一页 </a>
	<%=session.getAttribute("page")%>/<%=dao.getPageCount()%>
	<a href="PageServlet?op=next">下一页 </a>
</body>
</html>

visitor.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"
	import="java.util.*,myvisit.*,java.text.*,myuser.*"%>
<!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>
<link rel="stylesheet" type="text/css" href="librarian.css">
</head>
<body>
	<h2>历史访客</h2>
	<a href="main.jsp">主页面</a>
	<a href="login.jsp">登录页面</a>
	<a href="Online.jsp">在线用户</a>
	<a href="history1.jsp">访客记录</a>
	<table border="1" class="altrowstable">
		<tr>
			<th>序号</th>
			<th>用户名</th>
			<th>IP</th>
			<th>在线时间</th>
			<th>离开时间</th>
			<th>URL</th>
		</tr>
		<%
			VisitorDAO dao = new VisitorDAO();
			dao.setPageSize(10); /*设置当前页数为10 */
			if (session.getAttribute("page") == null) {//第一次打开 
				dao.setPageNo(1); //设置为第一页 
				session.setAttribute("page", 1);//保存起来

			} else {
				dao.setPageNo(Integer.parseInt(session.getAttribute("page").toString()));//需要接收字符串 
			}
			//初始化计算多少页
			dao.computePageCount(); //一共多少页 
			ArrayList<Visitor> al = dao.getPagedData();
			for (int i = 0; i < al.size(); i++) {
				Visitor v = al.get(i);
				SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
				String date = df.format(v.getVisitTime());// new Date()为获取当前系统时间,也可使用当前时间戳  
				String url = "";
				if (v.getComeFrom() != null) {
					url = v.getComeFrom();
				}
				String left = "";
				if (v.getLeftTime() != null) {
					left = df.format(v.getLeftTime());
				}
				UserDAO udao = new UserDAO();
				String username = udao.getNameById(v.getUserId());
		%>

		<tr>
			<td><%=i + 1%></td>
			<td><%=username%></td>
			<td><%=v.getIp()%></td>
			<td><%=date%></td>
			<td><%=left%></td>
			<td><%=url%></td>
		</tr>
		<%
			}
		%>
	</table>
	<a href="PageServlet1?op=prev">上一页 </a>
	<%=session.getAttribute("page")%>/<%=dao.getPageCount()%>
	<a href="PageServlet1?op=next">下一页 </a>
</body>
</html>

login.jsp

<%@ 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><link rel="stylesheet" type="text/css" href="librarian.css">
<script type="text/javascript" src="pytjon/jquery-1.11.1.js"></script>
<script type="text/javascript">
$(function(){
 	$("#btn").click(function(){
		if($.trim($("input[name='uname']").val()).length==0)
		{
			$("#info").css("color","red").html("请输入用户名!");
			$("input[name='uname']").select();
			$("input[name='uname']").focus();
			return false;
		}
		if($.trim($("input[name='pwd']").val()).length==0)
		{
			$("#info").css("color","red").html("请输入密码!");
			$("input[name='pwd']").select();
			$("input[name='pwd']").focus();
			return false;
		}
		//如果已经登录,就不准登录  JQ中ajax 默认异步执行
		$.ajaxSetup({async:false}); //变成同步运行  
		var info="";
		$.post("CheckExists",{username:$("input[type='text'][name='uname']").val()},function(data){
			info=data;
			});
				if(info.length>0)
				{
					alert(info);
					return false;
				}
		return true;
	});
});
</script>
</head>
<body>
<h2>登录</h2>
<a href="main.jsp">主页面</a> 
<a href="Online.jsp">在线用户</a>
<a href="history1.jsp">历史访客</a>
<a href="visitor.jsp">在线用户</a>
<form action="CheckIt" method="post">
<table border="1" class="altrowstable">
  <tr>
    <td colspan="2">用户登录信息
    </td>
  </tr>
  <tr>
    <td>用户名</td>
    <td><input type="text" name="uname">
    </td>
  </tr>
  <tr>
    <td>密码</td>
    <td><input type="text" name="pwd">
    </td>
  </tr>
  <tr>
    <td colspan="2"><input type="submit" id="btn" value="登录" style="float:left">
    <div id="info" style="float:left">
    </div>
    </td>
  </tr>
</table>
</form>
</body>
</html>

样式表.css

@charset "utf-8";
/* CSS Document */

table.altrowstable {
	font-family: verdana,arial,sans-serif;
	font-size:11px;
	color:#333333;
	border-width: 1px;
	border-color: #a9c6c9;
	border-collapse: collapse;
}
table.altrowstable th {
	border-width: 1px;
	padding: 8px;
	border-style: solid;
	border-color: #a9c6c9;
}
table.altrowstable td {
	border-width: 1px;
	padding: 8px;
	border-style: solid;
	border-color: #a9c6c9;
}
.oddrowcolor{
	background-color:#d4e3e5;
}
.evenrowcolor{
	background-color:#c3dde0;
}

init.jsp

<%@ 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></title>
<script type="text/javascript" src="pytjon/jquery-1.11.1.js"></script>
<script type="text/javascript">
$(function(){
	$("[type='button']").click(function(){
		$.post("InitIt",function(data){
		$("#info").html(data);
		});
	});
});
</script>
</head>
<body>
<input type="button" value="初始化按钮">
<div id="info"></div>
</body>
</html>

DBLib

package db;

import java.sql.Connection;
import java.sql.SQLException;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

public class DBLib {
	public static Connection getConnection() throws NamingException, SQLException
	{
		InitialContext initCtx = new InitialContext();   //初始化一个对象
		DataSource ds = (DataSource)initCtx.lookup("java:comp/env/mytest"); //去查找这个资源   数据源DataSource 得到资源
		return ds.getConnection();					//返回链接
	}
}

InitDB

package db;

import java.io.*;
import java.sql.*;

import javax.annotation.processing.Filer;
import javax.naming.NamingException;

public class InitDB {
	public static void initialize(String scriptfile) throws NamingException, SQLException, IOException
	{ 
	//接收数据库脚本文件  scriptfile
		Connection conn=DBLib.getConnection();  //得到连接
		Statement st=conn.createStatement();   //执行数据库操作 创建一个 对象来将 SQL 语句发送到数据库。
		FileReader fr=new FileReader(scriptfile);  //上抛一个找不到文件的错误 用到字符流
		BufferedReader br=new BufferedReader(fr);  //一行一行的读  
		String sql="";
		String line="";
		while((line=br.readLine())!=null)  //判读下一行是否为空!
		{
			if(!line.endsWith(";"))     //判断是否以分号结尾  endsWith() 方法用于测试字符串是否以指定的后缀结束
			{
				sql=sql+line;          //如果不是则相加
				continue;     
			}
			sql=sql+line;              //如果找到分号,加上   
			st.addBatch(sql);          // 批量插入数据的话 addBatch()用法很方便 
			sql="";                    //清空sql语句,防止下次插入时,加上之前的数据
		}
		st.executeBatch();             //批量处理
		br.close();
	}
}

 InitIt

package db;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class InitIt
 */
@WebServlet("/InitIt")
public class InitIt extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public InitIt() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		/*获取的是Servlet容器对象,相当于tomcat容器了。getRealPath("/") 
		获取实际路径,“/”指代项目根目录
		,所以代码返回的是项目在容器中的实际发布运行的根路径*/
		request.setCharacterEncoding("utf-8"); //提取数据乱码
		response.setCharacterEncoding("utf-8");//输出乱码
		PrintWriter out=response.getWriter();
		try {
			InitDB.initialize(request.getServletContext().getRealPath("")+"//init.sql");
			out.println("数据化初始成功!");
		} catch (NamingException | SQLException e) {
			// TODO Auto-generated catch block
			out.println(e.getMessage());
		}
		//response.getWriter().append("Served at: ").append(request.getContextPath());
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request,response);
	}

}

History

package myhis;

import java.util.Date;

public class History {
	int id;
	int visitId;   //跟访客表联系在一起ID
	Date visitTime;  //访问时间
	String url;      //访问地址
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public int getVisitId() {
		return visitId;
	}
	public void setVisitId(int visitId) {
		this.visitId = visitId;
	}
	public Date getVisitTime() {
		return visitTime;
	}
	public void setVisitTime(Date visitTime) {
		this.visitTime = visitTime;
	}
	public String getUrl() {
		return url;
	}
	public void setUrl(String url) {
		this.url = url;
	}
}

HistoryDAO

package myhis;
//数据访问对象
import java.sql.*;
import java.util.*;
import javax.naming.NamingException;
import db.DBLib;
public class HistoryDAO {   //数据访问对象
		Connection conn;   //连接数据库 
	    PreparedStatement ps;   //命令对象 
		String sql;             //存放数据对象
		ResultSet rs;
		int pageNo;				//当前页码是多少
		int pageSize;			//每页显示多少条数据
		int pageCount;          //一共有多少页
	 public HistoryDAO() throws NamingException, SQLException{
		conn=DBLib.getConnection();      //得到连接
		sql=" use visitor"; //使用数据库 
		ps=conn.prepareStatement(sql);//到的
		ps.executeUpdate();  //连接数据库
	 }
	 public void saveHistory(History history) throws SQLException, NamingException
	 {
		 //防止卡死 每次用完就关掉
		 if(conn.isClosed())
		 {
			 conn=DBLib.getConnection();
		 }
		//访客信息拿到数据库中visitors表中    并返回一个ID(因为要通过这ID找到此用户)
		sql="insert into history (visitId,visittime,url) values (?,?,?)"; 
		ps=conn.prepareStatement(sql);//命令对象 
		ps.setInt(1,history.getVisitId()); 
		ps.setTimestamp(2, new Timestamp(history.getVisitTime().getTime()));   //data类得到时间  用户进来时间
		ps.setString(3, history.getUrl());                                     //
	    ps.executeUpdate();  //提交 把信息保存起来了
	    conn.close();
	}
		public ArrayList<History> getHistory() throws SQLException, NamingException
		{ //提取所有数据
			 //防止卡死 每次用完就关掉
			 if(conn.isClosed())
			 {
				 conn=DBLib.getConnection();
			 }
			sql="select * from history";   //查询这个表
			ps=conn.prepareStatement(sql);
			rs=ps.executeQuery();
			ArrayList<History> al=new ArrayList<History>();
			while(rs.next())
			{	
				History his=new History();    
				his.setId(rs.getInt(1));
				his.setVisitId(rs.getInt(2));
				his.setVisitTime(rs.getTimestamp(3));
				his.setUrl(rs.getString(4));
				al.add(his);
			}
			conn.close();
			return al;	
		}
		public ArrayList<History> getPagedData() throws SQLException, NamingException
		{ //获取本页的数据
			 //防止卡死 每次用完就关掉
			 if(conn.isClosed())
			 {
				 conn=DBLib.getConnection();
			 }
			sql="select * from history limit " + (pageNo-1)*pageSize + "," + pageSize;   //查询这个表
			ps=conn.prepareStatement(sql);
			rs=ps.executeQuery();
			ArrayList<History> al=new ArrayList<History>();
			while(rs.next())
			{	
				History his=new History();    
				his.setId(rs.getInt(1));
				his.setVisitId(rs.getInt(2));
				his.setVisitTime(rs.getTimestamp(3));
				his.setUrl(rs.getString(4));
				al.add(his);
			}
			conn.close();
			return al;	
		}
		//计算这个表中有多少条数据
		public void computePageCount() throws SQLException, NamingException
		{
			 //防止卡死 每次用完就关掉
			 if(conn.isClosed())
			 {
				 conn=DBLib.getConnection();
			 }
			 sql="select count(*) from history";   //计算这个表中有多少条数据
				ps=conn.prepareStatement(sql);      //提交数据
				rs=ps.executeQuery();               //执行
				rs.next();                          //结果是一行一列 下一行记录 及第一行
				pageCount=rs.getInt(1);
				if(pageCount % pageSize==0)
				{
					pageCount=pageCount / pageSize;
				}
				else
				{
					pageCount=pageCount / pageSize + 1;
				}
				conn.close();
		}
		public int getPageNo() {
			return pageNo;
		}
		public void setPageNo(int pageNo) {
			this.pageNo = pageNo;
		}
		public int getPageSize() {
			return pageSize;
		}
		public void setPageSize(int pageSize) {
			this.pageSize = pageSize;
		}
		public int getPageCount() {
			return pageCount;
		}
}

PageServlet

package myhis;

import java.io.IOException;
import java.sql.SQLException;

import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class PageServlet
 */
@WebServlet("/PageServlet")
public class PageServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public PageServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String op=request.getParameter("op");
		HttpSession session=request.getSession(); //拿到session
		int page=Integer.parseInt(session.getAttribute("page").toString());//拿到当前页
		if(op.equals("prev"))
		{
			//判断是否为上一页
			if(page>1)
			{
				page--;
			}
		}
		else
		{
			try {
				HistoryDAO  dao=new HistoryDAO();
				dao.setPageSize(10);
				dao.computePageCount(); //计算总页数
				if(page<dao.getPageCount()) 
				{
					page++;
				}
			} catch (NamingException | SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
		//保存 session 中 
		session.setAttribute("page", page);
		response.sendRedirect("history1.jsp");
		//response.getWriter().append("Served at: ").append(request.getContextPath());
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

CheckExists

package myuser;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;

import javax.naming.NamingException;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import myvisit.Visitor;

/**
 * Servlet implementation class CheckExists
 */
@WebServlet("/CheckExists")
public class CheckExists extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CheckExists() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
		String date = df.format(new Date());// new Date()为获取当前系统时间,也可使用当前时间戳  
		String name=request.getParameter("username");
		int id=0;
		try {
			UserDAO dao=new UserDAO();
			id=dao.getIdNameBy(name);
		} catch (NamingException | SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		//id=0;输入用户名是错的、
		PrintWriter out=response.getWriter();
		if(id==0)
		{
			out.println("你输入的用户不存在!");
			return;
		}
		//判断用户表中是否有该id的访客
		ServletContext application=request.getServletContext();
		@SuppressWarnings("unchecked")
		HashMap<String, Visitor> map=(HashMap<String, Visitor>) application.getAttribute("ONLINE");
		Set<String> ids=map.keySet();
		Iterator<String> it=ids.iterator();
		Visitor current=null;
		while(it.hasNext())
		{
			String sid=it.next(); //键
			Visitor v=map.get(sid);//通过键拿到值
			if(v.getUserId()==id)
			{
				current=v;
				break;
			}
		}
		if(current!=null) //登录
		{
			out.println("当前用户已"+date+"时间"+"ID地址为:"+current.getIp()+"登录!");
		}
			
		//response.getWriter().append("Served at: ").append(request.getContextPath());
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

CheckIt

package myuser;

import java.io.IOException;
import java.sql.SQLException;

import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import myvisit.Visitor;
import myvisit.VisitorDAO;

/**
 * Servlet implementation class CheckIt
 */
@WebServlet("/CheckIt")
public class CheckIt extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CheckIt() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		request.setCharacterEncoding("utf-8");
		User user=new User();
		user.setUserName(request.getParameter("uname"));
		user.setPwd(request.getParameter("pwd"));
		int id=0;
		try {
			UserDAO dao=new UserDAO();
			id=dao.getUserId(user);
			if(dao.getUserId(user)==0)   //判读是否合法
			{ 
				response.sendRedirect("login.jsp");   //不正确 进入
			}
		} catch (NamingException | SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		//response.getWriter().append("Served at: ").append(request.getContextPath());
		//用户名密码正确
		//1.修改在线用户表,将登录用户的id写入
		HttpSession session=request.getSession();
		Visitor v=(Visitor) session.getAttribute("USER");
		v.setUserId(id);
		//2.修改历史访客表,就将登录用户的id写入
		try {
			VisitorDAO dao=new VisitorDAO();
			dao.updateVisitor(v);
		} catch (NamingException | SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		//登录成功 跳转页面
		response.sendRedirect("main.jsp");
	}
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

User

package myuser;

public class User {
 String userName;
 String pwd;
public String getUserName() {
	return userName;
}
public void setUserName(String userName) {
	this.userName = userName;
}
public String getPwd() {
	return pwd;
}
public void setPwd(String pwd) {
	this.pwd = pwd;
}
 
}

UserDAO

package myuser;
//数据访问对象
import java.sql.*;
import java.util.ArrayList;
import java.util.Date;

import javax.naming.NamingException;
import db.DBLib;
import myvisit.Visitor;
public class UserDAO {
  //数据访问对象
			Connection conn;   //连接数据库 
		    PreparedStatement ps;   //命令对象 
			String sql;             //存放数据对象
			ResultSet rs;
		 public UserDAO() throws NamingException, SQLException{
			conn=DBLib.getConnection();      //得到连接
			sql=" use visitor"; //使用数据库 
			ps=conn.prepareStatement(sql);//到的
			ps.executeUpdate();  //连接数据库
		 }
		 public int getUserId(User user) throws SQLException, NamingException   //判断是否合法 
		 {
			 //防止卡死 每次用完就关掉
			 if(conn.isClosed())
			 {
				 conn=DBLib.getConnection();
			 }
			//访客信息拿到数据库中visitors表中    并返回一个ID(因为要通过这ID找到此用户)
			sql="select id  from users where username=? and pwd=?";    //用户名和密码等于多少个 有一个可以登录 0不能登录  
			ps=conn.prepareStatement(sql);//命令对象 
			ps.setString(1,user.userName);                           
			ps.setString(2,user.pwd); 
			rs=ps.executeQuery();
			int id=0;
			if(rs.next())   //判断能否指到下一行
			{
				id=rs.getInt(1);
			}
			conn.close();
			return id;
		}
			public String getNameById(int id) throws SQLException, NamingException 
			{ //通过name找ID
				 if(conn.isClosed())
				 {
					 conn=DBLib.getConnection();
				 }
				sql="select username from users where id=?";
				ps=conn.prepareStatement(sql);
				ps.setInt(1, id);
				rs=ps.executeQuery();
				String name="";
				if(rs.next())
				{
				name=rs.getString(1);	
				}
				 //结果只有一行
				conn.close();
				return name;
			}
			public int getIdNameBy (String name) throws SQLException, NamingException
			{//通过ID找NAME
				 if(conn.isClosed())
				 {
					 conn=DBLib.getConnection();
				 }
				sql="select id from users where username=?";
				ps=conn.prepareStatement(sql);
				ps.setString(1, name);
				rs=ps.executeQuery();
				int id=0;
				if(rs.next())
				{
				id=rs.getInt(1);	
				}
				 //结果只有一行
				conn.close();
				return id;
				
			}
			
}

PageServlet1

package myvisit;

import java.io.IOException;
import java.sql.SQLException;

import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import myvisit.*;;

/**
 * Servlet implementation class PageServlet1
 */
@WebServlet("/PageServlet1")
public class PageServlet1 extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public PageServlet1() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String op=request.getParameter("op");
		HttpSession session=request.getSession(); //拿到session
		int page=Integer.parseInt(session.getAttribute("page").toString());//拿到当前页
		if(op.equals("prev"))
		{
			//判断是否为上一页
			if(page>1)
			{
				page--;
			}
		}
		else
		{
			try {
				VisitorDAO  dao=new VisitorDAO();
				dao.setPageNo(10);
				dao.setPageSize(10);
				dao.computePageCount(); //计算总页数
				if(page<dao.getPageCount()) 
				{
					page++;
				}
			} catch (NamingException | SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
		//保存 session 中 
		session.setAttribute("page", page);
		response.sendRedirect("visitor.jsp");
		//response.getWriter().append("Served at: ").append(request.getContextPath());
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

Visitor

package myvisit;

import java.util.Date;

public class Visitor {
	int id;
	int userId;
	Date visitTime;
	Date leftTime;
	String ip;
	String comeFrom;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public int getUserId() {
		return userId;
	}

	public void setUserId(int userId) {
		this.userId = userId;
	}

	public Date getVisitTime() {
		return visitTime;
	}

	public void setVisitTime(Date visitTime) {
		this.visitTime = visitTime;
	}

	public Date getLeftTime() {
		return leftTime;
	}

	public void setLeftTime(Date leftTime) {
		this.leftTime = leftTime;
	}

	public String getIp() {
		return ip;
	}

	public void setIp(String ip) {
		this.ip = ip;
	}

	public String getComeFrom() {
		return comeFrom;
	}

	public void setComeFrom(String comeFrom) {
		this.comeFrom = comeFrom;
	}

	@Override
	public String toString() {
		return "Visitor [id=" + id + ", userId=" + userId + ", visitTime=" + visitTime + ", leftTime=" + leftTime
				+ ", ip=" + ip + ", comeFrom=" + comeFrom + "]";
	}

}

VisitorDAO

package myvisit;
//数据访问对象
import java.sql.*;
import java.util.*;
import javax.naming.NamingException;
import db.DBLib;
public class VisitorDAO {
	Connection conn; // 连接数据库
	PreparedStatement ps; // 命令对象
	String sql; // 存放数据对象
	ResultSet rs;
	int pageNo; // 当前页码是多少
	int pageSize; // 每页显示多少条数据
	int pageCount; // 一共有多少页
	public VisitorDAO() throws NamingException, SQLException { // 定义构造函数初始化
		conn = DBLib.getConnection(); // 得到连接
		sql = " use visitor"; // 使用数据库
		ps = conn.prepareStatement(sql);// 到的
		ps.executeUpdate(); // 连接数据库
	}
	// 访客信息拿到数据库中visitors表中 并返回一个ID(因为要通过这ID找到此用户)
	public int saveVisitor(Visitor v) throws SQLException, NamingException {
		// 防止卡死 每次用完就关掉
		if (conn.isClosed()) {
			conn = DBLib.getConnection();
		}
		sql = "insert into visitors (userId,visitTime,leftTime,ip,comeFrom) values (?,?,?,?,?)";
		ps = conn.prepareStatement(sql);// 命令对象
		ps.setInt(1, v.getUserId());
		ps.setTimestamp(2, new Timestamp(v.getVisitTime().getTime())); // data类得到时间
																		// 用户进来时间
		if (v.getLeftTime() != null) {
			ps.setTimestamp(3, new Timestamp(v.getLeftTime().getTime())); // data类得到时间
																			// 用户出去时间
		} else {
			ps.setTimestamp(3, null); // data类得到时间 用户出去时间
		}
		ps.setString(4, v.getIp()); // IP地址
		ps.setString(5, v.getComeFrom());
		ps.executeUpdate(); // 提交 把信息保存起来了
		// 拿到最大ID
		sql = "select max(id) from visitors";
		ps = conn.prepareStatement(sql); // 命令对象
		ResultSet rs = ps.executeQuery();// 这个是有返回值的
		rs.next(); // 拿到的只有一行 指针往后挪动一行
		// conn.close();
		return rs.getInt(1); // 第一个 执行结果只有一行一列
	}
	public ArrayList<Visitor> getVisitiors() throws SQLException, NamingException {
		// 防止卡死 每次用完就关掉
		if (conn.isClosed()) {
			conn = DBLib.getConnection();
		}
		sql = "select * from visitors"; // 查询这个表
		ps = conn.prepareStatement(sql);
		rs = ps.executeQuery();
		ArrayList<Visitor> al = new ArrayList<Visitor>();
		while (rs.next()) {
			Visitor v = new Visitor();
			v.setId(rs.getInt(1));
			v.setUserId(rs.getInt(2));
			v.setVisitTime(rs.getTimestamp(3));
			v.setLeftTime(rs.getTimestamp(4));
			v.setIp(rs.getString(5));
			v.setComeFrom(rs.getString(6));
			al.add(v);
		}
		conn.close();
		return al;
	}

	public void updateVisitor(Visitor v) throws SQLException, NamingException {
		// 防止卡死 每次用完就关掉
		if (conn.isClosed()) {
			conn = DBLib.getConnection();
		}
		sql = "update visitors set lefttime=?,userid=? where id=?"; // 根据ID得到
																	// 俩个信息
		ps = conn.prepareStatement(sql);
		if (v.getLeftTime() == null) {
			ps.setTimestamp(1, null);
		} else {
			ps.setTimestamp(1, new Timestamp(v.getLeftTime().getTime()));
		}
		ps.setInt(2, v.getUserId());
		ps.setInt(3, v.getId());
		ps.executeUpdate(); // 提交
		conn.close();
	}

	public ArrayList<Visitor> getPagedData() throws SQLException, NamingException { // 获取本页的数据
																					// 防止卡死
																					// 每次用完就关掉
		if (conn.isClosed()) {
			conn = DBLib.getConnection();
		}
		sql = "select * from visitors limit " + (pageNo - 1) * pageSize + "," + pageSize; // 查询这个表
		ps = conn.prepareStatement(sql);
		rs = ps.executeQuery();
		ArrayList<Visitor> al = new ArrayList<Visitor>();
		while (rs.next()) {
			Visitor v = new Visitor();
			v.setId(rs.getInt(1));
			v.setUserId(rs.getInt(2));
			v.setVisitTime(rs.getTimestamp(3));
			v.setLeftTime(rs.getTimestamp(4));
			v.setIp(rs.getString(5));
			v.setComeFrom(rs.getString(6));
			al.add(v);
		}
		conn.close();
		return al;
	}

	// 计算这个表中有多少条数据
	public void computePageCount() throws SQLException, NamingException {
		// 防止卡死 每次用完就关掉
		if (conn.isClosed()) {
			conn = DBLib.getConnection();
		}
		sql = "select count(*) from visitors"; // 计算这个表中有多少条数据
		ps = conn.prepareStatement(sql); // 提交数据
		rs = ps.executeQuery(); // 执行
		rs.next(); // 结果是一行一列 下一行记录 及第一行
		pageCount = rs.getInt(1);
		if (pageCount % pageSize == 0) {
			pageCount = pageCount / pageSize;
		} else {
			pageCount = pageCount / pageSize + 1;
		}
		conn.close();
	}

	public int getPageNo() {
		return pageNo;
	}

	public void setPageNo(int pageNo) {
		this.pageNo = pageNo;
	}

	public int getPageSize() {
		return pageSize;
	}

	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}

	public int getPageCount() {
		return pageCount;
	}
}

LogListener 监听器

package common;

import javax.servlet.ServletContextAttributeEvent;
import javax.servlet.ServletContextAttributeListener;
import javax.servlet.ServletRequestAttributeEvent;
import javax.servlet.ServletRequestAttributeListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import org.apache.log4j.*;
/**
 * Application Lifecycle Listener implementation class LogListener
 *
 */
@WebListener
public class LogListener implements ServletContextAttributeListener, HttpSessionAttributeListener, ServletRequestAttributeListener {
/*  ServletRequestListener 监听访问网页的情况(什么时候开始请求一个网页,什么时候请求结束,中间的时间间隔是服务器处理请求的时间。)
    requestInitialized,requestDestroyed
	HttpSessionListener    监听访客什么时候来,什么时候走
	sessionCreated,sessionDestroyed
	ServletContextListener 监听服务器什么时候启动,什么时候停止
*/
	//private static Logger log=Logger.getLogger(Logger.class);
	//private static Logger log=Logger.getLogger("common.LogListener");
	private static Logger log=LogManager.getLogger(LogListener.class.getName());
    /**
     * Default constructor. 
     */
    public LogListener() {
        // TODO Auto-generated constructor stub
    	//PropertyConfigurator.configure("log4j.properties");
    }

	/**
     * @see ServletContextAttributeListener#attributeAdded(ServletContextAttributeEvent)
     */
    public void attributeAdded(ServletContextAttributeEvent arg0)  { 
         // TODO Auto-generated method stub
    	log.debug("添加一个application属性!属性名为:"+arg0.getName()+",值为:" + arg0.getValue());
    	log.error("这只是测试,其实没用报错!");
    	log.log(Level.ERROR, "这是第二次测试!");
    }

	/**
     * @see ServletContextAttributeListener#attributeRemoved(ServletContextAttributeEvent)
     */
    public void attributeRemoved(ServletContextAttributeEvent arg0)  { 
         // TODO Auto-generated method stub
    }

	/**
     * @see ServletRequestAttributeListener#attributeRemoved(ServletRequestAttributeEvent)
     */
    public void attributeRemoved(ServletRequestAttributeEvent arg0)  { 
         // TODO Auto-generated method stub
    }

	/**
     * @see ServletRequestAttributeListener#attributeAdded(ServletRequestAttributeEvent)
     */
    public void attributeAdded(ServletRequestAttributeEvent arg0)  { 
         // TODO Auto-generated method stub
    }

	/**
     * @see ServletRequestAttributeListener#attributeReplaced(ServletRequestAttributeEvent)
     */
    public void attributeReplaced(ServletRequestAttributeEvent arg0)  { 
         // TODO Auto-generated method stub
    }

	/**
     * @see HttpSessionAttributeListener#attributeAdded(HttpSessionBindingEvent)
     */
    public void attributeAdded(HttpSessionBindingEvent arg0)  { 
         // TODO Auto-generated method stub
    }

	/**
     * @see HttpSessionAttributeListener#attributeRemoved(HttpSessionBindingEvent)
     */
    public void attributeRemoved(HttpSessionBindingEvent arg0)  { 
         // TODO Auto-generated method stub
    }

	/**
     * @see HttpSessionAttributeListener#attributeReplaced(HttpSessionBindingEvent)
     */
    public void attributeReplaced(HttpSessionBindingEvent arg0)  { 
         // TODO Auto-generated method stub
    }

	/**
     * @see ServletContextAttributeListener#attributeReplaced(ServletContextAttributeEvent)
     */
    public void attributeReplaced(ServletContextAttributeEvent arg0)  { 
         // TODO Auto-generated method stub
    }
	
}

MyListener监听器

package common;

import java.sql.SQLException;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;

import javax.naming.NamingException;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import myhis.History;
import myhis.HistoryDAO;
import myvisit.*;

/**
 * Application Lifecycle Listener implementation class MyListener
 *
 */

@WebListener
public class MyListener implements ServletContextListener, HttpSessionListener, ServletRequestListener {
	HttpServletRequest request;
    /**
     * Default constructor. 
     */
    public MyListener() {
        // TODO Auto-generated constructor stub
    }

	/**
     * @see HttpSessionListener#sessionCreated(HttpSessionEvent)
     */
    public void sessionCreated(HttpSessionEvent arg0)  { 
         // TODO Auto-generated method stub
    	//session开始时设置session过期时间   
    	HttpSession session=arg0.getSession();                //拿到 session
    	session.setMaxInactiveInterval(10);                 //参数是秒 
    	Visitor v=new Visitor();
    	v.setIp(request.getRemoteAddr());  //得到IP地址
    	v.setComeFrom(request.getHeader("referer"));//得到来访地址
    	v.setVisitTime(new Date());       //得到来访时间
    	VisitorDAO dao;                   //保存到数据库中
    	int id=0;
		try {
			dao = new VisitorDAO();   //把用户保存,并且拿到ID
		   	id=dao.saveVisitor(v);
		} catch (NamingException | SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		v.setId(id);   				  //重新写到
		//保存到在线用户列表中,保存session ID 访问者信息
		ServletContext application=arg0.getSession().getServletContext();  //拿到 application
		@SuppressWarnings("unchecked")                        //压制警告
		HashMap<String, Visitor> map=(HashMap<String, Visitor>) application.getAttribute("ONLINE");  //服务器启动时给空
		map.put(session.getId(),v);							  //得到信息
	 //   application.setAttribute("ONLINE", map);              //提交服务器  
	    session.setAttribute("USER", v);                      //通过 session id 得到 当前用户存起来
    }

	/**
     * @see ServletRequestListener#requestDestroyed(ServletRequestEvent)
     * ServletRequestListener 监听访问网页的情况(什么时候开始请求一个网页,什么时候请求结束,中间的时间间隔是服务器处理请求的时间。)
     */
    public void requestDestroyed(ServletRequestEvent arg0)  { 
         // TODO Auto-generated method stub
    	//结束
    }

	/**
     * @see ServletRequestListener#requestInitialized(ServletRequestEvent)
     */
    public void requestInitialized(ServletRequestEvent arg0)  { 
         // TODO Auto-generated method stub
    	//开始
    	request=(HttpServletRequest) arg0.getServletRequest();
    	History his=new History();
    	his.setVisitTime(new Date());
    	his.setUrl(request.getRequestURI().toString());  //某一次访问
    	HttpSession session =request.getSession();
    	Visitor v=(Visitor)session.getAttribute("USER"); //之前已经保存了 直接得到
    	his.setVisitId(v.getId()); // 保存访问记录表上面
    	 HistoryDAO dao;
		try {//保存起来  还要提取出来显示
			dao = new HistoryDAO();
			 dao.saveHistory(his);
		} catch (NamingException | SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	
    }

	/**
     * @see HttpSessionListener#sessionDestroyed(HttpSessionEvent)
     * HttpSessionListener    监听访客什么时候来,什么时候走
     */
    public void sessionDestroyed(HttpSessionEvent arg0)  { 
         // TODO Auto-generated method stub
    			ServletContext application=arg0.getSession().getServletContext();  //拿到 application
    	    	@SuppressWarnings("unchecked")
    			HashMap<String, Visitor>map=(HashMap<String, Visitor>)application.getAttribute("ONLINE");
    	    	String id=arg0.getSession().getId();                 //拿到当前Session ID
    	    	//删除用户之前,先改当前用户在数据离开的时间
    	    	//当前用户设置离开时间
    	    	Visitor v=map.get(id); //拿到ID
    	    	v.setLeftTime(new Date());    //拿到离开时间传进去
    	    	VisitorDAO dao;
    			try {
    				dao = new VisitorDAO();
    				dao.saveVisitor(v);
    			} catch (NamingException | SQLException e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			}
    			//在线用户表删除
    	    	map.remove(id); 
    	    //	application.setAttribute("ONLINE",map);
    }

	/**
     * @see ServletContextListener#contextDestroyed(ServletContextEvent)
     * ServletContextListener 监听服务器什么时候启动,什么时候停止
     */
    public void contextDestroyed(ServletContextEvent arg0)  { 
         // TODO Auto-generated method stub
    	//把当前用户在在线用户中删除
    }
	/**
     * @see ServletContextListener#contextInitialized(ServletContextEvent)
     */
    public void contextInitialized(ServletContextEvent arg0)  { 
         // TODO Auto-generated method stub
    	//防止每次都拿都一个数据 在启动时给服务器一个空,缓冲一下
    	HashMap<String, Visitor>map=new HashMap<String,Visitor>();
        ServletContext application =arg0.getServletContext();
        application.setAttribute("ONLINE", map); //拿到空信息  map引用
    }
	
}

log4j.PatternLayout 生成日志

log4j.rootLogger=debug,A1,R

    log4j.appender.A1=org.apache.log4j.ConsoleAppender
    log4j.appender.A1.Threshold=debug
    log4j.appender.A1.target=System.out
    log4j.appender.A1.layout=org.apache.log4j.PatternLayout
    log4j.appender.A1.layout.ConversionPattern=%d -%m%n

    log4j.appender.R=org.apache.log4j.FileAppender
    log4j.appender.R.Threshold=error
    log4j.appender.R.ImmediateFlush=true
    log4j.appender.R.File=d:\\HelloLog4j.log
    log4j.appender.R.Append=true
    log4j.appender.R.layout=org.apache.log4j.PatternLayout
    log4j.appender.R.layout.ConversionPattern=%d -%m%n

数据库初始化代码init.sql

 drop database if exists Visitor;
 create database Visitor DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;
 use visitor;
  create table users
  (
    ID int(4) not null primary key auto_increment,
    UserName varchar(100),
    Pwd varchar(50)  
  );
  create table visitors
  (
    ID int(4) not null primary key auto_increment,
    UserID int(4),
    VisitTime datetime,
    LeftTime datetime,
    ip varchar(50),
    comefrom varchar(100)
  );
  create table history
  (
    ID int(4) not null primary key auto_increment,
    VisitID	int(4),
    VisitTime datetime,
    Url varchar(200)
  );
   insert into users (username,pwd) values ('张三','12345678');
   insert into users (username,pwd) values ('李四','87654321');
   insert into users (username,pwd) values ('王五','abcdefg');




------------------------------------以上为完整代码-----------------------------------------
下面简单说一下,我在写这个项目遇到的问题
1.数据库无法写入,


解决方法: 把注释去掉,尤其是22行上面的注释,编译通过

2.空指针报错,在做这个项目时,空指针报错遇到不下十次了,有的是真的错误,有的是session过期错误


解决方法:重新启动,有时可以,如果还报错空指针,如上图,找到错误位置,使用其方法内的变量去调用, 解决

3.404问题 找不到网页,代码完全正确
解决方法:自己重新写个jsp,发现没问题,由于粗心,把原文件创建的位置不对,未被找到 
4.判断代码无效,但是能找得到其值,用Ajax局部刷新功能无效


解决方法:Ajax默认是异步执行,改为同步执行,执行完当前代码才可以执行其他 


5.Mysql语句报错!

解决方法: 在其标记的最后加入空格,在遇到不确定sql语句是否正确,在navicat软件查询一下,看代码是否正确

6.当一个信息被俩个IP使用时会提示报错 但直接进去,无法判断

解决方法:Ajax局部刷新 异步改为同步



7.日志报错 空指针找不到指定文件
解决方法:把在代码中定义该文件的代码禁用,因为未设置路经,找不到回报空指针错误



----------------------------------这个项目其功能全部完善-------------------------------------
PS:在我资源里面可以下载源代码,可以二次开发,前端没写,有兴趣的同学可以去二次开发
把基本功能图展示给大家 利用分页功能

主页面


在线用户

历史访客

访客记录

登录
登录信息表

登录


再次登录


工作日志

     ------------------------------------------------到此结束,感谢观看-------------------------------------------------------------


猜你喜欢

转载自blog.csdn.net/LiuY521/article/details/79156139