反射动态调用方法

后台请求的路径必须是一个方法名,例如:请求路径为"${pageContext.request.contextPath }/query.do"

在web.xml文件中配置对应的servlet  /query.do


servlet:

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;

import com.yzh.methodes.Methods;

public class InvokeServlet extends HttpServlet
{
    /**
     * serialVersionUID
     */
    private static final long serialVersionUID = 1L;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException
    {
        doPost(req, resp);
    }
    
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException
    {
        String methodName = req.getServletPath();
        methodName = methodName.substring(1,methodName.lastIndexOf("."));
        
        try
        {
            Method method = Methods.class.getMethod(methodName);
            Methods methods = new Methods();
            method.invoke(methods);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        
    }
    
}

methodes类:

public class Methods
{
    public void query()
    {
        System.out.println("--------query---------");
    }
    
    public void update()
    {
        System.out.println("---------update-------------");
    }
}




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