簡單的Tomcat實現--2.3Tomcat的內建物件之service
阿新 • • 發佈:2020-08-05
service
-
在配置檔案中新增service標籤
-
<?xml version="1.0" encoding="UTF-8"?> <Server> <Service name="Catalina"> <Engine defaultHost="localhost"> <Host name="localhost"> <Context path="/b" docBase="d:/Java/JavaProjects/Jerrymice/webapps/b" /> </Host> </Engine> </Service> </Server>
-
service標籤是Engine標籤的父標籤
-
-
建立Service類
-
package jerrymice.catalina; import jerrymice.util.ServerXmlUtil; /** * @author :xiaosong * @description:TODO * @date :2020/8/5 10:21 */ public class Service { private final String name; private final Engine engine; private Server server; public Service(Server server){ this.server = server; this.name = ServerXmlUtil.getServiceName(); this.engine = new Engine(this); } public Engine getEngine(){ return engine; } public String getName(){ return name; } public Server getServer(){ return server; } }
-
-
在Engine類中新增Service屬性,並加入到構造方法中
-
package jerrymice.catalina; import cn.hutool.log.LogFactory; import jerrymice.util.ServerXmlUtil; import java.util.List; /** * @author :xiaosong * @description:TODO * @date :2020/8/4 22:59 */ public class Engine { private final String defaultHost; private List<Host> hosts; private Service service; public Engine(Service service){ this.defaultHost = ServerXmlUtil.getEngineDefaultHost(); this.hosts = ServerXmlUtil.getHosts(this); this.service = service; checkDefault(); } /** * 檢查時候存在預設的host,如果不存在的話丟擲異常 */ private void checkDefault(){ if (getDefaultHost() == null) { LogFactory.get().error("the default host does not exist!"); throw new RuntimeException("the default host does not exist!"); } } public Host getDefaultHost(){ for (Host host : hosts) { if (defaultHost.equals(host.getName())){ return host; } } return null; } public Service getService(){ return service; } }
-
-
和上面類似的處理,在ServerXmlUtil中建立工具方法
-
public static String getServiceName(){ String name = ""; try{ Document document = Jsoup.parse(Constant.serverXmlFile, "utf-8"); Element service = document.select("Service").first(); name = service.attr("name"); }catch(IOException e){ LogFactory.get().error(e); } return name; }
-