我可以使用 Class 变量将 Httpserveltrequest/response 对象传递给 运行() 方法吗?

Can I pass Httpserveltrequest/response object to run() method using Class variables?

我拨打了 ajax 电话并在 java class

中输入了以下代码
if("callfirstPageStoredProcedure".equalsIgnoreCase(request.getParameter("mode"))) {
    synchronized(this) {
        pb = new PayrollBean(request, response, logininfo, request.getParameter("mode"));
        pb.startThread();
    }
}

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

然后在 运行() 方法中,我尝试访问这些参数,但似乎它们在此处不可用,并且抛出 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.