首页 > 技术文章 > Tomcat基本使用

youngchaolin 2019-09-06 00:22 原文

Java Web项目有多种服务器的选择,比较常见的是Tomcat,WebLogic和WebSphere,接下来主要了解Tomcat。另外Web项目需要有HTTP的知识,这里对request和response消息也进行基本了解。

Web服务器简单对比

(1)Tomcat:免费,是apache下产品,支持全部的JSP以及Servlet规范,现在也开始支持其他JavaEE规范,如可以支持JDBC。

(2)WebLogic:收费,BEA公司产品,现在已被IBM收购,支持全部的JavaEE规范。

(3)WebSphere:收费,IBM公司产品,也支持全部的JavaEE规范。

Tomcat安装

这里使用的是Window系统,Tomcat官网下载zip压缩文件后直接解压到指定目录即完成安装,本次使用的版本是Tomcat 7。如果是Linux系统注意下载tar.gz文件,这个文件使用tar -zxvf命令解压到目标文件夹后即完成安装。安装Tomcat需要注意Java环境变量的配置,Tomcat启动会读取JAVA_HOME这个变量,注意名字要写成一样,否则读取不到。

Tomcat目录

 

如上图是Tomcat安装完后的目录,其各个部分主要功能如下:

(1)bin:主要存放脚本文件,如启动Tomcat和关闭Tomcat。

(2)conf:存放Tomcat服务器的配置文件,比较常用的有server.xml和web.xml。

(3)lib:存放Tomcat服务器的支持jar包

(4)logs:存放Tomcat在使用过程中的各种日志,主要使用catalina.log日志,这里面包含所有的日志。

(5)temp:存放Tomcat运行时产生的临时文件,一般少用

(6)webapps:存放web应用的目录,里面存放的是一个完整项目文件夹,或者能供外界访问的web资源目录,这里面的文件夹交给tomcat管理的过程,叫做虚拟目录的映射。

(7)work:tomcat工作目录。

虚拟主机及虚拟目录映射

tomcat可以认为是一台真实的主机,而一个网址对应就是一台虚拟主机,需区别虚拟机(搭建linux使用vm)。

虚拟主机

一个tomcat可以认为是一台真实主机.在一台真实主机中可以配置多个站点,这些站点在访问者看来访问他们就像在访问各自独立的主机一样,所以我们可以认为这些站点都运行在tomcat这台真实主机当中的各自的虚拟主机当中,一个网站就可以认为是一个虚拟主机。

web应用概念

一个虚拟主机中会有很多的web资源,但是web资源不能直接交给虚拟主机管理,需要按照一定方式组织成web应用虚拟主机才能使用。一般来说我们会按照功能将某一功能相关的所有的web资源组织成一个web应用后再交给虚拟主机。web应用里一般分为静态资源和动态资源,静态资源一般可以直接访问到,动态资源需要通过访问才能获取。

虚拟目录映射

所谓虚拟目录映射,就是将web目录交给web服务器管理,通过访问web服务器可以访问到文件夹里的资源,有三种方法可以实现虚拟目录映射,为了测试准备了一个简单的页面sou.html,可以通过访问服务器来获取这个网页的信息。

准备的网页代码:

 1 <!DOCTYPE html>
 2 <html lang="en" xmlns="http://www.w3.org/1999/xhtml">
 3 <head>
 4     <meta charset="utf-8" />
 5     <title>Web应用虚拟目录映射</title>
 6     <!--添加简单样式-->
 7     <style type="text/css">
 8     div{
 9         font-size:20px;
10         width:100%;
11         height:30px;
12         text-align:center;
13     }
14     #div1{
15         margin-top:150px;
16     }
17     #div2{
18         margin-top:10px;
19     }
20     #div3{
21         margin-top:10px;
22     }
23     #t1{
24         width:300px;
25         height:30px;
26         border:1px solid grey;
27     }    
28     #t2{
29         width:100px;
30         height:35px;
31         font-family:'微软雅黑';
32         font-size:20px
33     }
34     </style>
35 </head>
36 <body>
37     <form href="localhost:80" method="GET">
38     <div id="div1">搜一下~要你所想!</div>
39     <div id="div2"><input id="t1" type="text" name="question"></input></div>
40     <div id="div3"><input id="t2" type="submit" value="提交"></input><div>
41     </form>
42 </body>
43 </html>

(1)配置conf/server.xml,修改path和docBase属性,如果path里不写内容,则这个web应用就是这个虚拟主机的默认web应用,如下hello目录是虚拟路径,而真实路径则是D盘目录下的HtmlScript。

