標籤:生產 gets equal else except conf cep webapp alac
1 package my.tomcat2; 2 3 import org.xml.sax.SAXException; 4 5 import javax.xml.parsers.ParserConfigurationException; 6 import javax.xml.parsers.SAXParser; 7 import javax.xml.parsers.SAXParserFactory; 8 import java.io.IOException; 9 import java.util.List;10 import java.util.Map;11 12 public class WebApp {13 private static ServletContext servletContext;14 15 static {16 try {17 //建立一個 解析工廠18 SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();19 //生產出一個 解析器20 SAXParser saxParser = saxParserFactory.newSAXParser();21 //獲得一個 文檔處理器22 WebHandler webHandler = new WebHandler();23 //需要解析哪個檔案,並且用什麼 文檔處理器 來進行處理24 saxParser.parse(Thread.currentThread().getContextClassLoader().getResourceAsStream("web.xml"), webHandler);25 26 //這裡就不需要我們手動的將 資訊 存入 Map中去27 //將 webHandler 中的 Entitys 存入到 servlet 中去28 servletContext = new ServletContext();29 Map<String, String> servlet = servletContext.getServlet();30 for(Entity temp : webHandler.getEntities()){31 servlet.put(temp.getServletName(), temp.getServletClass());32 }33 //將 WebHandler 中的 Mappings 存入到 mapping 中去34 Map<String, String> mapping = servletContext.getMapping();35 for(Mapping temp : webHandler.getMappings()){36 List<String> urls = temp.getUrlList();37 for(String str : urls){38 mapping.put(str, temp.getServletName());39 }40 }41 } catch (SAXException e) {42 e.printStackTrace();43 } catch (IOException e) {44 e.printStackTrace();45 } catch (ParserConfigurationException e) {46 e.printStackTrace();47 }48 49 }50 51 //通過 URL 擷取 Servlet,這裡用到了 多態,反射52 public static Servlet getServlet(String url) throws ClassNotFoundException, IllegalAccessException, InstantiationException {53 if (url == null || url.trim().equals("")) {54 return null;55 } else {56 String reflect = servletContext.getServlet().get(servletContext.getMapping().get(url));57 return (Servlet) Class.forName(reflect).newInstance();58 }59 }60 }
(十)——WebApp