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

Two simple ways to remove text watermarks from web pages

<br /> When we browse certain websites and s...

Vue implements real-time refresh of the time display in the upper right corner

This article example shares the specific code of ...

How to use @media in mobile adaptive styles

General mobile phone style: @media all and (orien...

An example of using Dapr to simplify microservices from scratch

Table of contents Preface 1. Install Docker 2. In...

Vue makes div height draggable

This article shares the specific code of Vue to r...

Details of the underlying data structure of MySQL indexes

Table of contents 1. Index Type 1. B+ Tree 2. Wha...

How to install and use Server-U 14 version

Introducing Server-U software Server-U is a very ...

How to implement the King of Glory matching personnel loading page with CSS3

Those who have played King of Glory should be fam...

Analysis of the use of Linux vulnerability scanning tool lynis

Preface: Lynis is a security audit and hardening ...

About scroll bar in HTML/removing scroll bar

1. The color of the scroll bar under xhtml In the ...

Implementation of postcss-pxtorem mobile adaptation

Execute the command to install the plugin postcss...

Simple implementation method of vue3 source code analysis

Table of contents Preface 🍹Preparation 🍲vue3 usag...

Realization of real-time file synchronization between Linux servers

Usage scenarios For existing servers A and B, if ...

Detailed explanation of the text-fill-color property in CSS3

What does text-fill-color mean? Just from the lit...

Summary of the use of Datetime and Timestamp in MySQL

Table of contents 1. How to represent the current...