1. 程式人生 > >web應用和web.xml檔案

web應用和web.xml檔案

構建Web應用

手動建立一個web應用
1.任意目錄建立demo資料夾,用於建立一個web應用
2.資料夾中建立一個WEB-INF資料夾(區分大小寫)
3.在WEB-INF中建立web.xml檔案,並新增下面的程式碼(可以從Tomcat中的其他應用複製過來)

< 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"> < /web-app>

4.在WEB-INF資料夾中新增classes和lib兩個資料夾,這兩個資料夾的作用相同都是用於儲存Web應用中所需的Java類檔案。
區別:classes用於儲存單個*.class檔案,而lib用於儲存打包後的JAR檔案
5.這便形成了一個簡單的空的web應用,將web放到Tomcat中的webapps中,web應用可以自動完成部署到Tomcat
6.通常JSP檔案只需放到web應用的根目錄下

<%@ page contentType="text/html;charset=UTF-8"
language="java" errorPage=""%>
<html> <head> <title> web </title> <body> 這是一個簡單的web應用 </body> </head> </html>

配置描述符web.xml

  • 在Servlet2.5規範之前必須包含一個web.xml檔案,從Servlet3.0開始,WEB-INF路徑下的web.xml檔案不再是必須的,但建議保留該配置檔案
  • 客戶端瀏覽器無法訪問WEB-INF路徑下的任何內容
  • 在Servlet2.5規範之前,Java Web引用絕大部分元件通過web.xml檔案來配置管理,從Servlet3.0開始,也可以通過註解來配置管理Web元件

配置Web應用的首頁

使用welcome-file-first元素,該元素可以包含多個welcome-file子元素

<welcome-file-firsrt>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
</welcome-file-first>

當Web應用包含index.html檔案時,訪問的首頁為index.html,若沒有index.html檔案,則看看是否包含有index.htm檔案,若包含,則訪問的首頁為index.htm,以此類推