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>MyServlet1</servlet-name> <servlet-class>cn.itheima.web.servlet1.MyServlet1</servlet-class> </servlet> - <servlet-mapping> <servlet-name>MyServlet1</servlet-name> <url-pattern>/myServlet1</url-pattern> </servlet-mapping> - <servlet> <servlet-name>MyServlet2</servlet-name> <servlet-class>cn.itheima.web.servlet1.MyServlet2</servlet-class> </servlet> - <servlet-mapping> <servlet-name>MyServlet2</servlet-name> <url-pattern>/myServlet2</url-pattern> </servlet-mapping> </web-app>
接口
public interface IMyServlet { public void init(); public void service(); public void destory(); }
接口的一个实现类Myservlet1
public class MyServlet1 implements IMyServlet{ @Override public void init() { System.out.println("MyServlet1诞生了……"); } @Override public void service() { System.out.println("MyServlet1开始服务了……"); } @Override public void destory() { System.out.println("MyServlet1销毁了……"); } }
接口的另一个实现类Myservlet2
public class MyServlet2 implements IMyServlet{ @Override public void init() { System.out.println("MyServlet2诞生了……"); } @Override public void service() { System.out.println("MyServlet2开始服务了……"); } @Override public void destory() { System.out.println("MyServlet2销毁了……"); } }
Junit测试类
@Test public void testMyServlet(){ try { //1.创建解析器对象 SAXReader saxReader = new SAXReader(); //2.使用解析器加载web.xml文件得到document对象 Document document = saxReader.read("src/cn/itheima/web/servlet1/web.xml"); //3.获取根元素节点 Element rootElement = document.getRootElement(); //4.根据元素名称获取子元素节点 Element servletElement = rootElement.element("servlet"); //5.根据元素名称获取servlet-class的文本节点 String servletClass = servletElement.element("servlet-class").getText(); //System.out.println(servletClass); //6.通过类全名获取字节码文件 Class clazz = Class.forName(servletClass); //7.创建实例对象 MyServlet1 my = (MyServlet1) clazz.newInstance(); //8.调用实例对象里面的方法 my.init(); my.service(); my.destory(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }