在配置文件中添加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;
}
简单的Tomcat实现--2.3Tomcat的内置对象之service
原文:https://www.cnblogs.com/xsliu/p/13441372.html