Session member variable usage

I want to keep client-specific information for each incoming connection, but i heard it cannot be done with session variable. i read in a book that session variables in a servlet (or scriptlet section of a jsp page) are shared among all incoming threads (therefore all clients) accessing the servlet.
I guess a simple example of what i want to acheive is a shopping cart, but keeping the shopping cart order in a session-like variable specific to the original client machine/user who placed the order.
I thought of doing something like:
request.getSession().setAttribute("ShoppingCart", cart);
inside my doGet() method in a servlet. And a book author says it won't work. He says ff I use a member to keep information about user1, sometimes the session variable may be overwritten by user2 if they are accessing the servlet at the same time.
1) Can someone confirm whether session variables are shared among all incoming requests to the same servlet?
2) If so, how can i easily keep track of incoming user/client mahcine-specific information, without using cookies or other client-side storage methods.
3) If client side storage is necessary (to keep user info), what are the common techniques and the classes used?
I am fairly new to j2ee so i would appriciate it if you can explain in layman's terms.

Hi,
Session scope is made to save the user specific information only. All class(servlet) level members(state) can be shared by all incoming thread. So its a bad practice, if we used class level session variable which stores the client specific info.
I dont think session will overwritten if you used session var locally(inside any method).
When any user logs in you should create a new session for that user.
Means if you have LoginServlet.java file which have log in functionality, Here only you need to create new session.
HttpSession session = request.getSession();
Other than this file every where you need to use
request.getSeission(false);
In your case it would be
request.getSession(false).setAttribute("ShoppingCart", cart);
Hope This will help you.

