Browser Closed, servlet context cleared?

Greetings everyone!
I actually redeveloping JSP web apps these weeks.
But getting some few couple bugs here.
Perhaps I need some suggestions from you all here.
Okay, here they are;
I have multiple users who can use this web app.
Once they login, their User ID is stored on the ServletContext
so each JSP / Servlet from each access of those user may have a same information about
the active users there, by looking up into the ServletContext who are alive there.
At the time any user logout, calling a single servlet,
check his id from ServletContext, clear up if any.
Then boom close.
Okay, here's the bug.
What if the user didnt proceed to logout, instead
he / she may just close the browser. Thus, the User ID of corresponding user (that user)
is still exist on the ServletContext... and no one delete that user, except himself / herself.
anyone may clear me up what should I do
to alternate this matters?
:D

gumuruh wrote:
sessions are stored in server??Yes.
But I thought, the sessions are stored in the client side.Well you're wrong. The session ID is stored on the client side, so the server knows which client's session to use.
okay here my question is.
How could if i use this story to be used as a sharing session?You want to share a single session between several clients?
I mean the session is storing their names there. And at anytime they log out, or closed the browser, only
that username lost. While the rest of the username still there stored in the session?Each client has their own session.
Because I was thinking that;
The server doesn't know either the users are still there opening single page or not.
That's what I encountered when I used ServletContext. The value stored within
the ServletContext is not cleared at the time User just closed out their browser.That's why you set a session timeout, so old sessions get closed even if the user doesn't log out.
~ again I agree to use HTTPSession but how would it match with the story proposed?
well actually the purpose is that each user wants to know who is currently log in (by looking into the servletContext perhaps)Don't touch ServletContext. It's not meant to be used by you. At least in that way. You can read from the ServletContext, but you have no reason to store anything there.
You can use for example a Singleton (or a database table or any other shared resource) to store the logged in users.

