我尝试使用反射调用方法,方法参数是 HttpServletRequest 类型但执行中的参数获取 RequestFacade 并且无法调用该方法,这是我的代码
小服务程序代码:
/**
* Handles the HTTP
* <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//processRequest(request, response);
String test = (String)request.getParameter("testingText");
String methodToCall = (String)request.getParameter("method");
Method method;
try {
method = this.getClass().getMethod(methodToCall, HttpServletRequest.class, HttpServletResponse.class);
method.invoke((HttpServletRequest)request, (HttpServletResponse)response);
//test(request, response);
} catch (Exception e) {
System.out.println("Exception: " + e.getMessage());
}
}
public void test(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException{
processRequest(request, response, "test");
}
public void handleRequest(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException{
processRequest(request, response, "handleRequest");
}
这是JSP
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<form method="POST" action="Controller">
<input type="hidden" name="method" value="test"/>
<input type="text" placeholder="Testing text" name="testingText" />
<input type="submit" value="Click me!" />
</form>
<form method="POST" action="Controller">
<input type="hidden" name="method" value="handleRequest"/>
<input type="text" placeholder="Testing text" name="testingText" />
<input type="submit" value="Click me!" />
</form>
</body>
被doPost
调用,并且找到了方法,但是在调用中由于类型不同而失败。如果我尝试使用method = this.getClass().getMethod(methodToCall, request.class, response.class);
找不到该方法。
我尝试创建新的HttpServletRequest
类型变量,但变量仍然是类型RequestFacade
,如果我在方法的调用中转换参数,则不会调用该方法,因为参数保持相同的类型。
我发现参数RequestFacade
从包中获取了类型org.apache.catalina..
最后我无法更改方法参数类型,因为我无法使用该包。
PD:为了简单起见,我只是在帖子中使用了类型RequestFacade
和HttpServletRequest
,但我知道有一个ResponseFacade
和HttpServletResponse
类型。