在写一个监听器更新当前页面访问浏览次数时,因为需要在服务器停止时将浏览次数保存在文件中,方便下次调用。
为了保存多个页面的数据,使用了Map集合。保存的时候经过检查文件,可以确定没有发生任何错误,但是在重启TOMCAT时,始终会产生一个EOFException异常,无法读取到任何内容。
经过各种反复尝试、修改、删除都无法解决,百度了许多也似乎跟这个都没多大关系。然后因为下课放学,所以就此作罢,等待下个星期一询问老师。
然后今天想起来这个错误,总觉得心里不太舒服,犹豫了还是继续尝试修改正确,又是一番修改和百度,最后终于在一个CSDN博客中找到了解决办法,尝试后完美运行。
具体错误就是因为我先初始化了ObjectOutputStream对象,再初始化ObjectInputStream对象,但是它俩不是在用一个方法中调用各自相关的方法,所以一直引发该错误。在该博客一个截图是这样说的:然后检查了一下我的代码,确实是先初始化的ObjectOutputStream对象,同时服务器第二次启动时是先运行的readObject()方法,因此会产生EOFException异常。
修改后代码如下:
private int count;
private Map<String,Integer> map = new HashMap<>();
private File file;
public CountListener() {
file = new File("h:/map.txt");
}
public void requestInitialized(ServletRequestEvent sre) {
HttpServletRequest request = (HttpServletRequest)(sre.getServletRequest());
HttpSession session = request.getSession();
ServletContext application = request.getServletContext();
if( request.getServletPath().contains(".jsp")) {
String pageURI = request.getServletPath().substring(1, request.getServletPath().lastIndexOf("."));
if(!map.containsKey(pageURI)){
map.put(pageURI, 0);
}
count = map.get(pageURI);
long nowTime = System.currentTimeMillis();
long befTime = nowTime;
if(session.getAttribute(pageURI)!=null) {
befTime = (long) session.getAttribute(pageURI);
}
if((nowTime-befTime)==0||(nowTime-befTime)>=(1000*10)) {
count++;
}
session.setAttribute(pageURI,nowTime);
application.setAttribute(pageURI, count);
map.put(pageURI, count);
}
}
//生命周期---application
public void contextInitialized(ServletContextEvent sce) {
try {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file));
if(map instanceof Object) {
map = (Map<String, Integer>) ois.readObject();
}
ois.close();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (EOFException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void contextDestroyed(ServletContextEvent sce) {
try {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file));
oos.writeObject(map);
oos.flush();
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
}