用jsp系列做WEB开发时有个显示系统运行时间的需求。没有直接方法得到这个数值,用下面方法可以实现。
设置一个Servlet使之在中间件启动时加载,将启动时间加到ServletContext中。系统运行时间为当前时间和启动时间的差。
配制
在web.xml中加入如下配制。
QdsjServlet
com.iteedu.QdsjServlet
checkSource
false
0
QdsjServlet
/servlet/QdsjServlet
关键是0这一配制。加载Servlet时会调用init()方法,在这里加想要的参数就行了。
Servlet类
public class QdsjServlet extends HttpServlet
{
public void init() throws ServletException
{
super.init();
ServletContext application = this.getServletContext();
application.setAttribute("startTime", new Date());
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
super.doGet(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
super.doPost(req, resp);
}
}
调用
String format = "系统已正常运行%s小时%s分%s秒";
Date start = (Date) this.getServletContext().getAttribute("startTime");
Long time = Calendar.getInstance().getTimeInMillis() - start.getTime();
int h = (int) (time / (60 * 60 * 1000));
int m = (int) (time / (60 * 1000)) - h * 60;
int s = (int) (time / 1000 % 60);
format = String.format(format, new Object[]{ h, m, s });