- 配置环境变量
1.1配置CATALINA_HOME,指定tomcat的目录
1.2配置path,添加%CATALINA_HOME%\bin,%CATALINA_HOME%\lib
- 测试
2.2 执行startup命令
- 在Eclipse中添加tomcat
Eclipse->Preference-> Server->Runtime Environment
- 创建project,导入servlet相关jar包
- 编写代码
package web;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
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消息头
//按照key-value的方式存储的
//此方法返回key的迭代器,Enumeration是更古老的迭代器
Enumeration<String> e = req.getHeaderNames();
while(e.hasMoreElements()){
String key = e.nextElement();
String value = req.getHeader(key);
System.out.println(key+":"+value);
}
//1.3实体内容
//本案例浏览器没有给服务器传业务数据,所以实体内容为空,后面演示
//2.通过response发送请求数据
//2.1状态行
//由服务器自动填写,200表示成功
//创建服务器时间
Date date = new Date();//运行在tomcat内
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
String now = sdf.format(date);
//告诉浏览器给他发送的是什么格式的内容
//2.2消息头
res.setContentType("text/html");//"text/html"只能这么写
//向浏览器写东西
PrintWriter out = res.getWriter();
//2.3实体内容
//这里偷懒,没有拼写完整网页
out.println("<p>"+now+"</p>");
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>
<servlet>
<servlet-name>time</servlet-name>
<servlet-class>web.TimeServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>time</servlet-name>
<url-pattern>/ts</url-pattern>
</servlet-mapping>
</web-app>
测试结果