如果有这样的需求,请记录所有用户访问某个页面的次数。
您可能首先想到的是在此控制器中定义静态成员,然后在相应的操作中自行增加。 但是,如果Tomcat或其他服务重新启动,则会出现无法保存此值的问题。
当然,也可以直接保存到数据库中,但因此,单独创建表并访问数据库以供以后用户访问相应的页面就有点不值了。
使用自定义ServletContextListener可以轻松完成此操作。 想法如下。
1、web APP应用程序启动时,从文件中读取计数器的值,并将表示计数器的Counter对象保存在web APP应用程序的范围内。 存储计数器的文件的路径为helloapp/count/count.txt。
2、在web APP结束时,将web APP范围内的计数器值保存在count.txt文件中。
publicclassmyservletcontextlistenerimplementsservletcontextlistener { publicvoidcontextinitialized (servletcontexteventsce } )
system.out.println (helloappapplicationisinitialized.' ); //获取servlet上下文的对象
servletcontextcontext=SCE.getservletcontext (; 从try{//文件读取计数器值
bufferedreaderreader=newbufferedreader (context )。
getresourceasstream ('/count/count.txt ' ); int count=integer.parseint (reader.readline () );
reader.close (; //将计数器对象保存到web APP范围
context.setattribute('count ',count );
}catch(ioexceptione ) {
e .打印任务跟踪(;
}
} publicvoidcontextdestroyed (servletcontexteventsce ) )
system.out.println (helloappapplicationisdestroyed.' ); //获取servlet上下文的对象
servletcontextcontext=SCE.getservletcontext (;//从web APP范围获取计数器
intcount=(int ) context.getattribute('count ); if (计数!=0) try(/将计数器的值写入count.txt文件
string file path=context.get realpath ()/count;
filepath=filepath '/count.txt ';
printwriter pw=new printwriter (文件路径;
pw.println(count;
pw.close (;
}catch(ioexceptione ) {
e .打印任务跟踪(;
}
}
}
}
也在web.xml文件中设置
servletcontexttest.myservletcontextlistener
可以从ServletContext对象检索保存的count值。