gpt4 book ai didi

java - 我可以使用类变量将 Httpservletrequest/response 对象传递给 run() 方法吗?

转载 作者:行者123 更新时间:2023-12-01 11:17:03 25 4
gpt4 key购买 nike

我进行了 ajax 调用并在 java 类中输入了以下代码

if("callfirstPageStoredProcedure".equalsIgnoreCase(request.getParameter("mode"))) {
synchronized(this) {
pb = new PayrollBean(request, response, logininfo, request.getParameter("mode"));
pb.startThread();
}
}

所以在类 payrollBean 中,在这个新构造函数的帮助下,我将请求和响应参数设置为全局变量。

然后在 run() 方法中,我尝试访问这些参数,但似乎它们在这里不可用,并且抛出了 nullPointerexception

构造函数:

public PayrollBean(HttpServletRequest request, HttpServletResponse response, LoginInfo loginInfo, String methodToCall){
this.request = request;
this.response = response;
this.loginInfo = loginInfo;
this.methodToCall = methodToCall;
}

启动方法调用:

public void startThread(){
payrollThread=new Thread(this);
payrollThread.start();
System.err.println("The payrollThread is started Now!!!!!!!!!!!!!!!!!!!");
}

运行方法:

public void run(){
int InCatch = 0;
try {
if("callfirstPageStoredProcedure".equalsIgnoreCase(methodToCall)) {
callfirstPageStoredProcedure(request, response, loginInfo);
}
}

知道我在这里做错了什么吗?

最佳答案

Each request object is valid only within the scope of a servlet’s service method, or within the scope of a filter’s doFilter method

因此,您不应保存对 HttpServletRequestHttpServletResponse 的任何引用以便在另一个线程中使用。原始请求完成后,您将无法访问请求参数。您的Thread有时会在请求完成之前执行,有时会稍后执行。

相反,您应该从原始请求中复制所需的信息以供以后处理。

摘自Java Servlet Specification :

3.11 Lifetime of the Request Object

Each request object is valid only within the scope of a servlet’s service method, or within the scope of a filter’s doFilter method, unless the asynchronous processing is enabled for the component and the startAsync method is invoked on the request object. In the case where asynchronous processing occurs, the request object remains valid until complete is invoked on the AsyncContext. Containers commonly recycle request objects in order to avoid the performance overhead of request object creation. The developer must be aware that maintaining references to request objects for which startAsync has not been called outside the scope described above is not recommended as it may have indeterminate results.

关于java - 我可以使用类变量将 Httpservletrequest/response 对象传递给 run() 方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31699944/

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