简体   繁体   English

将 Session 参数传递给 Thread

[英]Passing Session parameters to Thread

I wanted to do two tasks simultaneously in web project in the Servlet once the user clicks on submit button一旦用户单击提交按钮,我想在 Servlet 的 web 项目中同时执行两个任务
1. Run a code to trigger some backend activity 1. 运行代码来触发一些后端活动
2. Display a webpage to the user. 2. 向用户显示网页。
I tried with the code sample here在这里尝试使用代码示例

As I have few session attributes being set I need to set this in one of the thread.由于我设置的会话属性很少,因此我需要在其中一个线程中进行设置。 I tried putting point one in one thread and point two in second but variables are not getting resolved to the thread from doPost() method.我尝试将第一个点放在一个线程中,将第二个点放在第二个线程中,但是变量没有从 doPost() 方法解析到线程。

Servlet:小服务程序:

public class JOBRUN extends HttpServlet{
protected void doGet(HttpServletRequest request, HttpServletResponse     response) throws ServletException, IOException {
     AESASNewOpenPeriod=request.getParameter("AESASNewOpenPeriod");
     ScriptRunOption = Integer.parseInt(request.getParameter("AESASJOBRUNOPTION"));
     HttpSession session=request.getSession();
     String Stream="aaaa";
     session.setAttribute("AEStream", Stream);
     //Do Job 1 (Update table)
     //Do Job 2 (Display webpage to user)
        }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    doGet(request, response);

}

You can create an anonymous thread (if you don't want a dedicated Thread class for ) Job 1.您可以为作业 1 创建一个匿名线程(如果您不需要专用的Thread类)。

new Thread(new Runnable() {
    Session localSession = session;// assign the session object to thread variable.
    public void run() {
        // you can access localSession here. and do the JOB 1
    }
}).start();// this will run asynchrously(non blocking).

Also if you want to pass only some attributes to do the Job 1(i,e if u don't want to change the session), you can pass relevant attributes only.For example此外,如果您只想传递一些属性来执行作业 1(即,如果您不想更改会话),则可以仅传递相关属性。例如

String threadStream = session.setAttribute("AEStream");//local memeber variable  inside anonymous thread

Then from the next line after thread, you can do Job 2.然后从线程后的下一行,您可以执行作业 2。

Note: If you mean something else- running an asychrounous worker thread with request , you start wit Servlet 3.x AsyncContext注意:如果你的意思是别的——运行一个带有 request 的异步工作线程,你可以从 Servlet 3.x AsyncContext开始

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM