1. Create a TestServlet class
Package com. yanek. test;
Import java. io. IOException;
Import java. lang. reflect. Method;
Import javax. servlet. ServletException;
Import javax. servlet. http. HttpServlet;
Import javax. servlet. http. HttpServletRequest;
Import javax. servlet. http. HttpServletResponse;
Public class TestServlet extends HttpServlet {
Public void doGet (HttpServletRequest request, HttpServletResponse response)
Throws ServletException, IOException {
// Obtain the full path and name of the class
String className = request. getParameter ("className ");
// Obtain the method name
String methodName = request. getParameter ("method ");
Try {
// Obtain the class file
Class <?> T_class = Class. forName (className );
// Obtain the required methods for this class
Method method = t_class.getDeclaredMethod (methodName,
HttpServletRequest. class, HttpServletResponse. class );
Method. invoke (t_class.newInstance (), request, response); // method implementation
} Catch (Exception e ){
E. printStackTrace ();
}
}
Public void doPost (HttpServletRequest request, HttpServletResponse response)
Throws ServletException, IOException {
DoGet (request, response );
}
}
2. Create a class to be called automatically
Package com. yanek. test;
Import javax. servlet. http. HttpServletRequest;
Import javax. servlet. http. HttpServletResponse;
Public class Test {
/**
* @ Param args
*/
Public static void main (String [] args ){
System. out. println ("hello world! ");
}
Public void test (HttpServletRequest request, HttpServletResponse response ){
System. out. println ("hello ");
System. out. println (request. getParameter ("username "));
}
}
3. web. xml configuration
<? Xml version = "1.0" encoding = "UTF-8"?>
<Web-app version = "2.5" xmlns = "http://java.sun.com/xml/ns/javaee"
Xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi: schemaLocation = "http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<Servlet>
<Description> Test </description>
<Display-name> Test </display-name>
<Servlet-name> Test </servlet-name>
<Servlet-class> com. yanek. test. TestServlet </servlet-class>
<Load-on-startup> 1 </load-on-startup>
</Servlet>
<Servlet-mapping>
<Servlet-name> Test </servlet-name>
<Url-pattern>/Test </url-pattern>
</Servlet-mapping>
<Welcome-file-list>
<Welcome-file> index. jsp </welcome-file>
</Welcome-file-list>
<Login-config>
<Auth-method> BASIC </auth-method>
</Login-config>
</Web-app>
4. Start server access:
Http: // 127.0.0.1: 8081/TestPrj/Test? ClassName = com. yanek. test. Test & method = test & username = aspboy
Console output:
Hello
Aspboy
Note: The public void test (HttpServletRequest request, HttpServletResponse response) method of the com. yanek. Test. test class is executed.
Reflection mechanism is an important function in java and is widely used in framework design.
Test environment: tomcat6.0