Similar Messages

  • Servlet Context in a Nutshell??????

    I am a newcomer to Servlets and relatively new to Java. I have not found a very clear explanation of what a servlet "Context" is and can therefore only assume that its so simple as to not need further explanation.
    Here goes;
    1. You write your Servlet code, compile it.
    2. If you add this Servlet to the classes directory of a web-app called "MyWebApp" then the context for that particular servlet is "/MyWebApp"
    3. Adding it to the classes directory of other web apps gives a different "context" for each one.
    4. You can add a servlet to a web-app ("context") by adding the servlet URI to the deployment descriptor of the web-app????????(THis one I am really not sure of)
    Summary: The context of a particular servlet is the name of the particular web-app within which it resides or is referred to
    Maybe some of you experts out there could shed some light on this and I could create a document explaing context a post it on the web sowmwhere for other poor beginners like myself.
    Thanks in advance.

    Well, some experts will wanna kill me for told that, but, lets go....
    Comparing with the JVM, a context is like a class path (of course they have many differences). In other worlds the context is a directory (or war file) where the web server (for example TOMCAT) wiil search your .class files (or.war, .jar, etc...)
    All context are "pointed" to a dir, for example you can point the context /myapps to a dir of your OS (for example /home/your_username or in a windows system - C:\Program Files.
    Then when you acces this context at the browser, the browser will show this directory hierarchy. For you execute your servlet you need to create a WSDL (the descritor file). This file is nothing more than a XML document (that had rules) and link a servlet at a context, (for example the servlet Hello can pointed to the path /hello, and then, this servlet is "install" at the context /myapps). After this, you can access your servlet at the path http://computer_address/myapps/hello.
    Note: Step by step, you need:
    1) create the web application strucuture directory (the WEB-INF, classes, etc...)
    2) write the servlet
    3) write the web.xml
    4) compile the servlet
    5) create a context - point the context to the web app structure "father"
    6) install this servlet at the context
    7) access the servlet
    I hope this help you to understand some things, but for learning I recomended the Tomcat manual!!!! Good Luck.
    Giscard

  • Inexplicable delays in browser-to-servlet-to-browser communication

    We are seeing some inexplicable "pauses" in the round-trip from
    browser-to-servlet-to-browser communication. The browser and Weblogic
    instance are on different machines, so correlating absolute times has
    been difficult. So at this point it's hard to tell whether the browser
    request is not being received immediately by the servlet, or the servlet
    response is not being received immediately by the browser... or perhaps
    it is, but maybe the response stream isn't "closing" properly, causing
    the browser to think there's still more to come.
    If the browser request is not being received immediately by the servlet,
    it could be because the execute thread count is so low that the request
    is being blocked until a thread is availble to service it. But our
    thread count is set to 30 and this is with just a single user hitting
    the servlet.
    If the servlet response is not being received immediately by the
    browser, or is not being closed properly, what could cause that?
    Occassionally, I have been able to account for some of the "delay"
    time. Our servlet does the usual stuff: writes out to the response
    writer and then closes the writer:
    PrintWriter writer = response.getWriter();
    writer.write( htmlString );
    writer.close();
    I have seen the writer.close() method taking a long time - over 5
    seconds on one occassion! What could it be doing?
    Could some type of TCP_NO_DELAY network setting account for all of
    this? Any and all help/experiences are appreciated.
    mg
    Mike Gorman, Director of Architecture
    YOUcentric, Inc.
    Charlotte, NC
    704-643-1000 x518
    http://www.youcentric.com

    If you are using 5.1 and you have ELF turned on (see docs).
    You can specify "time" as an ELF header and this gives you the time of
    processing and the write.
    mbg
    In article <[email protected]>, [email protected] says...
    Here are a few top of the head suggestions:
    1. You can log the time when the request is received by the servlet and
    when the output stream is closed. That should give you a fair idea of
    what percentage of delay happens on the servlet side.
    2. Try flush() to send stuff to the browser after every few lines of
    write(). It helps.
    3. IE does wait for the whole HTML to come in before it displays unlike
    Netscape which shows the streaming data. So switch browser and check.
    4. Make sure you are not using the SingleThread model even though that
    does not explain the delay encountered by a single user.
    If these do not help, you would need to give more insight into the code.
    - Anshum
    Mike Gorman wrote:
    We are seeing some inexplicable "pauses" in the round-trip from
    browser-to-servlet-to-browser communication. The browser and Weblogic
    instance are on different machines, so correlating absolute times has
    been difficult. So at this point it's hard to tell whether the browser
    request is not being received immediately by the servlet, or the servlet
    response is not being received immediately by the browser... or perhaps
    it is, but maybe the response stream isn't "closing" properly, causing
    the browser to think there's still more to come.
    If the browser request is not being received immediately by the servlet,
    it could be because the execute thread count is so low that the request
    is being blocked until a thread is availble to service it. But our
    thread count is set to 30 and this is with just a single user hitting
    the servlet.
    If the servlet response is not being received immediately by the
    browser, or is not being closed properly, what could cause that?
    Occassionally, I have been able to account for some of the "delay"
    time. Our servlet does the usual stuff: writes out to the response
    writer and then closes the writer:
    PrintWriter writer = response.getWriter();
    writer.write( htmlString );
    writer.close();
    I have seen the writer.close() method taking a long time - over 5
    seconds on one occassion! What could it be doing?
    ==================================================
    NewsGroup Rant
    ==================================================
    Rant 1.
    The less info you provide about your problem means
    the less we can help you. Try to look at the
    problem from an external perspective and provide
    all the data necessary to put your problem in
    perspective.

  • Condition to test for the browser closing/refreshing

    I have an applet that rotates pictures in a html file. I have it in an eternal loop to keep it running. It loads fine, but if you refresh or try to close the browser, the browser locks. Without question this happens because the loop does not test for the browser closing or refreshing so the loop never stops. Does anyone have an idea of a Java condition to test for the browser closing/refreshing so I can stop my loop when these events occur.

    The applets stop message should be called on a reload and/or a close. You could set a flag in your stop method that could be checked by a thread that actually sits and loops.
    When the flag is set, kill the tread.
    You should clear that flag in your start method.
    I have an applet that rotates pictures in a html file.
    I have it in an eternal loop to keep it running. It
    loads fine, but if you refresh or try to close the
    browser, the browser locks. Without question this
    happens because the loop does not test for the
    browser closing or refreshing so the loop never
    stops. Does anyone have an idea of a Java condition
    to test for the browser closing/refreshing so I can
    stop my loop when these events occur.

  • Getting servlet context in a web service

    Hi,
    I have a problem but have no solution to it and am not sure of the approach.
    I am creating a web service. Some parameters will be passed to this web service. I need to capture these parameters and put it in a hash table so that it is available to another applicatins servlet context i.e.
    there will be two calls .
    first the web service is invoked and the parameter is stored in the hash table of the applications servlet context.
    Next when the application is invoked it shud refer to the hash table and get the data in the hash table that was stored by the web service and process it.
    How can this be achieved?

    Well, some experts will wanna kill me for told that, but, lets go....
    Comparing with the JVM, a context is like a class path (of course they have many differences). In other worlds the context is a directory (or war file) where the web server (for example TOMCAT) wiil search your .class files (or.war, .jar, etc...)
    All context are "pointed" to a dir, for example you can point the context /myapps to a dir of your OS (for example /home/your_username or in a windows system - C:\Program Files.
    Then when you acces this context at the browser, the browser will show this directory hierarchy. For you execute your servlet you need to create a WSDL (the descritor file). This file is nothing more than a XML document (that had rules) and link a servlet at a context, (for example the servlet Hello can pointed to the path /hello, and then, this servlet is "install" at the context /myapps). After this, you can access your servlet at the path http://computer_address/myapps/hello.
    Note: Step by step, you need:
    1) create the web application strucuture directory (the WEB-INF, classes, etc...)
    2) write the servlet
    3) write the web.xml
    4) compile the servlet
    5) create a context - point the context to the web app structure "father"
    6) install this servlet at the context
    7) access the servlet
    I hope this help you to understand some things, but for learning I recomended the Tomcat manual!!!! Good Luck.
    Giscard

  • Servlet Context

    Could anyone please clarify me the meaning of the following line:
    "if the app is distributed, there's one ServletContext per JVM!"
    The above line I've quoted from head first book page no. 159. One thing has been cleared that, there's one ServletContext per web app, but still not able to grab the above quoted part specifically.
    Thanks in advance.

    For example, in online stores UI(view) might be designed in Java and gateway might be in some other language, this is called distributed.No doubt this is an example of distributed application, but in current context you are going out of track.
    In core there will be only one ServletContextWhy and how? If different parts of an application developed using different languages (assuming technology) are deployed in different platforms using different run times, then how they can have same servlet context?
    Here is the explanation:
    Usually any web application will have only one servlet context. However, in case of large applications to handle high number of concurrent users, typically web application is deployed in clustered environment. It means, same web application is deployed (and cloned) in multiple application server nodes. Each application server node has its own JVM (run time). In this scenario each application server will have different servlet context. That is why in your book it is written - If web application is distributed, there is one servlet context per JVM.
    Thanks,
    Mrityunjoy

  • How can I get the servlet Context from a WebService Implementation?

    I have made a webservice endpoint, using the conventional way (WSDL->wsimport->Java interface->implementation) . I need to get the servlet context below the implementation class. I haven't found any way to get the servletContext though. Any clues? Any help will be greatly appreciated.

    yes  i can found the words's unicode form Cmaps where may be at the type of tounicde and another Cmaps table just like "Adobe-GB1-GBK-EUC" ,but when the word dont have either of them how can i do? when i write a chinese word "一",it just the winansi encoding ,  there is not Cmap for me to use to change the "G208f" to the word "一"'s unicode value.
                   best wishes      thank you very much

  • Is it possible to create a file in servlet context? pls help me

    Is it possible to create a file in servlet context? pls help me

    Surely it is possible.File file = new File(path, name);

  • How to set a new attribute in th Servlet Context from an external app.

    Hi,
    I need to do an external application that can access to the servlet context to recover/modify some attributes. Anybody know how can I do it?.
    I've revised some mBeans thinking that they can serve me the servlet context, but I have not viewed anything related.
    Best Regards
    Antonio

    I'd say your best bet is adding another servlet and mapping to your application that presents a REST interface to this information. You could return application-scope data in a small XML document, and you could send attribute names and values with request parameters.
    It's not practical to dynamically change the actual init-params of the servlet context.

  • Browser right click context menu

    Hello Everyone,
    I want to get the browser right click context menu in the WD Application when they are running in portal. We don't want the SAP Default context menu, which is confusing for our end-users. Is there a way of disabling this. I would appreciate your help.
    Regards,
    Gopal.

    >Because, the iviews developed with WD JAVA will not have this option and the iViews with WD ABAP will have this special context menu. Which is not being consistent on the portal side for the end users.
    You must be running an older version of Web Dynpro Java then, because later versions have the same right mouse click context menu.
    You can't return to the browser context menu, because the application can also defined application-specific options in the WD Context Menu.  It isn't just the stuff that is placed in there by the framework.  You would be disabling Application specific funcitonality then.  You can hide some of the framework options as suggested already in this forum, but you can't go back to the browser context menu.

  • How to track browser closing event?

    Hi Everyone,
    I ran into a problem, which I thought at first would be a very easy thing to solve. Unfortunately, I spent few hours already reading through the forums posts and could not find the answer. Some say it is impossible to implement. I think there has got to be a solution to this problem.
    I need to track user's login time into the JSP application and record both login and logoff timestamps. I had no problem with the login. Just instantiated my TimeTracker object on the index.jsp page and it writes a new row into the database every time user hits this page. However, things are different with the logoff. User can exit out in three dirrent ways. One is to click the "Exit" button, second is when session expires and the third is when "X" button of the browser is clicked and browser shuts down. I can control first two scenarious. I don't know what to do about the user closing the browser.
    I tried capturing onCLose, onUnload or onBeforeUnload events but all of them are also invoked when window gets instantiated or when user clicks on a different page within the application. I also tried instantiating an applet within my JSP template and invalidate session inside its destroy() method but the problem here is that the applet gets destroyed every time a different page within the application is accessed.
    I am ready to give up and just leave it as it is now, let the session expire on its own and take care of the logoff time.
    Did anybody have similar problem and found the resolution?
    Any help would be greatly appreciated.
    Thanks,
    YM

    The common answer is that there is no good way to track the browser closing. A page can't tell the difference between the browser closing and simply navigating to a different page, so determining when the broswer is actually closed is a tough task. There have been some complex solutions in the past, but none seemed to be guaranteed to work, and as such, are pretty much useless for most applications.

  • How to stop Execution of Queries when the Browser closed in middle?

    Hi,
    I have JSP search page, which takes search parameters from previous page runs queries and display the results. I am using connection pool to connect to AS400 database.
    The problem I am facing is... The query still runs on database server, when the user closes browser before getting the search results.
    I am closing all my statements and returning connection to pool at the end of the JSP page.
    Is there any way to terminate the execution of the queries, when the user closes browser?
    Thanks in advance.

    Allright.
    As you know there is no direct way to catch that event, you will have to do this workaround :
    1. Create a class which implements HttpSessionBindingListener. The valueUnbound method will have flag or code to stop running query.
    2. Instantiate this in your search page, and add it into session.
    3. Add javascript in search JSP to access another(dummy) JSP on unload event(to catch browser closing) something like:
    function unload()
    location.href = "/kill.jsp";
    4. The code in dummy JSP will remove the object from session, and will fire valueUnbound method.
    Let me know if this helps.
    -Mak

  • Lock not always released if browser closed in edit mode.

    We have had a few instances in the last couple weeks (since deployment of an I.P. application) where a user has either closed the browser while in edit mode, or received some sort of error when saving plan data and the browser closed, where the Lock in RSPLSE/SM12 was not deleted. In the last case, the lock stayed for 6 hours before we were notified to manually delete the lock. The user had closed all windows, even restarted her machine.
    Any insight on how to enforce removal of locks if browser is closed? We are on SAPKW70017 and BI Java Support Package Patch SP015

    Hi Cote,
    this is a frequently discussed topic. Usually the lock should be released, the session should be closed etc at the time closing a window.
    One idea for this one: Does a small popup window appear when you close your browser? If the users have activated the popup blocker this will cause problems because the locks and sessions can not be released. Also it might cause problems using other browsers than IE...
    Good luck.
    Brgds,
    Marcel

  • Servlet Context problem.

    have two classes, one is a servletcontextlistner implementation and another one is the actual servlet that will call the first class.
    I am trying to have a counter in a servlet that keeps track of how many users have used the servlet. I like to store that in a servletcontextlistener and then call the counters value in the servlet. and also update that counters value.
    how can I do this ? are there any good examples that you know ? please help, as i have been stuck on this for manny hours.
    ServletContextListner implementation.
    public class counterContextListener implements ServletContextListener{
    String initialValue = "0";
    public counterContextListener(){}
    public void contextDestroyed(ServletContextEvent event){}
    public void contextInitialized(ServletContextEvent event){
    ServletContext context = event.getServletContext();
    context.setAttribute("countername", initialValue);
    public static String getCounterValue(ServletContext context) {
    String value = (String)context.getAttribute("countername");
    if (value == null) {
    value ="0";
    return(value);
    }//getCounterValue
    } // end of class
    Servlet
    public void doPost(HttpServletRequest req, HttpServletResponse res) throws
    ServletException, IOException{
    con = null;
    res.setContentType("text/plain");
    ServletInputStream sis = req.getInputStream();
    DataInputStream dis = new DataInputStream(sis);
    String username = dis.readUTF();
    dis.close();
    PrintWriter out = res.getWriter();
    System.out.println("The user has come:"+username+" " +count_users);
    //Using servlet context to get the current counter
    ServletContext context = getServletContext();
    String counter = getCounterValue(context); // passing context object.
    Error
    C:\Program Files\Apache Group\Tomcat 4.1\webapps\mudServlet>javac mudServletTTT.java
    mudServletTTT.java:36: cannot resolve symbol
    symbol : method getCounterValue (javax.servlet.ServletContext)
    location: class mudServletTTT
    String counter = getCounterValue(context);
    ^

    Why would you make the Context Listener also responsible for keeping track of the counts?
    1st of all, you are doing this inside the Servlet:
    String counter = getCounterValue(context); // passing context object.
    But the servlet does not have a mehtod called getCounterValue. You need to call the CounterContextListener's method, which means you have to create one:
      CounterContextListener ccl = new CounterContextListener();
      String counter = ccl.getCounterValue(context);Second, why give the counter context listener two jobs that it doesn't need? You should make a new object - a Counter class:
    public class Counter {
      private int count;
      public Counter() { this(0); }
      public Counter(String initialValue) {
        this(Integer.parseInt(initialValue);
      public Counter(Integer initialValue) {
        this(initialValue.intValue());
      public Counter (int initialValue) {
        count = initialValue;
      public Integer getCount() { return new Integer(count); }
      public void increment() { addCount(1); }
      public void decriment() { addCount(-1); }
      public void addCount(int amountToAdd) {
        count = count + amountToAdd;
    }Then in your context listener, all you do is add one of these to the context:
    public class CounterContextListener implement ServletContextListener {
        public void contextInitialized(ServletContextEvent sce) {
            ServletContext context = sce.getServletContext();
            Counter counter = new Counter();
            context.setAttribute("counter", counter);
        public void contextDestroyed(ServletContextEvenet sce) {
        }In your servlet, you get the counter from the context, get the count, and increment it if you want to:
    public void MyServlet exctends HttpServlet {
        public void doPost( ... ) ... {
            ServletContext context = this.getServletContext();
            Counter counter = context.getCounter();
            int count = counter.getCount();
            counter.increment();
    }

  • I want to use static variable instead of using variable in servlet context

    Hi all,
    In my web application i have to generate a unique Id.
    For this, At the application startup time i am connecting to the database and getting the Id and placing it in the servlet context.
    Every time i am incrementing this id to generate a unique id.
    But, now i want to place this id in a static variable which is available to all the classes.
    why i want to do this is to reduce burden on servlet context.
    my questing is, is this a best practice ? If not please give me your valuable suggestion.
    thanks
    tiru

    There isn't a problem with this as long as you want to share the value of that variable with all requests. If this is read-only except when it is first set then you're fine. The only real issue will be how to initialize and/or reinitialize the variable. When the servlet is started, how will you get the value for the variable? If the servlet is shutdown and restarted (a possibility in any application server) how will you re-read the variable? You need to answer these questions to decide the best route. It may be as simple as a static initializer or it may be more complex like a synchronized method that is called to see if the variable is set.

Maybe you are looking for