Servlet and Class instances

Under normal conditions a web-container creates only one instance of servlet.Now the case is I am creating instance of a class in the servlet.So for every request to the servlet does an instance of the class is created?

If you make the instance in a service method (service(), doGet(), doPost() etc...) then yes, each request will create a new instance.
If you create the instance anyplace else, no they will share it.
If you hold the reference to the class in the servlet class level as opposed to storing it in the method which creates and uses it, then you can run into problems as well, since there will be only one reference for all requests.
So generally speaking in Servlets (and in any application you need to worry about thread safety:
This is bad. One object will be used by all requests:
public class BadServlet ... {
    Object myObject = new Object();
    public void doGet(...) ... {
        do something with myObject;
}This is bad. A new instance is made for each request, but only one reference. So one request will end up using another's instance:
public class BadServlet ... {
    Object myObject;
    public void doGet(...)... {
        myObject = new Object();
        do something with myObject;
}This is how you would do it in a thread safe manner:
public class GoodServlet ...{
    public void doGet(...)... {
        Object myObject = new Object();
        //Another method in same class needs a reference?  Pass it as a parameter
        someOtherMethod(myObject);
        //Some other servlet needs access?  Store it in Request scope
        request.setAttribute("myObject", myObject);
        //Some other request needs to access it?  Put it in the session scope
        HttpSession session = request.getSession();
        session.setAttribute("myObject", myObject);
    private void doSomething(Object myObject) ... {
        do something with myObject
}

Similar Messages

  • Using a single connection for jsp, servlets and classes

    Hi! I'm building a web site that uses JSP, Servlets and some classes. I use database access in all my pages. I want to open a connection and use it for all the pages while the user is in my site, so I don't need to open a connection with every new jsp or servlet page. My software must be capable of connection with various databases, like SQLServer, Oracle, Informix, etc... so the solution must not be database (or OS or web server) dependant.
    Can you help me with this? Some ideas, links, tips? I'll REALLY appreciate your help.
    Regards,
    Raul Medina

    use an initialiation servlet with pooled connection which can be accessed as sesssion object.
    Abrar

  • 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());
    }

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

  • Sharing an object/class bewteen servlets and applications

    Hi there,
    I wish to know how to share a class/object between all
    types of other classes, be they applications or servlets, but I encounter the following problem.
    Basically, if I instantiate the common class using, say a servlet, then when I try to gain a handle on the instance of that class from an application, the application creates a new(or it's own) instance. Similarly, if I instantiate first within an application.
    How do I prevent this from happening?
    The actual class files for both the application and servlets are all the same.
    Appreciate the help,
    Fintan.

    I am actually implementing the singleton pattern in
    this common class.ok, that clarifies the issue a bit...
    The RMI route seems to me to be a bit too much work > as a solution to a very simple concept.actually, it's really not a simple concept. What you really want isn't just an application singleton, where there is one instance in the application/servlet JVM. What you really want is more along the lines of a universal singleton, where there is only one instance for ALL applications/servlets...
    Interestingly, if I run two java apps side by side in
    two DOS windows that each call a getInstance
    method in common singleton, both apps create their
    own instance.
    How come? Separate instances of VM?Yes, this is exactly correct. The same is true of C++ Singletons; if you start a second application it will create another instance of the Singleton because one does not yet exist in the application.
    How do I get aroun this one?Like I said, think of it as a universal singleton. Consider Verisign a universal singleton--everyone comes to them for certificates. How does this run? Well, truthfully, Verisign operates as a service, right? So you need some way of setting up a service that really holds onto the object and brokers (aha, 5 dollar word!) who has access to it, who can modify it, and who can read from it. This leads you to a few options... RMI, CORBA, or writing your own object server.
    Networking is really easy in Java, so here's another option... You can set up a server that listens for messages on a specific socket/port with whatever protocol you specify to get/set values. Have the server run on only one specific machine. Then you can have all the servlets and applications come to the machine to get the information.
    Gee, this sounds like a back-end database. =)
    If all this is too complex, maybe you need to rethink the design... do you really need to have the exact same object shared between all application/servlet instances? Or is it acceptable to just make sure they all contain the same data?
    If what you really want is a real-time data update scheme, then you probably want something like a subscribe-publish architecture where the one server publishes the origainal data. Then when a client updates the server, the server posts an update message to all the clients, who then in turn update their internal data.
    Anyway, I'm just throwing out some ideas. I'm sure you can come up with some better ones of your own since you know what your requirements are. =)
    Once again appreciate the help!I hope it actually was. =)
    --David

  • What is the difference between instance variable and class variable?

    i've looked it up on a few pages and i'm still struggling a bit maybe one of you guys could "dumb" it down for me or give and example of how their uses differ.
    thanks a lot

    Instance is variable, class is an object.What? "Instance" doesn't necessarily refer to variables, and although it's true that instances of Class are objects, it's not clear if that's what you meant, or how it's relevant.
    if you declare one instance in a class that instance
    should be sharing within that class only.Sharing with what? Non-static fields are not shared at all. Sharing which instance? What are you talking about?
    if you declare one class object it will share
    anywhere in the current program.Err...you can create global variables in Java, more or less, by making them static fields. If that's what you meant. It's not a very good practice though.
    Static fields, methods, and classes are not necessarily object types. One can have a static primitive field.

  • InterMedia Java Classes for Servlets and JSPs and Netscape

    I am using the interMedia Java Classes for Servlets and JSPs to upload and retrieve multimedia data. I have found that it is much more performant in Internet Explorer (5.5) than in Netscape Communicator (4.7). In fact, I cannot upload images larger than 10K at all using netscape. However, the same image can be uploaded into the same application using IE. Is this a known issue?
    Thanks in advance.

    Hi,
    We have successfully uploaded multimedia data in the giga-byte range (Quicktime and AVI files) at the same speed with both the Netscape (4.7n) and MS IE (4.n and 5.n) browsers. One thing we have noticed is that its very important to set the manual proxy settings correctly if you have an environment with a proxy server. If you don't, then uploads can go via the proxy server and, for some reason, that seems to take considerably longer. For example, suppose you are in the www.xyzco.com domain and are connecting to a host named webserver.www.xyzco.com, then specify webserver and webserver.www.xyzco.com (to cover both cases) in the "Do not use proxy servers for..." box in the manual proxy server configuration screen. Also, if you're using a tool such as JDeveloper that uses the host IP address in the debugger environment, then you also need to add the numeric-based (nnn.nnn.nnn.nnn) IP address to this list.
    Hope this helps.
    In order to better understand the variety of ways in which our customers are using interMedia, we'd be very interested in knowing a little more about your application, the interMedia functionality that you are using, and how you are developing and deploying your application. If you are able to help us, please send a short email message with some information about your application, together with any comments you may have, to the Oracle interMedia Product Manager, Joe Mauro, at [email protected] Thank you!
    Regards,
    Simon
    null

  • ATM model with Servlet and Cookies(class assignent)

    i am struggling starting a class assignment. I am suppose to use and access database, a servlet and cookies. If i understand correctly the servlet will have the buttons and GUI? What would i use the cookies for? or how would i use cookies in such an application? Please help.
    ty,
    max

    A servlet will typically generate HTML content. The generated HTML will contain tags which will be rendered into buttons and the like. Cookies are used for persisting state about a particular web browser across several sessions. For example, if a user enters their name in your system you could set a cookie (which would be stored on the client's machine). Then, when they return to the site you can re-access the cookie which was originally set.
    Good luck,
    -Derek

  • Get class Instance, and then get hers attributes

    Hi Gurus,
    i'm new to ABAP Object,
    creating an a BSP whit MVC controller i've try to implement the class controller,
    but on a method of it i want to get instance of the class parents:
    the class that i implement is an extension of CL_BSP_CONTROLLER2.
    In this class in the method DO_REQUEST ( for example ) i try to get the instance of the class
    parent ( and i got it! ) using this syntax:
      data: Parent type ref to IF_BSP_DISPATCHER,   " type take from attribute M_PARENT of the class
    Parent = ME->M_PARENT.
    In debug i see that 'Parent'  get rightly the class parent instance but than i want do this:
    (i want get the sub controller of the main contoller 'parent', in debug i can see everything fine)
       SubController = Parent->GET_ATTRIBUTE(LEFT_CONTROLLER).
    But the compiler say that the class instance 'Parent' has no methods and no attribute.
    i've try other syntax like:
        call METHOD Parent_>GET_ATTRIBUTE
            IMPORTING
         LEFT_CONTROLLER)
      call METHOD ME->M_PARENT->GET_CONTROLLER
       EXPORTING
         CONTROLLER_ID = 'search'
       IMPORTING
         CONTROLLER_INSTANCE = Parent2
    No one work!
    How can i do?
    Here screnshot of that i see in debug mode, and that i want get:
    http://img190.imageshack.us/i/1debugscreen.jpg/
    http://img10.imageshack.us/i/2debugscreen.jpg/
    Thanks in advance,
    Davide

    Hi Pawan,
    classes ref to CL_BSP_CONTROLLER2 like my controller class, have an attribute
    M_PARENT type IF_BSP_DISPATCHER.
    If the class is a subclass of an main class it has the M_PARENT attribute containing the instance of the parent class,
    i can see in debug mode ( here example: http://img40.imageshack.us/img40/1648/3debugscreen.jpg )
    i can get this attribute:
      data: Parent type ref to IF_BSP_DISPATCHER,   " type take from attribute M_PARENT of the class
    Parent = ME->M_PARENT.
    but  the interface IF_BSP_DISPATCHER has no attribute and no method defined, and if i declare 'Parent' as type ref to
    CL_BSP_CONTROLLER2 the compiler return error
          <=>      "The type of "PARENT" cannot be converted to the type of "ME->M_PARENT". "
    Davide

  • JSP, Servlet, and Java Classes location in Tomcat

    In tomcat, I want to know JSP files, Servlets, and Java classes
    should put in different locations:
    I put web.xml in the following:
    C:\jakarta-tomcat-4.1.30\webapps\proj1\WEB-INF
    I put all JSP files in the following:
    C:\jakarta-tomcat-4.1.30\webapps\proj1
    I put all servlet files in the following:
    C:\jakarta-tomcat-4.1.30\webapps\proj1\WEB-INF\classes
    I put all Java classes in the following with package proj1:
    C:\jakarta-tomcat-4.1.30\webapps\proj1\WEB-INF\classes\proj1
    When I execute JSP files, it has HTTP error 404, file not found.
    The content of web.xml is:
    <?xml version="1.0" encoding="ISO-8859-1"?>
    <!DOCTYPE web-app
    PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
    "http://java.sun.com/dtd/web-app_2_3.dtd">
    <web-app>
    <display-name>proj1</display-name>
    <description>
         proj1
    </description>
    <servlet-mapping>
    <servlet-name>invoker</servlet-name>
    <url-pattern>/*</url-pattern>
    </servlet-mapping>
    </web-app>
    Please advise. thanks!!!

    <servlet-mapping>
    <servlet-name>invoker</servlet-name>
    <url-pattern>/*</url-pattern>
    </servlet-mapping>
    </web-app>Where's the servlet definition that maps to "invoker"?

  • Deploying the JSPs, Servlets and Java class files

    Hello All,
    I'm very new to the Oracle 9i AS. We are using Version 1.0.2.2.
    How do we deploy the JSPs, Servlets, and Java class files (simple class files, not EJBs)?
    plese give us the procedure and stpes how to deply or the links for the same.
    Thanks,
    Santhosh.

    Hi
    I guess u r running apache-jserv as servlet engine for your jsp and servlets. If its so, jsp files can be run without any additonal configuration by putting the jsp file under document root or any subdirectory and for running servlets u have to add classpath entries for your servlet in jserv.properties file.
    To make sure that your servlet engine is working, try
    http://servername:port/servlet/IsItWorking, if u get success msg that means servlet engine is working fine.
    Hope this will help
    Regards
    Kumaran

  • What is the difference between acquiring lock on a CLASS and OBJECT (instance) of that class

    What is the difference between acquiring lock on a CLASS and OBJECT (instance) of that class

    What is the difference between acquiring lock on a CLASS and OBJECT (instance) of that class
    The Java Tutotials has several trails that discuss both implicit and explicit locking, how they work and has code examples.
    The Concurrency trail has the links to the other sections you need to review
    http://docs.oracle.com/javase/tutorial/essential/concurrency/index.html
    The Synchronized Methods and Intrinsic Locks and Synchronization trails discusse Synchronized Methods and Statements
    http://docs.oracle.com/javase/tutorial/essential/concurrency/syncmeth.html
    And the Lock Objects trail begins the coverage of explicit locking techniques.
    http://docs.oracle.com/javase/tutorial/essential/concurrency/newlocks.html

  • The difference between class, instances and object?

    I've been reading a JAVA book and i've come accross terms such as class, instances and object. What I don't understand is why after creating a class, we have to create an object and then create instances? What's an object and instance anyway? I don't really understand the term. Can anyone pls help and explain it to me in an easier way to understand?
    Thanks a lot.

    A Class defines what attributes (properties) and methods a particular item will have.
    Ex. You have a class person
    public class Person
    public void walk()
    String name;
    int age;
    }An instance and Object are the same. When you create an instance of a class, you get an object of that class.
    Person kevonline = new Person();You can then set kev's name, age, make him walk, etc... since these are defined in the class Person.
    HTH,
    Dewang

  • Access to Class Instance inside TileList and DataProvider?

    I have a TileList that is fed by a DataProvider.  The DataProvider places a source Class (and corresponding MovieClip) into the TileList as visual and interactive objects.
         dpChords.addItem({ label:tt, source:ChordUnit, data:i, scaleContent:true }); 
    How do I pass unique values to the instances of the "ChordUnit" within the TileList?
    public function setChordBin(song:int):void {
              var dpChords:DataProvider = new DataProvider();
              var i:uint;
              // determine chord set
              if (song == -1) {
                        activeChords = allChords;
               else {
                        activeChords = songChordSets[song];
              // fill dataProvider
              for(i=0; i<activeChords.length; i++) {
                        var tt = activeChords[i];
              dpChords.addItem({ label:tt, source:ChordUnit, data:i, scaleContent:true }); 
              chordBin.dataProvider = dpChords;
         // FORMATTING
              chordBin.columnWidth = 105;
         chordBin.rowHeight = 115; 
              chordBin.direction = ScrollBarDirection.HORIZONTAL;
              chordBin.setStyle("contentPadding", 5); 
              chordBin.setRendererStyle("imagePadding", 0);
              chordBin.scrollPolicy  = ScrollPolicy.ON;
              // set style for labels
              chordBin.setRendererStyle("textFormat", textFormat2);
              // set the background skin
              chordBin.setStyle("skin", lightBackground);
              //set the cell renderer
              chordBin.setStyle("cellRenderer", MyTileListRenderer);
        // EVENTS
              chordBin.addEventListener(ListEvent.ITEM_ROLL_OVER, chordBinItemOVER);
              chordBin.addEventListener(ListEvent.ITEM_ROLL_OUT, chordBinItemOUT);
              chordBin.addEventListener(ListEvent.ITEM_CLICK, chordBinItemCLICK);

    Here is the "" Class:
    package {
              // associates to "ChordUnit" MC graphic in library
              import flash.display.*;
              import flash.events.*;
              import flash.net.URLRequest;
              public class ChordUnit extends MovieClip {
                   public var imagePath:String;
                   public function ChordUnit():void {
                        loadDiagramImage(imagePath);
                   public function loadDiagramImage(imagePath:String) {
                        trace (imagePath)
                        var request:URLRequest = new URLRequest(imagePath);
                       this.diagramView.scaleContent = true;
                        // this.diagramView.addEventListener(Event.COMPLETE,loadComplete);
                        // this.diagramView.addEventListener(ProgressEvent.PROGRESS,loadProgress);           
                        this.diagramView.load(request);
    Of course, without being able to pass a unique "imagePath" value into the Class instance, the trace is "null".

  • Interaction between 2 classes (servlet and someother)

    Hi all,
    I have 2 java files one is a servlet and the other is an ordinary java file which checks to see whether a username and password exists in the database(UserPresent.java).This file has got the presentation layer which has to be put into the servlet.
    The servlet file must call the UserPresent.java file.I am going to make an interface to the UserPresent.java file ,I will call it User.java.This User.java file will have a method by name
    public boolean validateUser(String username,String pasword) .
    The UserPresent.java file will implement this interface.
    My question now is,where will these java files be put ?,hope that my point is conveyed.How do I test UserPresent.java file.Kindly excuse me if there is a much more sophisticated way of expressing this.
    Hoping to hear from you all
    Thanks
    AS

    If put means where does that files goes into directories.
    then u can put that files in same package as servlet resides or put in anther package and import
    thats all my understanding
    regards
    hithesh

Maybe you are looking for