java 去系统运行时间,JAVA WEB获取系统运行时间

用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 });

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值