Unit01: Servlet基础 、 HTTP协议
在页面上输出当前时间
package web; 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 TimeServlet extends HttpServlet { @Override protected void service( HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { //1.使用request接收请求数据 //1.1请求行 System.out.println( "请求方式:"+req.getMethod()); System.out.println( "访问路径:"+req.getServletPath()); System.out.println( "协议类型:"+req.getProtocol()); //1.2消息头 //1.3实体内容 //2.使用response发送响应数据 //获取服务器时间 Date date = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss"); String now = sdf.format(date); //告诉浏览器发送给它的是网页 res.setContentType("text/html"); //获取writer PrintWriter out = res.getWriter(); //输出网页的内容(偷懒少写点) out.println("<p>"+now+"</p>"); //关闭writer out.close(); } }
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5"> <display-name>servlet1</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> <!-- 1.给Servlet取一个别名 --> <servlet> <servlet-name>time</servlet-name> <servlet-class>web.TimeServlet</servlet-class> </servlet> <!-- 2.给Servlet取一个网络访问路径(网名) --> <servlet-mapping> <servlet-name>time</servlet-name> <url-pattern>/ts</url-pattern> </servlet-mapping> </web-app>