---
title: "Tomcat"
author: "tianhei"
date: "2011-03-02T10:43:20Z"
tags: ["JSP", "JavaEE", "Servlet", "Tomcat", "Web"]
categories: ["企业架构"]
slug: "tomcat"
draft: false
lastmod: "2011-03-10T17:32:00Z"
id: 937858
url: "https://tianhei.iteye.com/blog/937858"
---

一、简介

Tomcat是一个web服务器也是Servlet/JSP容器。web项目的运行要加载到这个容器中才行。

 

二、Tomcat目录说明

bin：启动关闭脚本

conf：配置文件

lib：tomcat运行需要的库文件

logs：tomcat运行的日志文件

webapp：web程序的发布目录

work：存放jsp编译后的class文件

 

三、基于Tomcat的web开发例子

1、在webapp下新建web应用名称，例如：chunming

2、在chunming下新建WEB-INF目录和cm.jsp文件

3、在WEB-INF下新建web.xml文件和/classes/com/vmn目录

4、把编译后的class文件放到/classes/com/vmn下

web.xml如下：

```
<?xml version="1.0" encoding="ISO-8859-1"?>

<web-app xmlns="http://java.sun.com/xml/ns/javaee"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   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>Welcome to Tomcat</display-name>
  <description>
     Welcome to Tomcat
  </description>
  <servlet>
	<servlet-name>Test</servlet-name>
	<servlet-class>com.vmn.TheServlet</servlet-class>
  </servlet>
  <servlet-mapping>
	<servlet-name>Test</servlet-name>
	<url-pattern>/cm</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
	<welcome-file>cm.jsp</welcome-file>
  </welcome-file-list>
</web-app>
```

cm.jsp如下：

```
<html>
<body>
<center>
　　Now time is: <%=new java.util.Date()%>
</center>
</body>
</html>
```

com.vmn.TestServlet如下：

```
package com.vmn;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author wangjy
 */
public class TheServlet extends HttpServlet {
    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        PrintWriter out = response.getWriter();
        out.println("<html><body><h1>This is a servlet test.</h1></body></html>");
        out.flush();
    }
}
```

 启动tomcat后，运行[http://localhost:8080/chunming](http://localhost:8080/chunming)和[http://localhost:8080/chunming/cm.jsp](http://localhost:8080/chunming/cm.jsp)时页面上出现现在时间； 运行[http://localhost:8080/chunming/cm](http://localhost:8080/chunming/cm)时出现This is a servlet test.