gpt4 book ai didi

java - Servlet的反射(reflection),Httpservletrequest类型正在获取RequestFacade类型并且无法调用方法

转载 作者:行者123 更新时间:2023-11-30 04:09:51 24 4
gpt4 key购买 nike

我尝试使用反射调用方法,方法参数是 HttpServletRequest 类型,但执行中的参数获取 RequestFacade 并且无法调用该方法,这是我的代码

Servlet 代码:

 /**
* 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 类型,如果我在方法调用中转换参数,则不会调用该方法,因为参数保持相同的类型。

我发现参数从包 org.apache.catalina.. 中获取了类型 RequestFacade最后,我无法更改方法参数类型,因为我无法使用该包。

PD:为了简单起见,我只是在帖子中使用了 RequestFacadeHttpServletRequest 类型,但我知道有一个 ResponseFacade >HttpServletResponse 类型。

最佳答案

您错误地使用了 Method#invoke() 方法

method.invoke((HttpServletRequest)request, (HttpServletResponse)response);

See the javadoc for that method here.

第一个参数必须是要执行该方法的实例。第二个以上参数是可选的,即。 varargs,这是方法的参数。像这样使用它

method.invoke(this, (HttpServletRequest)request, (HttpServletResponse)response);

其中 this 引用您的 Servlet 实例。如果该方法位于其他类中,则您将需要该类的实例。

关于java - Servlet的反射(reflection),Httpservletrequest类型正在获取RequestFacade类型并且无法调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19896300/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com