Tomcat 源码分析1 之 构建maven项目

2017-05-09  本文已影响0人  江之北

本文是Tomcat源码分析系列文章的第一篇,主要讲如何下载tomcat源码并且到导入到ide中,最终能够在本地运行起来,以便以后的调试与分析。本系列文章主要以tomcat80源码为基础,代码地址在https://github.com/apache/tomcat80
  tomcat默认是使用ant来构建的,官方参考地址:https://tomcat.apache.org/tomcat-8.0-doc/building.html, 平常多使用maven,在google搜索一下,没找到合适的使用maven构建的教程,于是就自己尝试下,从下载源码到能在ide调试起来倒也不难,写这篇文章备忘下,也作为tomcat源码分析系列的开篇。

1、代码下载
git clone https://github.com/apache/tomcat80.git
2、在eclipse 或者 intellij idea中新建一个maven项目。
把刚下载的tomcat80目录下的java 文件夹内的orgjavax文件夹拷贝到maven项目的src/main/java目录下。
pom.xml中添加如下依赖
<dependency> <groupId>org.apache.ant</groupId> <artifactId>ant</artifactId> <version>1.8.2</version> </dependency> <dependency> <groupId>org.eclipse.jdt.core.compiler</groupId> <artifactId>ecj</artifactId> <version>4.6.1</version> </dependency> <dependency> <groupId>javax.xml</groupId> <artifactId>jaxrpc-api</artifactId> <version>1.1</version> </dependency> <dependency> <groupId>wsdl4j</groupId> <artifactId>wsdl4j</artifactId> <version>1.6.2</version> </dependency>

3、在项目中分别建立conf 、webapps 、 lib 目录。并将tomcat80目录conf下的所有文件拷贝到conf目录中。
里面主要包含tomcat的启动参数等配置。

4、在webapps中新建ROOT/WEB-INF 目录,并添加web.xml文件。
里面添加如下内容

<?xml version="1.0" encoding="ISO-8859-1"?>
<!-- Licensed to the Apache Software Foundation (ASF) under one or more contributor 
    license agreements. See the NOTICE file distributed with this work for additional 
    information regarding copyright ownership. The ASF licenses this file to 
    You under the Apache License, Version 2.0 (the "License"); you may not use 
    this file except in compliance with the License. You may obtain a copy of 
    the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required 
    by applicable law or agreed to in writing, software distributed under the 
    License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 
    OF ANY KIND, either express or implied. See the License for the specific 
    language governing permissions and limitations under the License. -->
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                      http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
    version="3.1" metadata-complete="true">

    <display-name>Welcome to Tomcat</display-name>
    <description>
     Welcome to Tomcat
  </description>
    <servlet>
        <servlet-name>myServlet</servlet-name>
        <servlet-class>my.MyServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>myServlet</servlet-name>
        <url-pattern>/my</url-pattern>
    </servlet-mapping>
</web-app>

PS: 如果不想自己新建项目的话,直接把tomcat80目录下的webapps下的所有文件夹拷贝到maven项目的webapps目录下也可以,web.xml里面有一些示例配置,要稍作修改。

5、添加自己的servlet
新建一个package 名为my
在里面新建一个叫MyServlet的servlet即可。当然 包名 和 url-pattern都可以自定义。

6、启动项目
通过 org.apache.catalina.startup.Bootstrap 的main方法即可启动。
打开浏览器,通过 http://localhost:8080/my 即可访问到自己的servlet。

上一篇下一篇

猜你喜欢

热点阅读