servlet方法的动态调用


servlet的动态方法调用

1 创建web项目工程Demo

2 创建BaseServlet【继承HttpServlet】

   web.xml的servlet配置信息

<servlet>
    <servlet-name>BaseServlet</servlet-name>
    <servlet-class>com.yq.servlet.BaseServlet</servlet-class>
  </servlet>

<servlet-mapping>
    <servlet-name>BaseServlet</servlet-name>
    <url-pattern>/servlet/BaseServlet</url-pattern>
  </servlet-mapping>

public class BaseServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("进入Servlet...");

String methodName = request.getParameter("methodName");
Class clazz = this.getClass();
Method method = null;
try {
method = clazz.getMethod(methodName, HttpServletRequest.class,

 HttpServletResponse.class);
method.invoke(this, request,response);
}  catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
public void login(HttpServletRequest request, HttpServletResponse response){
System.out.println("进入login方法");
}
}

部署之后 访问localhost:8080/Demo/servlet/BaseServlet?methodName=login即可访问login方法  实现动态方法调用...

3 创建UserServlet extends BaseServlet{

public void save(HttpServletRequest request , HttpServletResponse response) {
System.out.println("子类的方法save()...");
}

}

3.1 在web.xml中配置

<servlet>
    <servlet-name>UserServlet</servlet-name>
    <servlet-class>com.yq.servlet.UserServlet</servlet-class>
  </servlet>

    <servlet-mapping>
    <servlet-name>UserServlet</servlet-name>
    <url-pattern>/servlet/UserServlet</url-pattern>
  </servlet-mapping>

部署之后 访问localhost:8080/Demo/servlet/UserServlet?methodName=save即可访问save方法  实现动态方法调用...实现类似struct2中动态方法的调用


你可能感兴趣的:(servlet方法的动态调用)