案例需求:编写Servlet,当浏览器发送systemTime.do请求时,返回yyyy-MM-dd hh:mm:ss格式的日期字符串并在浏览器中显示。
案例实现:
● Servlet对应的Java类源代码:
package com.xdl.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class XdlSystemTime extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest req,
HttpServletResponse resp) throws ServletException, IOException {
// 获取系统当前时间 yyyy-MM-dd hh:mm:ss
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
String dateStr = sdf.format(date);
//写给浏览器
PrintWriter pw = resp.getWriter();
pw.write("<h1>" + dateStr + "</h1>");
pw.close();
}
}
● web.xml配置
<servlet>
<servlet-name>XdlSystemTime</servlet-name>
<servlet-class>com.xdl.servlet.XdlSystemTime</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>XdlSystemTime</servlet-name>
<url-pattern>/systemTime.do</url-pattern>
</servlet-mapping>