1 <Context path="/hello" docBase="D:/HtmlScript" />

测试访问hello,获取它下面的sou.html静态资源。

(2)在tomcat/conf/引擎名/虚拟主机名 目录下新建一个xml文件,其中xml文件的名字就是虚拟路径,类似上面的path,并在xml里配置<Context docBase='' />,这个就是真实路径。其中引擎名这里使用的是catalina,虚拟主机名就是localhost。

 xml中配置的就是真实路径,注意xml文件的名字需写成hello,如果要设置此web应用为虚拟主机的默认web应用,需将名字设置为ROOT。

1 <?xml version="1.0" encoding="utf-8" ?>
2 <Context docBase="D:/HtmlScript" />

将前面配置的server.xml注释掉,测试访问hello下的资源,发现依然能访问,可参考上图。

(3)这种方法比较好设置,后面的测试也是基于这种设置来进行,只需要在webapp目录下新建一个目录,目录名就是虚拟路径名,目录里的内容就是上文的sou.html,其他无需配置,测试发现也可以访问到静态资源。

 

同样的如果将hello名字修改为ROOT就是将次应用设置为虚拟路径的默认web应用。如tomcat刚开始连接的那个地址,就是ROOT,可以看到里面包含熟悉的静态资源。

web应用目录结构

正常来说web应用是有规定的目录结构的,如下是按照web应用目录规则自定义的一个目录,可以看到在boe/ROOT目录下面,包含一个sou.html,静态资源就放在这个层级,跟它平级的是WEB-INF,它里面存放的是静态资源,如图有两个文件夹和一个web.xml文件,其中classes存放编译后的class文件,lib存放运行需要的jar包,而web.xml则是整个web应用的配置文件,里面可以配置主页、配置过滤器filter,监听器listener等。

参考第三种配置虚拟目录映射的方式,这里需要在conf/server下添加配置一个host标签,让用户登录这个host时默认访问boe,类似访问localhost默认访问webapp,并且将boe下目录文件名设置为ROOT,代表这个应用为这个虚拟主机下的默认web应用。

conf/server.xml里添加配置

 1 <Engine name="Catalina" defaultHost="localhost">
 2 
 3       <!--For clustering, please take a look at documentation at:
 4           /docs/cluster-howto.html  (simple how to)
 5           /docs/config/cluster.html (reference documentation) -->
 6       <!--
 7       <Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"/>
 8       -->
 9 
10       <!-- Use the LockOutRealm to prevent attempts to guess user passwords
11            via a brute-force attack -->
12       <Realm className="org.apache.catalina.realm.LockOutRealm">
13         <!-- This Realm uses the UserDatabase configured in the global JNDI
14              resources under the key "UserDatabase".  Any edits
15              that are performed against this UserDatabase are immediately
16              available for use by the Realm.  -->
17         <Realm className="org.apache.catalina.realm.UserDatabaseRealm"
18                resourceName="UserDatabase"/>
19       </Realm>
20       <!-- 虚拟主机域名 -->
21       <Host name="localhost"  appBase="webapps"
22             unpackWARs="true" autoDeploy="true">
23             
24 
25         <!-- SingleSignOn valve, share authentication between web applications
26              Documentation at: /docs/config/valve.html -->
27         <!--
28         <Valve className="org.apache.catalina.authenticator.SingleSignOn" />
29         -->
30 
31         <!-- Access log processes all example.
32              Documentation at: /docs/config/valve.html
33              Note: The pattern used is equivalent to using pattern="common" -->
34         <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
35                prefix="localhost_access_log." suffix=".txt"
36                pattern="%h %l %u %t &quot;%r&quot; %s %b" />
37             
38       <!-- 自定义虚拟主机名称,也是域名 -->
39        <Host name="www.boe.com" appBase="boe"/>
40       
41     </Engine>

为了能让访问www.boe.com能直接变成访问主机的tomcat服务器,还需修改hosts文件,添加本地ip解析。

 1 # Copyright (c) 1993-2009 Microsoft Corp.
 2 #
 3 # This is a sample HOSTS file used by Microsoft TCP/IP for Windows.
 4 #
 5 # This file contains the mappings of IP addresses to host names. Each
 6 # entry should be kept on an individual line. The IP address should
 7 # be placed in the first column followed by the corresponding host name.
 8 # The IP address and the host name should be separated by at least one
 9 # space.
10 #
11 # Additionally, comments (such as these) may be inserted on individual
12 # lines or following the machine name denoted by a '#' symbol.
13 #
14 # For example:
15 #
16 #      102.54.94.97     rhino.acme.com          # source server
17 #       38.25.63.10     x.acme.com              # x client host
18 
19 # localhost name resolution is handled within DNS itself.
20 #    127.0.0.1       localhost
21 #    ::1             localhost
22 176.222.10.128 www.boe.com

