Tomcat parses XML and creates objects through reflection

Tomcat parses XML and creates objects through reflection

The following example code introduces the principles of Tomcat parsing XML and creating objects through reflection. The specific code is as follows:

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
public class ServerReadXML1 {
  public static void main(String[] args)
      throws DocumentException, ClassNotFoundException, InstantiationException, IllegalAccessException,
      NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException {
    // Now if you enter a Servlet url-pattern in the browser
    String urlPattern = "/first";
    // Get the class name according to urlPattern String className = getClassByUrl(urlPattern);
    // Get the Class object based on the full class name Class clazz = Class.forName(className);
    // Create the specified object by reflecting the clazz object Object obj = clazz.newInstance();
    // Get the service method Method method = clazz.getDeclaredMethod("service");
    // Get permissions method.setAccessible(true);
    // Execute the service method method.invoke(obj);
  }
  private static String getClassByUrl(String urlPattern) throws DocumentException {
    // 1. Create a SAXReader object SAXReader reader = new SAXReader();
    // 2. Read the file Document document = reader.read(ServerReadXML1.class.getClassLoader().getResourceAsStream("web.xml"));
    // 3. Get the root node Element rootElement = document.getRootElement();
    //System.out.println(rootElement.getName());
    // 4. Get the child nodes List<Element> under the root node servletList = rootElement.elements();
    // Record the content of the servlet-name tag that is the same as urlPattern String servletName = "";
    // Record the content of servlet-class in the servlet tag // The content of servletClassName is the full class name of the Servlet String servletClassName = "";
    // 5. Traverse child nodes for (Element servletElement : servletList) {
      //System.out.println(servletElement.getName());
      // If it is a servlet-mapping tag, execute the code if ("servlet-mapping".equals(servletElement.getName())) {
        // Get the url-pattern tag object Element url = servletElement.element("url-pattern");
        // Check if the content of the tag is the same as the entered urlPattern value if (urlPattern.equals(url.getText())) {
          //Record the content of the servlet-name tag that is the same as urlPattern //If they are the same, record ServletName
          // Get the content of servelt-name in servlet-mapping servletName = servletElement.element("servlet-name").getText();
        }
      }
    }
    // Traverse again for (Element servletElement : servletList) {
      // If it is a servlet tag, execute this code if ("servlet".equals(servletElement.getName())) {
        // Determine whether the value of servletName obtained in the previous traversal is the same as the content of servlet-name in this traversal if (servletName.equals(servletElement.element("servlet-name").getText())) {
          // If the same record servletClassName
          servletClassName = servletElement.element("servlet-class").getText();
        }
      }
    }
    // Return the full class name of the Servlet servletClassName
    return servletClassName;
  }
}

1. 4 ways to obtain Class through reflection

@Test
  public void test1() throws ClassNotFoundException {
    //1. Class name.class
    Class clazz = String.class;
    System.out.println(clazz);
    //2. Object.getClass()
    Class clazz1 = "abc".getClass();
    System.out.println(clazz1);
    //3.Class.forName();
    Class clazz2 = Class.forName("java.lang.String");
    System.out.println(clazz2);
    //4.ClassLoader .loadClass("full class name")
    Class clazz3 = ReflectTest1.class.getClassLoader().loadClass("java.lang.String");
    System.out.println(clazz3);
  }

2. Common methods of using reflection properties

@Test
  public void test2() throws ClassNotFoundException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
    //Get the Class object to get its internal properties Class clazz = Class.forName("com.atguigu.bean.User");
    User user = new User();
    //The Field object represents the class attribute getField can only get the public attribute Field field = clazz.getField("email");
    System.out.println(field);
     //This method destroys the encapsulation of the code and is not recommended. Field field2 = clazz.getDeclaredField("id");
    System.out.println(field2);
    field2.setAccessible(true);
    field2.setInt(user, 1001);
    System.out.println(user);
  }

3. Common methods of using reflection

@Test
  public void test3() throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException {
    Class clazz = Class.forName("com.atguigu.bean.User");
    //Create an object through reflection Object obj = clazz.newInstance();
    //Now we want to set the name value String fileName = "name";
    //Create a method name String methodName = "set" + fileName.substring(0, 1).toUpperCase() //N
    + fileName.substring(1).toLowerCase(); //ame
    //Get the public method according to the method name Method method = clazz.getMethod(methodName, String.class);
    //Execute the specified method method.invoke(obj, "yangjian");
    System.out.println(obj);
  }

Summarize

The above is the principle of Tomcat parsing XML and creating objects through reflection introduced by the editor. I hope it will be helpful to everyone. If you have any questions, please leave me a message and the editor will reply to you in time. I would also like to thank everyone for their support of the 123WORDPRESS.COM website!
If you find this article helpful, please feel free to reprint it and please indicate the source. Thank you!

You may also be interested in:
  • Detailed explanation of Tomcat core components and application architecture
  • Detailed explanation of the startup principle of SpringBoot built-in tomcat
  • Analyze the working principle of Tomcat
  • Detailed analysis of the startup.bat principle in Tomcat
  • Detailed analysis of catalina.bat principle in Tomcat
  • Introduction to the principles, configuration, and use of Tomcat data sources
  • Detailed explanation of the implementation principle of Tomcat hot deployment
  • Analyze Tomcat architecture principles to architecture design

<<:  JavaScript built-in date and time formatting time example code

>>:  Detailed explanation of various loop speed tests in JS that you don’t know

Recommend

MySQL 8.0 DDL atomicity feature and implementation principle

1. Overview of DDL Atomicity Before 8.0, there wa...

How to remove the dotted border when clicking a link in FireFox

I encountered several browser compatibility issue...

Detailed explanation of how to write mysql not equal to null and equal to null

1. Table structure 2. Table data 3. The query tea...

Detailed explanation of the use of custom parameters in MySQL

MySQL variables include system variables and syst...

JavaScript ES new feature block scope

Table of contents 1. What is block scope? 2. Why ...

Detailed explanation of the lock structure in MySQL

Mysql supports 3 types of lock structures Table-l...

vue+echarts realizes the flow effect of China map (detailed steps)

@vue+echarts realizes the flow effect of China ma...

Mysql modify stored procedure related permissions issue

When using MySQL database, you often encounter su...

Docker data storage tmpfs mounts detailed explanation

Before reading this article, I hope you have a ba...

How to write high-quality JavaScript code

Table of contents 1. Easy to read code 1. Unified...

How to Customize Bash Command Prompt in Linux

Preface As we all know, bash (the B ourne-A gain ...