web.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>helloServlet</servlet-name> <servlet-class>cn.sasa.web01.servlet.Hello</servlet-class> </servlet> <servlet-mapping> <servlet-name>helloServlet</servlet-name> <url-pattern>/hello</url-pattern> </servlet-mapping> <servlet> <servlet-name>hiServlet</servlet-name> <servlet-class>cn.sasa.web01.servlet.Hi</servlet-class> </servlet> <servlet-mapping> <servlet-name>hiServlet</servlet-name> <url-pattern>/hi</url-pattern> </servlet-mapping> </web-app>
创建一个接口,其实现类实现接口的方法
package cn.sasa.web01.servlet; public interface IMyServlet { public void init(); public void service(); public void destory(); }
创建两个实现类Hello、Hi实现IMyServlet接口
package cn.sasa.web01.servlet; public class Hello implements IMyServlet { @Override public void init() { System.out.println("hello----init"); } @Override public void service() { System.out.println("hello----service"); } @Override public void destory() { System.out.println("hello----destory"); } }
package cn.sasa.web01.servlet; public class Hi implements IMyServlet { @Override public void init() { System.out.println("hi----init"); } @Override public void service() { System.out.println("hi----service"); } @Override public void destory() { System.out.println("hi----destory"); } }
测试:
package cn.sasa.web01.servlet; import java.lang.reflect.Method; import java.util.List; import org.dom4j.Document; import org.dom4j.Element; import org.dom4j.io.SAXReader; public class Test { public static void main(String[] args) { SAXReader reader = new SAXReader(); // try { // Document doc = reader.read("src/cn/sasa/web01/servlet/web.xml"); // Element root = doc.getRootElement(); // Element servElement = root.element("servlet"); // String className = servElement.element("servlet-class").getText(); // //System.out.println(str); // Class c1 = Class.forName(className); // hello obj = (hello)c1.newInstance(); // obj.init(); // obj.service(); // obj.destory(); // } catch (Exception e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } try { //获取xml文档对象 Document doc = reader.read("src/cn/sasa/web01/servlet/web.xml"); //获取根节点 Element root = doc.getRootElement(); List<Element> chilNodes = root.elements(); for(Element e : chilNodes) { if("servlet".equals(e.getName())) { //获取类全名 String className = e.element("servlet-class").getText(); //反射获取字节文件对象 Class c = Class.forName(className); //生成对象 Object obj = c.newInstance(); //获取方法 Method init = c.getMethod("init", null); //运行 init.invoke(obj, null); Method service = c.getMethod("service", null); service.invoke(obj, null); Method destory = c.getMethod("destory", null); destory.invoke(obj, null); } } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }