JavaSE02_Day05(上)-WebServer專案解析web.xml檔案、重構setEntity方法、完成註冊業務
阿新 • • 發佈:2021-07-18
一、版本八:解析web.xml檔案
在http包下新建一個類:HttpContext,使用這個類定義相關Http協議的內容。由於不同的檔案對應的Content-Type值不同,那麼在HttpContext類中定義一個Map。 使用Tomcat安裝目錄的下的conf/web.xml檔案,將裡面配置的所有媒介(介質)型別都解析出來,並初始化HttpContext中mimeMapping的這個Map,使得我們的WebServer也能支援所有的媒介(介質)型別。
步驟1:在專案的pom.xml檔案新增dom4j的依賴
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>cn.tedu</groupId>
<artifactId>webserver01</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<!-- https://mvnrepository.com/artifact/dom4j/dom4j -->
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>
</dependencies>
</project>
步驟2:在專案目錄下建立一個目錄,名字為conf,將群檔案中上傳的web.xml複製進來
步驟3:編寫HttpContext類,通過解析web.xml檔案初始化mimeMapping
package cn.tedu.http;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
/**
* 解析web.xml檔案,使用其中的媒介型別
* @author cjn
*
*/
public class HttpContext {
//定義用於儲存媒介型別的Map屬性
private static Map<String, String> mimeMapping =
new HashMap<String, String>();
static {
initMime();
}
/**
* 靜態方法,用於解析web.xml檔案中的媒介型別
* @param args
*/
public static void initMime() {
/*
* 解析web.xml檔案中的媒介型別,
* 然後新增到Map屬性中
*/
try {
SAXReader reader = new SAXReader();
Document document = reader.read(new File("conf/web.xml"));
//獲取根節點
Element root = document.getRootElement();
//獲取根節點中位元組點名字是mime-mapping的節點元素
List<Element> elements = root.elements("mime-mapping");
//獲取mime-mapping節點中子節點對應的內容
for (Element e : elements) {
String key = e.elementText("extension");
String value = e.elementText("mime-type");
//將獲取到的元素資料儲存到屬性Map中
mimeMapping.put(key, value);
}