简体   繁体   中英

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
1. Run a code to trigger some backend activity
2. Display a webpage to the user.
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.

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.

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

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

Then from the next line after thread, you can do Job 2.

Note: If you mean something else- running an asychrounous worker thread with request , you start wit Servlet 3.x AsyncContext

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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