XML约束
作者:互联网
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://www.example.org/web-app_2_5" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.example.org/web-app_2_5 web-app_2_5.xsd" version="2.5"> <servlet> <servlet-name>MyServlet</servlet-name> <servlet-class>com.oracle.demo01.MyServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>MyServlet</servlet-name> <url-pattern>/MyServlet</url-pattern> </servlet-mapping> </web-app>
package com.oracle.demo01; public class MyServlet { public void init(){ System.out.println("MyServlet创建了...."); } public void service(){ System.out.println("MyServlet被访问了...."); } public void destroy(){ System.out.println("MyServlet销毁了...."); } }
public class Demo01 { public static void main(String[] args) throws Exception { // 创建一个SaxReader对象 SAXReader sax=new SAXReader(); // 加载xml文件获取Document对象 Document doc=sax.read("src/com/oracle/demo01/web.xml"); // 获取根元素 Element root=doc.getRootElement(); // 获取servlet元素 Element servlet=root.element("servlet"); // 获取servlet-class元素 Element servletClass=servlet.element("servlet-class"); // 获取本文节点 String className=servletClass.getText(); // 获取字节码文件对象 Class c=Class.forName(className); // 快速创建对象 MyServlet my=(MyServlet)c.newInstance(); // 调用方法 my.init(); my.service(); my.destroy(); } }
<?xml version="1.0" encoding="UTF-8"?> <!-- 模拟servlet2.5规范,如果开发人员需要在xml使用当前Schema约束,必须包括指定命名空间。 格式如下: <web-app xmlns="http://www.example.org/web-app_2_5" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.example.org/web-app_2_5 web-app_2_5.xsd" version="2.5"> --> <xsd:schema xmlns="http://www.w3.org/2001/XMLSchema" targetNamespace="http://www.example.org/web-app_2_5" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:tns="http://www.example.org/web-app_2_5" elementFormDefault="qualified"> <xsd:element name="web-app"> <xsd:complexType> <xsd:choice minOccurs="0" maxOccurs="unbounded"> <xsd:element name="servlet"> <xsd:complexType> <xsd:sequence> <xsd:element name="servlet-name"></xsd:element> <xsd:element name="servlet-class"></xsd:element> </xsd:sequence> </xsd:complexType> </xsd:element> <xsd:element name="servlet-mapping"> <xsd:complexType> <xsd:sequence> <xsd:element name="servlet-name"></xsd:element> <xsd:element name="url-pattern" maxOccurs="unbounded"></xsd:element> </xsd:sequence> </xsd:complexType> </xsd:element> <xsd:element name="welcome-file-list"> <xsd:complexType> <xsd:sequence> <xsd:element name="welcome-file" maxOccurs="unbounded"></xsd:element> </xsd:sequence> </xsd:complexType> </xsd:element> </xsd:choice> <xsd:attribute name="version" type="double" use="optional"></xsd:attribute> </xsd:complexType> </xsd:element> </xsd:schema>
标签:XML,my,void,约束,class,MyServlet,servlet,public 来源: https://www.cnblogs.com/sihaoyu/p/14873660.html