接下来测试访问www.boe.com,发现能正常访问。

发现也能展示sou.html页面,但是网址里并没有显示要访问这个资源,原来这个是在WEB-INF下web.xml配置的结果,里面将sou.html设置为了主页。 

以下为boe/ROOT/WEB-INF/web.xml里的配置内容。

 1  1 <?xml version="1.0" encoding="ISO-8859-1"?>
 2  2 <!--
 3  3  Licensed to the Apache Software Foundation (ASF) under one or more
 4  4   contributor license agreements.  See the NOTICE file distributed with
 5  5   this work for additional information regarding copyright ownership.
 6  6   The ASF licenses this file to You under the Apache License, Version 2.0
 7  7   (the "License"); you may not use this file except in compliance with
 8  8   the License.  You may obtain a copy of the License at
 9  9 
10 10       http://www.apache.org/licenses/LICENSE-2.0
11 11 
12 12   Unless required by applicable law or agreed to in writing, software
13 13   distributed under the License is distributed on an "AS IS" BASIS,
14 14   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 15   See the License for the specific language governing permissions and
16 16   limitations under the License.
17 17 -->
18 18 
19 19 <web-app xmlns="http://java.sun.com/xml/ns/javaee"
20 20   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
21 21   xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
22 22                       http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
23 23   version="3.0"
24 24   metadata-complete="true">
25 25 
26 26     <welcome-file-list>
27 27         <welcome-file>sou.html</welcome-file>
28 28         <!--<welcome-file>index.htm</welcome-file>
29 29         <welcome-file>index.jsp</welcome-file>-->        
30 30     </welcome-file-list>
31 31 </web-app>

需要注意的是,上面三种添加目录映射的方法,后面两种支持热部署,即tomcat在运行的阶段也可以修改的意思。

下图是request里的信息和response里的信息,可以分别看一下。

请求以及请求参数,Http请求内容包括请求行、请求头、一个空行和包含请求的参数的实体内容。

 

 

 响应内容,包含状态行、响应头、一个空行和返回的响应内容,一般为html页面信息,或者AJAX数据信息。

配置www.boe.com的简单应用

现在有一个需求,就是在上面的基础上,完成搭建www.boe.com,将其作为缺省虚拟主机使用,此外发布两个web应用,一个为搜索功能,一个为邮箱功能,并且将搜索功能作为缺省web应用,还需要为缺省web应用配置缺省主页

分析一下上面需求,需完成三个部分的配置:

(1)配置缺省虚拟主机,需要conf/server.xml中配置

(2)有两个web应用,需配置其中一个为缺省web应用,直接修改搜索功能目录名为ROOT

 修改后的目录图,里面包含我自己写的class文件,后面测试servlet用的先不管:

(3)给缺省的web应用配置一个缺省主页,设置WEB-INF/web.xml下的welcome-file-list标签

这样就完成了以上的需求。

配置一个Servlet到web.xml

Servlet属于JavaEE规范,是sun公司用于开发动态web资源的技术,本质上是java代码,需存放到servlet容器(能够存储和运行web资源的环境)中才能运行,这里使用tomcat作为容器。这里写一个简单的servlet,它需要实现GenericServlet,编译后将其放置到WEB-INF/classes文件夹下,放完后就是上面图片的效果,其内容如下,即向浏览器输出一句话。

 1 package com.boe.servlet;
 2 import java.io.*;
 3 import javax.servlet.*;
 4 public class FirstServlet extends GenericServlet{//使用GenericServlet因为它只需要实现一个抽象方法service
 5     
 6      public void service(ServletRequest req, ServletResponse res) throws ServletException, java.io.IOException{
 7         res.getWriter().write("boe is the best enterprise in the world!"); 
 8      }
 9     
10 }

配置WEB-INF/web.xml,注册自己写的servlet

1     <!--配置自定义servlet-->
2     <servlet>
3         <servlet-name>firstServlet</servlet-name>
4         <servlet-class>com.boe.servlet.FirstServlet</servlet-class>
5     </servlet>
6     <servlet-mapping>
7         <servlet-name>firstServlet</servlet-name>
8         <url-pattern>/firstServlet</url-pattern>
9     </servlet-mapping>

在前面的基础上,www.boe.com已配置成缺省主机,直接测试访问127.0.0.1/firstServlet,成功!

以上为Tomcat的基本使用,记录一下。

推荐阅读