1 package test; 2 3 import org.dom4j.Document; 4 import org.dom4j.Element; 5 import org.dom4j.io.SAXReader; 6 7 import java.util.HashMap; 8 import java.util.List; 9 import java.util.Map; 10 11 /** 12 * @Create 16:16 13 */ 14 public class ReadXml2 { 15 public static void main(String[] args) throws Exception { 16 SAXReader saxReader = new SAXReader(); 17 String str = "/test2";//从控制台输入,表示url-pattern的值 18 Document document = saxReader.read("src/web.xml"); 19 Element rootElement = document.getRootElement(); 20 List<Element> servletmappingElements = rootElement.elements("servlet-mapping"); 21 List<Element> servletElements = rootElement.elements("servlet"); 22 23 Map mappingMap=new HashMap<>(); 24 //map.put("/test1","aa”); map.put("/test2","bb") 25 for (Element e1 : servletmappingElements) { 26 Element servletname = e1.element("servlet-name"); 27 Element urlpattern = e1.element("url-pattern"); 28 mappingMap.put(urlpattern.getText(),servletname.getText()); 29 } 30 Map servetmap=new HashMap(); //map.put("aa","com.atguigu.Demo1"); 31 for (Element e2 : servletElements) { 32 Element servletname = e2.element("servlet-name"); 33 Element servletclass = e2.element("servlet-class"); 34 servetmap.put(servletname.getText(),servletclass.getText()); 35 } 36 //给定的条件 37 String url="/test2"; 38 String servletname =(String) mappingMap.get(url); 39 Object o = servetmap.get(servletname); 40 System.out.println(o); 41 42 } 43 }
web.xml:
<?xml version="1.0" encoding="UTF-8" ?> <web> <servlet> <servlet-name>aa</servlet-name> <servlet-class>com.atguigu.Demo1</servlet-class> </servlet> <servlet-mapping> <servlet-name>aa</servlet-name> <url-pattern>/test1</url-pattern> </servlet-mapping> <servlet> <servlet-name>bb</servlet-name> <servlet-class>com.atguigu.Demo2</servlet-class> </servlet> <servlet-mapping> <servlet-name>bb</servlet-name> <url-pattern>/test2</url-pattern> </servlet-mapping> </web>
标签:xml,文件,servletname,Element,String,put,import,servlet,读取 From: https://www.cnblogs.com/deyo/p/17238317.html