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 //Create a parsing factory
18 SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
19 // Produce a parser
20 SAXParser saxParser = saxParserFactory.newSAXParser();
21 //Get a document processor
22 WebHandler webHandler = new WebHandler();
23 //Which file needs to be parsed, and what document processor is used for processing
24 saxParser.parse(Thread.currentThread().getContextClassLoader().getResourceAsStream("web.xml"), webHandler);
25
26 //This does not require us to manually save the information into the Map.
27 //Save the Entitys in the webHandler to the 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 //Save the Mappings in the WebHandler to the 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 / / Get the Servlet through the URL, here used polymorphism, reflection
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 }
(10)--webapp