Similar Messages

  • Class/member variables usage in servlets and/or helper classes

    I just started on a new dev team and I saw in some of their code where the HttpSession is stored as a class/member variable of a servlet helper class, and I was not sure if this was ok to do or not? Will there be problems when multiple users are accessing the same code?
    To give some more detail, we are using WebLogic and using their Controller (.jpf) files as our servlet/action. Several helper files were created for the Controller file. In the Controller, the helper file (MyHelper.java) is instantiated, and then has a method invoked on it. One of the parameters to the method of the helper class is the HttpServletRequest object. In the method of the helper file, the very first line gets the session from the request object and assigns it to a class variable. Is this ok? If so, would it be better to pass in the instance of the HttpServletRequest object as a parameter to the constructor, which would set the class variable, or does it even matter? The class variable holding the session is used in several other methods, which are all invoked from the method that was invoked from the Controller.
    In the Controller file:
    MyHelper help = new MyHelper();
    help.doIt(request);MyHelper.java
    public class MyHelper {
        private HttpSession session;
        public void doIt(HttpServletRequest request) {
            session = request.getSession();
            String temp = test();
        private String test() {
            String s = session.getAttribute("test");
            return s; 
    }In the past when I have coded servlets, I just passed the request and/or session around to the other methods or classes that may have needed it. However, maybe I did not need to do that. I want to know if what is being done above will have any issues with the data getting "crossed" between users or anything of that sort.
    If anyone has any thoughts/comments/ideas about this I would greatly appreciate it.

    No thoughts from anyone?

  • Default initialisation of member variables and local variables

    I don't understand why member variables are initialized with default values by Java.
    Objects are initialized with "null" and primitives with "0", except boolean, which is initialized with "false".
    If these variables are used locally they are not initialized. The compiler requires them to be initialized by the programer, for example "String s = null".
    Why? What is the use of that difference?
    And why are arrays always initialized with default values, no matter if they are member variables or local variables? For example String[] s = new String[10]; s[0] to s[9] are initialized with "null", no matter if "s" is a local or member variable.
    Can someone please explain that strange difference, why it is used? To me it has no sense.

    Most of the time I have to initialize a local variable
    with "String s = null" in order to use it because
    otherwise the compile would complain. This is a cheap
    little trick, but I think everyone uses it.
    I wouldn't agree with "most of the time". The only cases where it is almost necessary to do that is when the variable should be initialized in a loop or a try-catch statement, and that doesn't happen too often.
    If local variables were initiliazed automatically without a warning it would be a Bad Thing: the compiler could tell when there is a possibility that a variable hasn't been assigned to and prevent manymanymany NullPointerExceptions on run time.
    And you didn't answer me why this principle is not
    used with arrays if it is so useful as you think.
    Possibly it is much more difficult to analyse the situation in the case of arrays; what if values are assigned to the elements in an order that depends on run time properties such as values returned from a random number generator.
    The more special rules one has to remember, the more
    likely one makes errors.I agree, but what is the rule to remember in this case?

  • Different ways to referencing Session State variables

    Hi,
    According to APEX documentation there's 4 different ways to reference session state variables: http://download-west.oracle.com/docs/cd/B32472_01/doc/appdev.300/b32471/concept.htm#BEICHBBG
    In an inline PL/SQL statement, what's the difference when using the different methods? I remember reading something that the bind and static text have a size restrictions. What's the difference between the V() and NV() functions?
    Thank you.
    Martin

    Martin,
    In PL/SQL, the preferable method is to use bind variable notation, e.g., :P1_ITEM. In HTML contexts, you must use &ITEM. notation. In stored procedures, you can use v or nv, the latter function being identical to the former with the additional characteristic that it raises an exception if the retrieved value is non-numeric.
    Scott

  • GetVariable() doesn't work in FireFox for object member variables

    I'm trying to access Flash member variables from Javascript
    using GetVariable. The following line of code works for IE but not
    for Firefox:
    var variable = swf.GetVariable("someObject.someProperty");
    In IE, the GetVariable() function returns the correct value
    for the property. However in Firefox, the GetVariable() function
    returns "null" when trying to access the property. If I just try to
    access the object in Firefox (i.e. swf.GetVariable("someObject"), I
    get a string back (instead of the object that I am expecting). If I
    try to access a variable (such as a string) and not an object using
    GetVariable(), this works in both Firefox and IE.
    Any ideas what I am doing wrong? I suspect that my syntax for
    accessing object member variables in Firefox is incorrect but I
    have not been able to find any documentation on the correct syntax.
    Any assistance would be greatly appreciated.
    Thanks.

    Thanks, but this isn't an issue.
    The window.document.flashMovie will return the correct flash
    object/embed flash movie.
    The issue is that the GetVariable method wont return the
    object variable. When you try to get an simple variable that is in
    the _root timeline, it will return the value. Example:
    movie.GetVariable(_url) will return the url of the flash
    movie without any problem.
    But when you create an ActionScript class with
    userName property and then you will create the instance of
    it in the _root, you should be able to get it's value. Example:
    Flash:
    var obj = new SomeClass();
    obj.userName = "peter";
    JavaScript:
    movie.GetVariable("/obj:userName");
    or
    movie.GetVariable("obj.userName");
    This will return
    Peter for IE and null for Forefox/Opera.
    The same when you use the document.embeds[..].

  • How can I view the member variable while debugging

    When I using JCOP-debug mode in eclipse, I want to view the variable in the Variable window. I can see the "this" instance in the window. But when I click the "+" beside "this" to view the member variables of the instance. Debug process is terminated, following lines displayed in console window:
    ASSERTION FAILED: Object header element PAK must be odd!
    Expression: (o->pak&1)==1
    File: simulation.c
    Line: 393
    What can I do then?

    http://forum.java.sun.com/thread.jspa?threadID=722788
    http://download.boulder.ibm.com/ibmdl/pub/software/dw/jcop/tools.zip

  • Session state variables across multiple ApEx applications

    We have a suite of loosely integrate ApEx applications that all share a common authentication scheme. When you first log in we attempt to load a series of session state variables with temporary data to streamline various logging and authentication related activities for the life of the session.
    However, these session variables seem to disappear when you move from one application to another, so they are not truly tied to just the "session" which carries over across all applications, but the application from which the session state is set.
    What is the suggested way, keeping in mind that the data being held may have security related context, to preserve values during a session, but regardless of which ApEx application you are in.
    The method we are using to share the authentication is using a common "Cookie Name" from a common subscribed authentication scheme as suggested elsewhere on this site and seems to work very well outside of this specific issue.
    Thanks in advance,
    Barney

    Apologies for the delay getting back on this.
    My use of the word "disappear" was probably misleading. They were not visible from the second application. When setting "Session State" I was under the impression that it was setting it for the authenticated session, not for the specific application. (I am referring to the: apex_util.set/get_session_state).
    Your solution will work fine, as long as I know which application the user last authenticated against. However, it could be one of over 30 (and growing) different applications which would require me writing a program to go through every "p_flow" to try and find a valid value every time I need to reference the field.
    It would be really beneficial if you could store true Session variables which stay alive for the life of the authenticated session and is available to anything authenticated against that session id. This would streamline alot of cross-application program development.
    The "get/set_session_state" is a misleading as it is not a Session value, but an Application value. The Session exists across multiple applications, while this procedure does not.
    Thanks,
    Barney

  • Session-scope variable for JSP page used in a frame

    Hi,
    I don't know if there's a way to do this at the same time:
    (1)- assign session scope to a variable (in order to be able to retrieve recurrently the previous value each time the JSP is called);
    (2)- set its visibility in a way that it could be accessed only by the page that defines it. The JSP is used in a frameset along with an other JSP that can potentially define identical session-scoped variable (You understand why I want to keep them separate)
    session.setAttribute():
    seems not to be the thing I need
    pageContext.setAttribute():
    with SESSION_SCOPE, it behaves the same way as session.setAttribute(). with PAGE_SCOPE, condition (1) can't be satisfied.
    Does anybody have an idea ?
    Thanx in advance.

    I can see that you will not want to maintain two different files for every possible page on the site!
    It may be possible to do something like <frameset rows="*" cols="50%,*">
      <frame name="content1" src="file.jsp?frame=one" >
      <frame name="content2" src="file.jsp?frame=two" >
    </frameset>and then in the jsp<%
    String frame=request.getParameter("frame");
    session.setAttribute(frame+"AttributeName",attributeValue);
    %>This will set up two session attributes - "oneAttributeName" and "twoAttributeName". Depending on how many variables you have, this may prove just as difficult to maintain.
    You may end up having to simply pass url parameters between pages to maintain state within the individual frames, which is far from elegant also.
    I am interested in how you end up solving this one.

  • SQL Queries don’t recognize Package member variables.

    Hi,
    I have a package defined like this:
    CREATE OR REPLACE PACKAGE PROD.PKG_BSYS_COMMON
    AS
    MAX_RETURN_ROWS NUMBER(6) :=1000;
    END PKG_BSYS_COMMON;
    The problem is that I cannot use MAX_RETURN_ROWS in my SQL queries:
    SELECT
    FROM
    CLIENT
    WHERE
    ROWNUM < PROD.PKG_BSYS_COMMON.MAX_RETURN_ROWS
    Is there any way to use that package member variable in my queries?
    This is a simplified explanation of our problem and it is very important for our business to avoid hardcoding constants in queries and define all of them in a central location. Is there a better way doing this?
    Any help would be appreciated,
    Alan

    CREATE OR REPLACE PACKAGE PKG_BSYS_COMMON
    AS
    function max_return_rows return number ;
    END PKG_BSYS_COMMON;
    CREATE OR REPLACE PACKAGE body PKG_BSYS_COMMON  as
    function max_return_rows return number is
    begin
    return(1000);
    end;
    end PKG_BSYS_COMMON;
    select pkg_bsys_common.max_return_rows from dual;
    MAX_RETURN_ROWS
               1000                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Member variable verses method parameter to pass information

    Hi all,
    Is the a performance penalty in using method parameter, such as a String, to pass information into multiple methods( method1(String X), method2(String X), etc ) in a class verses using a class member variable to pass the information to the methods?
    Thanks.

    Never, ever, ever make a decision as to what should be parameter and what should be field based on this kind issue. If the value is reasoably part of the state of the object it should stored (or referenced by) a field. Otherwise it should not and so your left with it being a parameter or an atribute of some other object.
    There is little if any performance cost in passing a parameter (on the order of 10's to 100's of nanoseconds on modern computers and JVM's. Optimizing in this area will only noticeably impact performance of such calls if it needs to get performed 100's of thousands or millions of times per second. That generally excludes everything any of us is likely to write.
    Chuck

  • All variable usage

    hi, I am new to sap-abap.
    i want to learn more about variable usage in abap.
    can anyone guide me?
    regards,
    hema.

    hi hema,
    this will guide u.
    hi,
    *& Report Z_OOABAP18 *
    &----REPORT Z_OOABAP18 .CLASS lcl_employee DEFINITION.
    PUBLIC SECTION.
    The public section is accesible from outside
    TYPES:
    BEGIN OF t_employee,
    no TYPE i,
    name TYPE string,
    END OF t_employee.
    METHODS:
    constructor
    IMPORTING im_employee_no TYPE i
    im_employee_name TYPE string,
    display_employee.
    Class methods are global for all instances
    CLASS-METHODS: display_no_of_employees.
    PROTECTED SECTION.
    The protecetd section is accesible from the class and its subclasses
    Class data are global for all instances
    CLASS-DATA: g_no_of_employees TYPE i.
    PRIVATE SECTION.
    The private section is only accesible from within the classs
    DATA: g_employee TYPE t_employee.
    ENDCLASS.
    LCL Employee - Implementation
    CLASS lcl_employee IMPLEMENTATION.
    METHOD constructor.
    g_employee-no = im_employee_no.
    g_employee-name = im_employee_name.
    g_no_of_employees = g_no_of_employees + 1.
    ENDMETHOD.
    METHOD display_employee.
    WRITE:/ 'Employee', g_employee-no, g_employee-name.
    ENDMETHOD.
    METHOD display_no_of_employees.
    WRITE: / 'Number of employees is:', g_no_of_employees.
    ENDMETHOD.
    ENDCLASS.
    R E P O R T
    DATA: g_employee1 TYPE REF TO lcl_employee,
    g_employee2 TYPE REF TO lcl_employee.
    START-OF-SELECTION.
    CREATE OBJECT g_employee1
    EXPORTING im_employee_no = 1
    im_employee_name = 'Vikram.C'.
    CREATE OBJECT g_employee2
    EXPORTING im_employee_no = 2
    im_employee_name = 'Raghava.V'.
    CALL METHOD g_employee1->display_employee.
    CALL METHOD g_employee2->display_employee.
    regards,
    madhu.

  • How to use member variable to all my pakages

    i want to use some member variables to all my packages in my project how to declare it.

    why doesn't declaring it public works for you. You may declare it public static, if want to get rid of creating objects of the containing class.

  • How to activate and passivate member variables?

    Hi
    ViewObjects have methods like
    public void passivateState(ViewRowImpl currentRow, Document doc, Element parent)andpublic void activateState(ViewRowImpl currentRow, Element elem)However, I can't find any example how to use them. Can anyone show me a code example how to use this methods? Can anyone point me to some documentation on this?
    Thank
    Frank Brandstetter

    Sorry, I should have mentioned, that I want to use this methods to passivate some member variables stored in my View. BC4J JavaDoc says, that I must override this methods to do this. But how?
    Thanks

  • Coldfusion session/client variables?

    We have multiple users using VPN to get to our intranet.  When the second user gets on they get the first person's session/client variables?
    I have tried looking for the session/client variables and where they are stored but I can't seem to find them.  I have tried searching out the cookies.
    I would appreciate any help.

    There are not too many people on this forum that have dabbled with ColdFusion. I used to, but that was more than one decade ago.
    Your best bet on getting assistance with your problem, is to go to the ColdFusion forum.

  • Session scope variables and weird behaviour of AdfContext()

    Hello,
    what is the best method and correct API to create a session scope variable?
    I am currently using ADFContext().getCurrent().getSessionScope().get()/put(), but it looks like it has some problems: for some unkown reasons I loose the variable, that is get() returns null when called from a method of a (overridden)ViewRowImpl. Why does this happen?
    Thanks you in advance

    There are a couple of ways you can set values on a sessions scope but I would have to question if you really need a scope as high as session to accomplish what you want to do. At any rate, you should be able to store the value using the method you described but you could also try setting it using EL by using the setExpressionValue and resolveExpression methods in JSFUtils.java (you can find this in the latest fusion demo application). JSFUtils also has a getFromSession and storeOnSession that you could try.
    With all that said I don't think it is good practice to access scope variables from your model layer. You should write your method in the ViewRowImpl class to accept the value as a method parameter and then pass the value in through the binding layer or when invoking the method from your bean class.

Maybe you are looking for