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?

Similar Messages

  • 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.

  • Reference EJB from servlet's action/helper classes

    Hello
    How to make a reference to stateless session bean from one of the helper classes of a servlet WITHOUT using any of these:
    * dependency injection (like @EJB) - I think this is not supported in this kind of class, EJB references can be injected only to servlets themselves or some other things (but not objects of classes "accompanying" a servlet)
    * home or local home interfaces (I would like to avoid writing them)
    * using mappedName (either in @Stateless or in ejb-jar) - since meaning of this is application-server dependent and thus not portable.
    By a "class accompanying a servlet" / "helper class" I mean utility or action classes, like MyActionClass, which would be instantiated and then used by a aforementioned servlet.
    Thanks.

    The EJB dependency must be looked up via the java:comp/env namespace since as you point out
    Java EE 5 environment annotations are not supported on POJOs. However, the dependency itself
    can either be defined using @EJB on some other managed class in the .war or within the
    web.xml. We have an entry in our EJB FAQ that has the details :
    https://glassfish.dev.java.net/javaee5/ejb/EJB_FAQ.html#POJOLocalEJB
    Also, whenever the client component resides in the same application as the target EJB (which is
    required for Local access but not for Remote access) there is no need to use mappedName to
    resolve the EJB dependency. It is either automatically resolved if the business interface type of
    the EJB dependency is only exposed by a single EJB in the application, OR the beanName()
    / ejb-link attributes can be used to unambiguously identify the target EJB using ejb-name.
    You can find more about this in the FAQ as well.

  • Servlet cannot find helper class

    Hello
    Under WEB-INF/classes I put ServletExample and SingletonExample. Compiling ServletExample, that makes use of SingletonExample, works.
    In the directory WEB-INF/classes I also have another direcotry, test. And in WEB-INF/classes/test I put again ServletExample and SingletonExample.
    Here I have tried in several ways to compile the servlet, but I always get an:
    Cannot find symbol class SingletonExample.
    I tried writing package test at the top of both files, and even at the top of only one of these two.
    I even tried to make WEB-INF/classes/test/ServletExample make use of SingletonExample residing in WEB-INF/classes, but I didnt succeded.
    What happens when you have subdirectory in WEB-INF/classes/? I think this is a MUST, to have subdirectory in large webapplication, so I really dont want to put everything in the classes directory.
    Do you how to resolve this prolem? And: if Im in WEB-INF/classes/test and want to referr from a servlet residing in this direcory to a Singleton/helper class residing in WEB-INF/classes/, which approach do I have to use?
    Thanks
    Paolo

    Jeez, you aren't gonna get very far in Java like this.
    CLASSPATH is wrong - again. You're supposed to give JARs and paths where the class loader is supposed to look, not the actual .class file.
    Also, you're not telling the compiler to put the .class file in the package directory structure.
    Your example is pretty awful. Try this:
    Put this code into c:\common
    package common;
    import common.test.TestDown;  // What the hell is this?  There is no package test, but there is a package named common.test
    public class TestUp
       public void sayHello()
          System.out.println("Hello.....");
    }Put this code into c:\common\test
    package common.test;
    import common.TestUp;
    public class  TestDown
       public TestDown()
            TestUp testUp = new TestUp();
            testUp.sayHello();
       public static void main(String[] args)
            new TestDown();
    }Open a command shell and navigate to c:\, then do the following:
    Directory of c:
    07/01/2005  03:43 PM    <DIR>          .
    07/01/2005  03:43 PM    <DIR>          ..
    07/01/2005  03:45 PM    <DIR>          common
                   0 File(s)              0 bytes
                   3 Dir(s)  74,909,675,520 bytes free
    C:\>javac -d . common\*.java
    C:\>javac -d . common\test\*.java
    C:\>java -classpath . common.test.TestDown
    Hello.....Once you've got your head around this, go learn Ant and have it compile your projects properly.
    %

  • Servlet and CSS help!!

    Hi everyone!
    This may be the simpliest thing to most of you but I'm just wondering if anyone can give me a little help on how i can call and use a CSS in a servlet...
    Here's what i tried:
    out.println("<link rel=\"alternate stylesheet\" href=\"someCSS.css\" type=\"text/css\" title = \"someCSS\">");
    I have also tried putting the .css files inside different directories
    Web\WEB-INF\classes\someCSS.css
    or
    Web\WEB-INF\someCSS.css
    or even
    Web\someCSS.css
    I really don't know what's wrong, I did try searching through the forums but it's not leading me anywhere, one suggested to use request.getContextPath() + \"/myStyle.css\" but i tried a couple of different ways to implement it(having it by itself, having it inside the out.println("") things...) but it just gives errors to that line..... if i'm doing it in a completely wrong way can anyone point me in the right direction??
    Anyone who can help would be greatly appreciated :)
    Tomato

    I just put the CSS file in the web application directory (this one: Web\someCSS.css) and my HTML simply says <link ... href="someCSS.css">. Works just fine. Of course if your servlet isn't in a web application but has a customized mapping, then I have no idea.

  • Using class from an API named System and builtin System class

    For some godforsaken reason the guys at sprint decided to name one of their utility classes System so it clashes with the java.lang.System class. Their must be an easy way to use both of these at the same time but I havent come across it yet. Anyone??
    Heres what I got so far:
    import com.sprintpcs.util.System;
    System.gc() //fails becasue it now looks at other sprint System class
    System.promptMasterVolume();
    Thanks;
    Sam

    use the full class name (inc. package), so
    java.util.System.out.println( "format the bastards harddisk" );
    com.bastard.System.format();

  • I need a clarification : Can I use EJBs instead of helper classes for better performance and less network traffic?

    My application was designed based on MVC Architecture. But I made some changes to HMV base on my requirements. Servlet invoke helper classes, helper class uses EJBs to communicate with the database. Jsps also uses EJBs to backtrack the results.
    I have two EJBs(Stateless), one Servlet, nearly 70 helperclasses, and nearly 800 jsps. Servlet acts as Controler and all database transactions done through EJBs only. Helper classes are having business logic. Based on the request relevant helper classed is invoked by the Servlet, and all database transactions are done through EJBs. Session scope is 'Page' only.
    Now I am planning to use EJBs(for business logic) instead on Helper Classes. But before going to do that I need some clarification regarding Network traffic and for better usage of Container resources.
    Please suggest me which method (is Helper classes or Using EJBs) is perferable
    1) to get better performance and.
    2) for less network traffic
    3) for better container resource utilization
    I thought if I use EJBs, then the network traffic will increase. Because every time it make a remote call to EJBs.
    Please give detailed explanation.
    thank you,
    sudheer

    <i>Please suggest me which method (is Helper classes or Using EJBs) is perferable :
    1) to get better performance</i>
    EJB's have quite a lot of overhead associated with them to support transactions and remoteability. A non-EJB helper class will almost always outperform an EJB. Often considerably. If you plan on making your 70 helper classes EJB's you should expect to see a dramatic decrease in maximum throughput.
    <i>2) for less network traffic</i>
    There should be no difference. Both architectures will probably make the exact same JDBC calls from the RDBMS's perspective. And since the EJB's and JSP's are co-located there won't be any other additional overhead there either. (You are co-locating your JSP's and EJB's, aren't you?)
    <i>3) for better container resource utilization</i>
    Again, the EJB version will consume a lot more container resources.

  • 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

  • Servlets and EJBs in weblogic 5.1

              Me somebody can say like communicating servlet that this in a machine with Weblogic 5,1 with a EJB in another machine also with weblogic5.1
              When trying gives it to me Comunication Exception .
              But if I have the 2 in the same machine it works well
              

    We have the same scenario and had the same CommunicationException.
              We had the remote & home interfaces of the ejb and the helper classes
              avaliable
              to the server#1 , and still encountered the following CommunicationException
              Tue Feb 06 17:53:54 GMT+05:30 2001:<I> <ServletContext-General>
              scripInfoServletWAP25:
              ScripInfoServlet.init()javax.naming.CommunicationException [Root exception
              is weblogic.rmi.UnmarshalException: Unmarshalling return
               - with nested exception:
              [java.lang.ClassNotFoundException: class
              ITS.beans.order.ScripInfoSessionEJBHomeImpl_ServiceStub previously not
              found]]
              Tue Feb 06 17:53:54 GMT+05:30 2001:<E> <ServletContext-General> Servlet
              failed with Exception
              javax.servlet.ServletException: javax.naming.CommunicationException [Root
              exception is weblogic.rmi.UnmarshalException: Unmarshalling return
              - with nested exception:
              [java.lang.ClassNotFoundException: class
              ITS.beans.order.ScripInfoSessionEJBHomeImpl_ServiceStub previously not
              found]]
              at ITS.wap.ScripInfoServletWAP25.init(ScripInfoServletWAP25.java:83)
              at
              weblogic.servlet.internal.ServletStubImpl.createServlet(ServletStubImpl.java
              :390)
              at
              weblogic.servlet.internal.ServletStubImpl.createInstances(ServletStubImpl.ja
              va, Compiled Code)
              at
              weblogic.servlet.internal.ServletStubImpl.prepareServlet(ServletStubImpl.jav
              a:338)
              at
              weblogic.servlet.internal.ServletStubImpl.getServlet(ServletStubImpl.java:16
              4)
              at
              weblogic.servlet.internal.ServletStubImpl.invokeServlet(ServletStubImpl.java
              :99)
              at
              weblogic.servlet.internal.ServletContextImpl.invokeServlet(ServletContextImp
              l.java:742)
              at
              weblogic.servlet.internal.ServletContextImpl.invokeServlet(ServletContextImp
              l.java:686)
              at
              weblogic.servlet.internal.ServletContextManager.invokeServlet(ServletContext
              Manager.java:247)
              at
              weblogic.socket.MuxableSocketHTTP.invokeServlet(MuxableSocketHTTP.java:361)
              at weblogic.socket.MuxableSocketHTTP.execute(MuxableSocketHTTP.java:261)
              at weblogic.kernel.ExecuteThread.run(ExecuteThread.java, Compiled Code)
              Only when the jar file was made available to the server#1(i.e. present in
              weblogicclasspath but not deployed) was the servlet on server#1 able to call
              the ejb on server#2.
              When calling the ejb through a Java Application or through a servlet
              deployed on the same server as the ejb,
              the stub classes are not required to be specified in the weblogicclasspath.
              Has anybody else encountered a similar situation?
              Thanks in advance.
              Aparna
              "Cameron Purdy" <[email protected]> wrote in message
              news:[email protected]...
              > You can have a Servlet on server #1 talk to an EJB on server #2. It is
              > accomplished by having the client classes for the EJB available to the
              > Servlet on server #1 and using JNDI on server #1 to get initial context
              for
              > server #2 and using that to look up the EJB.
              >
              > (Sorry, no habla espanol.)
              >
              > --
              > Cameron Purdy
              > Tangosol, Inc.
              > http://www.tangosol.com
              > +1.617.623.5782
              > WebLogic Consulting Available
              >
              >
              > "Javier Fdez" <[email protected]> wrote in message
              > news:[email protected]...
              > >
              > > Me somebody can say like communicating servlet that this in a machine
              with
              > Weblogic 5,1 with a EJB in another machine also with weblogic5.1
              > > When trying gives it to me Comunication Exception .
              > > But if I have the 2 in the same machine it works well
              >
              >
              

  • EJB and helper classes ...

    I have created an EJB component which uses
    some helper classes in JDeveloper 3.0 .
    The component deploys sucessfully to OAS 4.0.8.1 . When I try to run the component through an applet ( including the _client.jar
    in the archive tag) , the applet does not find the helper classes . How I do i include the helper classes in the _client.jar file ?                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    Hi,
    Try to put all the EJB's in a single package and import the package. I
    can think of this solution right now, will keep posting for updates.
    Regards
    Raj
    Daniel Westerdale wrote:
    Hi,
    I have a number of EJBs that each use a common set interfaces,
    exceptions and Value beans. If I deploy using the iasdeploy command
    line, then I must package up all these common classes within each of
    the EJB modules - leading to a lot of duplicate code.
    Is there a smarter a way of packaged the common classes so that I can
    include them in the .EAR file but only in one module.
    Note: I would prefer to only argument the IAS classpath with 3rd party
    classes that rarely change and not these common classes e.g. Jlog
    cheers
    Daniel
    Try our New Web Based Forum at http://softwareforum.sun.com
    Includes Access to our Product Knowledge Base!

  • FXML and Controller base classes?

    Hey Guys,
    Another FXML question: does anyone know if it is possible to get FXMLLoader to pick up the FXML annotations on base classes?
    If we have this:
    public class MyBaseController
        @FXML
        protected Label myLabel1;
    } And this:
    public class MyController extends MyBaseController
        @FXML
        protected Label myLabel2;  
    } And then we load some FXML that references MyController as its controller, it seems only the direct properties on the Controller class are mapped (i.e. 'myLabel2') and not the inherited ones (i.e. 'myLabel1').
    I'm guessing it just hasn't been written this way?
    Greg - I don't suppose sharing the source code for FXMLLoader is an option? It would certainly help us early users work out what we're doing in lieu of more complete docco.
    Cheers,
    zonski

    Just in case anyone is interested, the answer to this question is currently 'no'.
    JIRA issue for it here: http://javafx-jira.kenai.com/browse/RT-16722

  • Helper Classes

    Hi,
    going through the J2EE Tutorial you'll read on page 76 that Helper Classes "... must reside in the EJB JAR file that contains the enterprise bean class".
    Now, when deploying the cart example, the BookException class is included in both EJB JAR and Client JAR files.
    I would like to understand this construction. Can you help me?
    TIA
    Ivo

    Hi Iwo,
    The reason why the BookException is placed both in the EJB Jar and in the Client Jar is that both the server and the client must know the Exception. Basically you can devide your bean into three parts:
    Remote interface, which is known both by the client and the server.
    Home interface, do.
    EJB class, which only the server knows.
    When an exception is declared thrown at an interface, then the Exception must be included beside the interface otherwise a ClassNotFoundException will be thrown.
    Second, the reason why the helper classes must be included in the EJB jar is that the enterterprise bean is using the classes. If you do not include the Helper classes the bean will not be able to instantiate the Helper classes and it will not work.
    Hope this information will be helpful to you.
    Regards,
    Jess

  • Servlets and their instance variables

    I understand that for every request to a servlet, a new thread handles those requests. So it's one request, one thread. But how about instance variables of a servlet class? Are they also one instance variable per thread/request or just like the servlet, one instance?

    hi, its exactly as you expect - one instance at all. all threads are working with one intance. you can indeed finetune the number of instances of a servlet using the
    <load-on-startup/>tag in the web.xml file, but its up to container if multiple thread will be using many instances.
    you can also implement the (deprecated) SingleThreadedModel interface which flags the container not to share that servlet instance to other threads. But this shall not be used in productive environments.
    so its always a good idea to put your business impleementation to another class and only use the servlets to connect your business implementation to http like
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException{
       new MyBusinessLogic().perform(request.getInputStream(), response.getOutputStream());
    }

  • How to access function from Top Class to Function of class that contain the the member variable of TopClass

    Dear All,
    is there any way that i can access function or member variable of aggregate class.
    i am working in Visual Studio 2010 
    and making win32 dll with mfc Support. i am new in dll system. just learning and doing.
    previously all in exe and i am working this like
    CTestDoc*pDoc = (CTestDoc*)GetTestDocument();
    somevar = pDoc->xDoc.mVar.GetValue (); 
    now i am trying to put all in dll. so getting problem 
    will i get help on this. thanks in advance.
    below code is just an example.
    for example
    // dll 1
    class aaa : public BaseClass
    public:
    int Index;
    char *cName;
    void doSometing()
    if (GetCurBColor() == 125) // how to access GetCurBColor function of the
    color = GetCurBColor();
    long color;
    // dll 2
    class bbb :public BaseClass
    public:
    int Index;
    long lSize;
    long color;
    void doSometing();
    // dll 3
    class DDD
    public:
    vector <aaa> va;
    vector <bbb> vb;
    int cura;
    int curb;
    long GetCurBColor ()
    return vb[curb].color;
    };// MFC doc/view support
    /// in exe in document
    class inExe
    public:
    DDD d;
    void addB()
    { bbb bb;
    bb.color = 152;
    d.vb.push_back(bb);
    bb.color = 122;
    d.vb.push_back(bb);
    bb.color = 1232;
    d.vb.push_back(bb);
    d.curb = 1;
    void addA()
    { aaa aa;
    aa.color = 152;
    d.va.push_back(aa);
    aa.color = 1232;
    d.va.push_back(aa);
    aa.color = 1542;
    d.va.push_back(aa);
    aa.color = 15;
    d.va.push_back(aa);
    d.cura = 2;
    d.va [1].doSometing ();

    Dear All,
    is there any way that i can access function or member variable of aggregate class.
    i am working in Visual Studio 2010
    and making win32 dll with mfc Support. i am new in dll system. just learning and doing.
    previously all in exe and i am working this like
    CTestDoc*pDoc = (CTestDoc*)GetTestDocument();
    somevar = pDoc->xDoc.mVar.GetValue ();
    now i am trying to put all in dll. so getting problem
    What problem?
    The rules of C++ do not change because some of the code ins in a DLL. But the classes in a DLL need to be exported. See for example
    https://msdn.microsoft.com/en-us/library/81h27t8c.aspx
    You should also supply a macro so that the class header can be used in both the DLL and the client. See for example
    http://stackoverflow.com/questions/14980649/macro-for-dllexport-dllimport-switch
    If  you exchange memory between the DLL and the client (as your example will do, because of the std::vector content), you should also be sure to use the same version of the compiler for each module, and to dynamically link to the CRT.
    I would also advise you to start with a less complicated scenario, with just one DLL.
    David Wilkinson | Visual C++ MVP

  • From Where should i download Servlets and how to set Environment variables?

    Hi,
    I want to download the Servlets Kit for my development of application,but couldnt find it.I found a zip file containing all class files.If that is the correct one,then how should i set my environment variables?
    thanks
    rao

    Your files should come in a folder with the name "Javax" and subfolders right?
    What you can do is to paste the file "Javax" in your folder of your JDK installation.
    For example, I have installed my JDK in C:\Java\jdk1.3
    I added one new folder in C:\Java\jdk1.3 called classes.
    Then I would put the Javax folder in classes.
    PS : We add one new folder called classes so that in future when you want to add new classes you can just into this folder.
    Then in your enviroment settings, simple point to C:\Java\jdk1.3\classes;.;
    This works for me. Hopefully you will no problems!
    jing
    170902

Maybe you are looking for

  • Cost of Goods Sold Turnover Ratio query

    Has anyone written a Cost of Goods Sold Turnover ratio query?  The formula would be Cost of goods sold/(beginning inventory+ending inventory/2) within a specified date range at the item key level. Thank you for any assistance Gary

  • Connecting Computer to my Tv

    Hi, i was wondering if i can connect my computer to my tv to watch shows (mainly wrestling) we do not have cable. I was planning on getting a HDMI cable and connecting to my tv. My question is will that work? and will i be able to use my computer whi

  • EF6: How can I get navigation properties automatically updated?

    I've defined the following entities: public abstract class EntityBase public int Id { get; set; } public string Name { get; set; } public class Person : EntityBase public virtual HashSet<Message> Messages { get; set; } public int CountryId { get; set

  • Function keys status is not showing on screen

    Hi... please help me.  I m havin lenova ideapad s10-2 netbook. In this when i press fn + function keys action is performing but its status is not displaying on screen. So if i want to switch on WLAN when i press fn+F5 screen is not showing. Also usb

  • Att: "ORACLE REPORTS TEAM"

    Hi, I have a report in RDF format which need further calculation and generation of Graph.So,I want to convert this report to XLS (Excel). Is there any Solution from "ORACLE REPORTS TEAM"? santosh