一、Web应用的组成结构
开发web应用时,不同类型的文件有严格的存放规则,否则不仅可能会使web应用无法访问,还会导致web服务器启动报错。
web.xml文件是整个web应用中最重要的配置文件,必须放置在WEB-INF目录中。在开发web应用时,但凡涉及到对web应用中的web资源的配置,通通是在web.xml文件中进行配置。例如:
- 某个web资源配置为网站首页
- 将servlet程序映射到某个url低智商
- 为web应用配置监听器
- 为web应用配置过滤器
web.xml配置举例:将某个web资源配置为首页
按照web应用的组成结构创建JavaWebDemo应用程序,放到webapps下面,让web服务器自动映射虚拟目录,补充web.xml(可以参考webapps下的examples中的,赋值xml头部和尾部),把首页改成自己html。
<?xml version="1.0" encoding="UTF-8"?><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/javaeehttp://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"version="3.1"metadata-complete="true"><welcome-file-list><welcome-file>home.html</welcome-file></welcome-file-list></web-app>
运行结果:
二、模拟搭建网站
2.1 基本概念
浏览器中输入https://www.baidu.com:
- URL:https://www.baidu.com
- 主机名:www.baidu.com
- 域名:baidu.com,域名下面可以搭建多个主机,比如www服务器、mail服务器
2.2 web资源访问流程
简要说明两点:
1. 如果在hosts文件中查询到主机对应的ip,就不会再去DNS服务器查询
2. 主机名有两个作用
1)通过DNS服务器查询服务器的IP
2)访问服务器时告诉要访问的资源在哪个主机下(连接服务器用的是IP)
2.3 配置虚拟主机
1. 修改server.xml,增加一个新的主机名site:
<Host name="site" appBase="webapps"unpackWARs="true" autoDeploy="true"><!-- SingleSignOn valve, share authentication between web applicationsDocumentation at: /docs/config/valve.html --><!--<Valve className="org.apache.catalina.authenticator.SingleSignOn" />--><!-- Access log processes all example.Documentation at: /docs/config/valve.htmlNote: The pattern used is equivalent to using pattern="common" --><Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"prefix="localhost_access_log" suffix=".txt"pattern="%h %l %u %t "%r" %s %b" /></Host>
2. 修改C:\Windows\System32\drivers\etc\hosts
# Copyright (c) 1993-2009 Microsoft Corp.
#
# This is a sample HOSTS file used by Microsoft TCP/IP for Windows.
#
# This file contains the mappings of IP addresses to host names. Each
# entry should be kept on an individual line. The IP address should
# be placed in the first column followed by the corresponding host name.
# The IP address and the host name should be separated by at least one
# space.
#
# Additionally, comments (such as these) may be inserted on individual
# lines or following the machine name denoted by a '#' symbol.
#
# For example:
#
# 102.54.94.97 rhino.acme.com # source server
# 38.25.63.10 x.acme.com # x client host# localhost name resolution is handled within DNS itself.
# 127.0.0.1 localhost
# ::1 localhost
127.0.0.1 site #这个是新增的
运行结果:
2.3 搭建网站
1. 修改默认端口号(8080端口修改为80)
2. 修改主机名(先去网上注册个域名)
3. DNS服务器上增加你的主机名和你的IP对应关系
4. 启动Tomcat服务器
5. 外界使用浏览器访问你的电脑上的web资源