JSP behavior - static initializer and jspInit

In a recent discussion, the concept of using a static intializer in a JSP came up. The situtation was that someone had a series of Strings used in a single JSP and they wanted to #1, define these strings in the JSP itself (vs in web.xml or a resource file, which while preferable, was not really an item of discussion) and #2 wanted indexed access to the Strings (such as via a Map).
My thought was to declare the Map variable as static final in the JSP and then initialize it in a static initializer block with Map.put operations. Both the declaration of the Map and the static initializer block would be declared in a <%! %> declaration tag block. (The thought behind the static initialization - vs overriding jspInit - being that if multiple instances of the JSP were to be created, we wouldn't want to keep put'ing values into the Map for each new instance of the JSP.)
I built the following test scenario:
<<untitled3.jsp source>>
<%@ page import="java.util.*" %>
<%!
static final Map m = new HashMap();
static int staticCount = 0;
static int jspInitCount = 0;
static {
System.out.println("static initializer called");
staticCount++;
m.put("staticCount"+staticCount, "static# " + staticCount);
     public void jspInit() {
          super.jspInit();
jspInitCount++;
m.put("jspInitCount"+jspInitCount, "jspInit# " + jspInitCount);
System.out.println("overriden jspInit called:" + this);
%>
Map values:<br>
<%
Collection values = m.values();
Iterator i = values.iterator();
while (i.hasNext()) {
out.println(i.next().toString() + "<br>");
%>
Test
<<end of untitled3.jsp source>>
with the following web.xml entries:
<servlet>
<servlet-name>JSPServlet1</servlet-name>
<jsp-file>untitled3.jsp</jsp-file>
</servlet>
<servlet>
<servlet-name>JSPServlet2</servlet-name>
<jsp-file>untitled3.jsp</jsp-file>
</servlet>
<servlet-mapping>
<servlet-name>JSPServlet1</servlet-name>
<url-pattern>/jsp1</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>JSPServlet1</servlet-name>
<url-pattern>/jsp2</url-pattern>
</servlet-mapping>
I open a browser and request untitled3.jsp, I get the following output in the browser:
Map values:
static# 1
jspInit# 1
Test
with the following output to my JDeveloper (9.0.3.1) log window:
static initializer called
overriden jspInit called:_untitled3@61
I then request /jsp1 and get the following output in the browser:
Map values:
static# 1
jspInit# 2
jspInit# 1
Test
with the following output to my log window:
overriden jspInit called:_untitled3@63
Subsequent calls to /jsp1, /jsp2 or untitled3.jsp result in that same last output in the browser and no further output in the log window (ie, no further calls to the static initializer or jspInit method)
So, it appears that jspInit is being called once for the unmapped JSP request and one more time, the first time one of the web.xml-mapped JSP instances is requested. (I'd have thought that it would be called once for the /jsp1 request and once for the /jsp2 request...), but the static initializer is being called only once as expected.
Is this the correct behavior for the jspInit method? (ie, being called once for the unmapped request and once for the first mapped request?)
Also, if OC4J is used in a clustered/balanced configuration, is it possible that I'd end up with additional instances of my JSP in one or more JVMs?
Thanks!
Jim Stoll

You could scope such info to the application scope - some info is provided here: http://java.sun.com/products/jsp/tags/11/syntaxref11.fm14.html
"application - You can use the Bean from any JSP page in the same application as the JSP page that created the Bean. The Bean exists across an entire JSP application, and any page in the application can use the Bean."

Similar Messages

  • Help required on java.lang.StackOverFlowError and static initializer

    I wanted to create an instance of a class that contains another instance of the same class. So I wrote:
    class A {
         A z = new A ();     
         void display () {
              System.out.println ("Hello World");
         public static void main (String [] args) {
              A y = new A();
              y.display ();
    }During execution I got java.lang.StackOverFlowError. But if I put a static initializer, it works fine. Here is the code using static initializer.
    class A {
         static{
              A z = new A ();     
         void display () {
              System.out.println ("Hello World");
         public static void main (String [] args) {
              A y = new A();
              y.display ();
    }Could anyone please help me to understand the logic why "java.lang.StackOverFlowError" is happening here and how the same program runs fine by putting a static initializer ?
    Regards,
    Shambhu

    Could anyone please help me to understand the logic
    why "java.lang.StackOverFlowError" is happening hereWhen you instantiate an A object with A y = new A () then A z = new A () also gets executed inside the A class, which in it's turn executes A z = new A () again, and again, and again...
    and how the same program runs fine by putting a
    static initializer ?Because the static block gets executed only once.
    The use of class- and instance variables is explained in more detail here:
    http://java.sun.com/docs/books/tutorial/java/javaOO/classvars.html

  • Instance initializer and static initializer blocks

    Hi guys,
    I read about the above mentioned in the JLS and also in a book before, but I still don't quite understand, what is the use of these. I sort of have a rough idea, but not exactly. I mean, what is the purpose of the instance initializer and static initializer blocks, how can it be useful? I understand I can execute pieces of code that will initialize instance and static variables accordingly, but how is it different then to using a constructor to initialize these fields? Are these pieces of code executed before any constructor is executed, or when otherwise?
    Sorry for my noob, I'm learning.
    PR.

    Static initializers are useful for initializing a class when the initialization is more complex than simply setting a single variable, or when that initialization can throw a checked exception.
    public class Foo {
      private static final Bar bar;
      static {
        try {
          bar = new Bar();
          bar.doSomeInitializationStuff();
        catch (SomeCheckedExceptionThatBarThrows e) {
          throw new ExceptionInInitializerError(e);
    }Here we could not do the two-step new Bar() + doSomeInit() stuff in the line where we declare the bar variable. Additionally, assuming that one or both of those can throw a checked exception, we could not do that on the declaration line; we need the static initializer to wrap that in the appropriate unchecked exception.
    This allows us to do more complex class initialization when the class is loaded than we could do with a simple variable initialization.
    Instance initializers are useful if you want to perform the same steps in every constructor and don't want to have to repeat the code in each constructor. Instance initializers are executed as the first step of each constructor (or maybe it's after any super() calls, I forget).

  • [svn:osmf:] 15220: Fix static initialization order in OSMFPlayer, so that the Log doesn't create TraceLoggers and DebugLoggers.

    Revision: 15220
    Revision: 15220
    Author:   [email protected]
    Date:     2010-04-05 10:29:52 -0700 (Mon, 05 Apr 2010)
    Log Message:
    Fix static initialization order in OSMFPlayer, so that the Log doesn't create TraceLoggers and DebugLoggers.
    Modified Paths:
        osmf/trunk/apps/samples/framework/OSMFPlayer/src/OSMFPlayer.as

    shak wrote:
    I've followed the first method with the mpd daemon and everything worked fine .
    THanks for all your help everyone !
    The add of MPD : ALL to hosts.allow seems to solved it .
    Thanks again!
    Nice.
    Please mark threads as [SOLVED] when they are. You can do so by editing the opening post.

  • JNDI lookup in Static initializer

    Hi,
    Is there a problem looking up home interfaces in a static initializer in
    WL6.1?
    I have a class X which runs in my application client. It has a static
    initializer that looks up a home interface. The call to Context.lookup()
    times out with weblogic.rjvm.PeerGoneException: No message was received for:
    '240' seconds.
    The strange thing is, if I force the static initializer to run myself (by
    instantiating X directly), then it runs ok. I only get the above problem if
    the VM causes it to run (by loading a class Y that references X).
    Also, this behaviour is only apparent in the client. In the app server, X
    behaves correctly. I'm passing in JNDI properties as system properties on
    the command line to the client.
    Any help appreciated.
    Cheers,
    Manish

    Check the class loader and thread dump during the place where it works and
    the one where it doesn't ... that could help track down why it works that
    way.
    Peace,
    Cameron Purdy
    Tangosol Inc.
    << Tangosol Server: How Weblogic applications are customized >>
    << Download now from http://www.tangosol.com/download.jsp >>
    "Manish Shah" <[email protected]> wrote in message
    news:[email protected]..
    Hi,
    Is there a problem looking up home interfaces in a static initializer in
    WL6.1?
    I have a class X which runs in my application client. It has a static
    initializer that looks up a home interface. The call to Context.lookup()
    times out with weblogic.rjvm.PeerGoneException: No message was receivedfor:
    '240' seconds.
    The strange thing is, if I force the static initializer to run myself (by
    instantiating X directly), then it runs ok. I only get the above problemif
    the VM causes it to run (by loading a class Y that references X).
    Also, this behaviour is only apparent in the client. In the app server, X
    behaves correctly. I'm passing in JNDI properties as system properties on
    the command line to the client.
    Any help appreciated.
    Cheers,
    Manish

  • Problems with static member variables WAS: Why is the static initializer instantiating my class?!

    Hi,
    I have been hunting down a NullPointerException for half a day to come to
    the following conclusion.
    My constructor calls a method which uses static variables. Since an intance
    of my class is created in the static block when the class is loaded, those
    statics are probably not fully initialized yet and the constructor called
    from the static block has those null pointer problems.
    I've considered moving the initialization of the static variables from the
    declaration to the static block. But your code is inserted BEFORE any other
    code. Therefore not solving my problem.
    Two questions:
    1) what would be a solution to my problem? How can I make sure my static
    variables are initialized before the enhancer generated code in the static
    block calls my constructor? Short of decompiling, changing the code and
    recompiling.
    2) Why is the enhancing code inserted at the beginning of the static block
    and not at the end? The enhancements would be more transparent that way if
    the static variables are initialized in the static block.
    Thanks,
    Eric

    Hi Eric,
    JDO calls the no-args constructor. Your application should regard this constructor as belonging
    primarily to JDO. For example, you would not want to initialize persistent fields to nondefault
    values since that effort is wasted by JDO's later initilization to persistent values. Typically all
    you want to initialize in the no-args constructor are the transactional and unmanaged fields. This
    rule means that you need initialization after construction if your application uses the no-args
    constructor and wants persistent fields initialized. On the other hand, if your application really
    uses constructors with arguments, and you're initializing persistent fields in the no-args
    constructor either unintentionally through field initializers or intentionally as a matter of
    consistency, you will find treating the no-args constructor differently helpful.
    On the other hand, if Kodo puts its static initializer code first as you report, then it is a bug.
    Spec Section 20.16: "The generated static initialization code is placed after any user-defined
    static initialization code."
    David Ezzio
    Eric Borremans wrote:
    >
    Hi,
    I have been hunting down a NullPointerException for half a day to come to
    the following conclusion.
    My constructor calls a method which uses static variables. Since an intance
    of my class is created in the static block when the class is loaded, those
    statics are probably not fully initialized yet and the constructor called
    from the static block has those null pointer problems.
    I've considered moving the initialization of the static variables from the
    declaration to the static block. But your code is inserted BEFORE any other
    code. Therefore not solving my problem.
    Two questions:
    1) what would be a solution to my problem? How can I make sure my static
    variables are initialized before the enhancer generated code in the static
    block calls my constructor? Short of decompiling, changing the code and
    recompiling.
    2) Why is the enhancing code inserted at the beginning of the static block
    and not at the end? The enhancements would be more transparent that way if
    the static variables are initialized in the static block.
    Thanks,
    Eric

  • JFileChooser incredibly slow both to initialize and to change directories

    I have searched the forums for this and haven't found anything useful. I have the following code running in jre1.6.0_07:
    JFileChooser objFileChooser = new JFileChooser();
    objFileChooser.setAcceptAllFileFilterUsed(true);
    objFileChooser.addChoosableFileFilter(new CookbookFileFilter());
    objFileChooser.setMultiSelectionEnabled(false);
    if(objFileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION)
         getModel().load(objFileChooser.getSelectedFile().getAbsolutePath());the first line takes upwards of 20-30 seconds or more to get past when debugging - I don't know how long it takes when running without the debugger however the application does sit for a while after pressing the hotkey to activate the actionlistener. That's a problem, but if that was the only thing, I would do as another post suggested and initialize the jFileChooser from a separate thread during the initialization of the window or application...however, I also run into an issue whenever I change directories where it takes a subset of the initialization time(maybe 10-15 seconds instead of 20-30) to change the directory. This happens in both System and Cross-Platform Look and Feel-s.
    I've looked into the issue with zip files and there are no (0) zip files(or archives of any kind) in the initial directory(My Documents folder). There is a small delay going to My Computer through Windows normally but it may be 1-2 seconds at most, and only sometimes. Notepad opens the Load / Save Dialogs within milliseconds and while I do understand Java is not Notepad, I'm willing to accept a few seconds (like maybe 5 or so), but not 20-30. I also looked into potentially using JDK 7 however I can't seem to get Eclipse to work with it and it consistently uses the JDK 6.
    If a solution can not be found to this, then is there a way to hook into the dialog/control in order to change the mouse cursor to the 'wait' cursor and change it back when the directory is ready? I'd like to provide some communication to the user. Thanks!

    camickr,
    I did include a "Short, Self Contained, Compilable and Executable Example Program (SSCCE)" in my initial posting; and I also included Code Formatting as everyone can see. I've been a programmer for over 10 years, closer to 15 and have almost 8 years experience with Java so I'm not about to ask a question without investigating the solution on my own first(to avoid wasting people's time. Admittedly all I posted was the snippet but that entire snippet could be put within Main like this below and it would be exactly the same without the waste of space. The machine I have running / developing this on is: Athlon 64 3000, 1 GB RAM, about 13 or 14 total hard drive partitions and removable media drives, running under Windows XP SP2. I can even eliminate the Choosable Filter in the example as I do below and the JFileChooser takes (31 seconds on average over 5 iterations, I timed it after I originally posted this) to fully display the dialog and all files and deliver control back to the user. That is unacceptable and one can not deny that it's the class itself when FileDialog runs significantly faster and programs outside of Java executing the standard XP File Dialog run even faster still. If this code is not good enough, I don't know how much shorter or self contained I can make this code example without removing the configuration lines between the initialization and that would defeat my cause as I need the Look and feel customization and prefer not writing my own File Chooser Dialog. Here's the code w/ the main function and all.
    import javax.swing.JFileChooser;
    public class Example
         public static void main(String[] args)
              JFileChooser objFileChooser = new JFileChooser();
              objFileChooser.setAcceptAllFileFilterUsed(true);
              objFileChooser.setMultiSelectionEnabled(false);
              if(objFileChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION)
                   System.out.println("Approved");
    }Thanks,
    Seth

  • How to reference a static variable before the static initializer runs

    I'm anything but new to Java. Nevertheless, one discovers something new ever' once n a while. (At least I think so; correct me if I'm wrong in this.)
    I've long thought it impossible to reference a static variable on a class without the class' static initializer running first. But I seem to have discovered a way:
    public class Foo  {
      public static final SumClass fooVar;  // by default initialized to null
      static  {
         fooVar = new SumClass();
    public class Bar  {
      public static final SumClass barVar;
      static  {
         barVar = Foo.fooVar;  // <<<--- set to null !
    }Warning: Speculation ahead.
    Normally the initial reference to Foo would cause Foo's class object to instantiate, initializing Foo's static variables, then running static{}. But apparently a static initializer cannot be triggered from within another static initializer. Can anyone confirm?
    How to fix/avoid: Obviously, one could avoid use of the static initializer. The illustration doesn't call for it.
    public class Foo  {
      public static final SumClass fooVar = new SumClass();  // either this ..
    public class Bar  {
      public static final SumClass barVar = Foo.fooVar;  // .. or this would prevent the problem
    }But there are times when you need to use it.
    So what's an elegant way to avoid the problem?

    DMF. wrote:
    jschell wrote:
    But there are times when you need to use it. I seriously doubt that.
    I would suppose that if one did "need" to use it it would only be once in ones entire professional career.Try an initializer that requires several statements. Josh Bloch illustrates one in an early chapter of Effective Java, IIRC.
    Another classic usage is for Singletons. You can make one look like a Monostate and avoid the annoying instance() invocation. Sure, it's not the only way, but it's a good one.
    What? You only encounter those once in a career? We must have very different careers. ;)
    So what's an elegant way to avoid the problem? Redesign. Not because it is elegant but rather to correct the error in the design.<pff> You have no idea what my design looks like; I just drew you a couple of stick figures.If it's dependent on such things as when a static initializer runs, it's poor. That's avoidable. Mentioning a case where such a dependency is used, that's irrelevant. It can be avoided. I know this is the point where you come up with a series of unfortunate coincidences that somehow dictate that you must use such a thing, but the very fact that you're pondering the problem with the design is a design problem. By definition.
    Besides, since what I was supposing to be a problem wasn't a problem, your "solution" isn't a solution. Is it?Well, you did ask the exact question "So what's an elegant way to avoid the problem?". If you didn't want it answered, you should have said so. I'm wondering if there could be any answer to that question that wouldn't cause you to respond in such a snippy manner. Your design is supposedly problematic, as evidenced by your question. I fail to see why the answer "re-design" is unacceptable. Maybe "change the way the Java runtime initializes classes" would have been better?
    This thread is bizarre. Why ask a question to which the only sane answer, you have already ruled out?

  • Static initializer error

    hi guys,
    can anyone explain what might cause the following error?
    i have the following classes
    class BonesPlayLevel {
    // execution reaches here
    ObjFigure.initJointedModel();
    class ObjFigure {
    public static void initJointedModel() {
    // execution does not reach here
    initJointedModelList(myVecs);
    and when i try and run i get the following error message:
    java.lang.Error: Static initializer: java.lang.NullPointerException
    java.land.Error
    cheers
    spob

    its ok i understand how to debug, and how the stack trace works.
    i am running this in JBuilder, here is the output produced
    D:\Nokia\Devices\Series_60_MIDP_Concept_SDK_Beta_0_3_1_Nokia_edition\bin\emulator.exe -classpath "E:\javaApps\MIDlets\mlj3d_exbones\classes;D:\MLJ3D\v1.0.1dev\jars\mljFrame.jar;D:\MLJ3D\v1.0.1dev\jars\mljRender.jar;" -Xdevice:Series_60_MIDP_Concept_SDK_Beta_0_3_1_Nokia_edition -Xdescriptor:"E:\javaApps\MIDlets\mlj3d_exbones\jad-temp\ExBones.jad"
    java.lang.Error: Static initializer: java/lang/NullPointerException

  • Why is the static initializer instantiating my class?!

    It seems that the static { ... } blocks for my enhanced classes actually
    create instances of those classes. Gack! It seems, furthermore, that
    this is due to the JDO spec itself, whose JDOImplHelper.registerClass()
    requires an instance of the class being registered. Double gack!
    This is causing a problem for me, because I've put a sequence generator in
    my class's constructor. Now merely **loading** a PC class will cause my
    sequence to be incremented (not great), or will throw an exception if the
    environment isn't set up for the sequence generator (terrible). This
    latter problem happens if I enhance my classes, then try to enhance them
    again -- the enhancer tries to load my class, the static { ... } block
    tries to load the sequence generator, and the whole enhancer blows up.
    Questions:
    * Why is this necessary? Why does JDOImplHelper.registerClass() take an
    instance of the class being registered? Could the call to
    JDOImplHelper.registerClass() happen the first time the ctor is called,
    instead of inside a static { ... } block?
    * Given that the above questions probably have reasonable answers, how
    should I work around this problem?
    Thanks,
    Paul

    Hi Patrick,
    Do you understand why jdoNewInstance and jdoNewObjectIdInstance are not static? And if that could
    be done, would that void the need to register the class when loaded?
    David
    Patrick Linskey wrote:
    >
    On 5/28/02 12:39 PM, "Paul Cantrell" <[email protected]> wrote:
    Questions:
    * Why is this necessary? Why does JDOImplHelper.registerClass() take an
    instance of the class being registered? Could the call to
    JDOImplHelper.registerClass() happen the first time the ctor is called,
    instead of inside a static { ... } block?The JDO spec inserts some utility methods into PersistenceCapable classes
    for which it needs a method around.
    These utility methods are the jdoNewInstance() methods and the
    jdoNewObjectIdInstance() methods. These methods improve performance by
    allowing PersistenceCapable objects and application ID OID classes to be
    created without using reflection.
    This class registration must occur at class initialization time, because
    your first operation on the class might very well be to look up objects of
    that class from the data store, in which the no-args constructor might not
    be called.
    * Given that the above questions probably have reasonable answers, how
    should I work around this problem?Your best bet is probably to not do the sequence generation in your no-args
    constructor. One option would be to create a constructor with a marker
    boolean that designates if sequence generation should occur; another
    probably more elegant solution would be to create a factory method that uses
    the default constructor and then assigns an ID, or fetches an ID and then
    invokes a non-default constructor with that ID.
    -Patrick
    Patrick Linskey [email protected]
    SolarMetric Inc. http://www.solarmetric.com

  • Help please with a Static Initializer for ImageIcons inside Jar Files

    At the moment I'm playing around displaying XML using A JTree
    I am subclassing DefaultMutableTreeNode, and want it to have some default Icons set up....
    Sort of like this:
    public class XNode extends DefaultMutableTreeNode
        public static final ImageIcon icon;
       public static ImageIcon getIcon()
            return XNode.icon;
    }The only thing is that for the life of me after trying various things and searching these forums and google:
    I can't work out how to write the static Initializer for the ImageIcon.
    The ImageIcon will need to be created using a URL, cos it will be inside my jar file.....
    the usual...
               URL url = this.getClass().getResource("/images/Exit16.gif");
               ImageIcon Icon = new ImageIcon( url );but I wanted these Icons to be class members..............
    Could someone help?
    }

    DrClap " I don't understand why you put Class.forName in there either"
    A: Because I don't really know what I'm doing.
    I will try that suggestion.
    At present I have this:
         static ImageIcon loadIcon;
         static
              try
                loadIcon = new ImageIcon( Class.forName("cis.editor.xml.nodes.AlNode").getResource("/images/Exit16.gif"));
              catch( ClassNotFoundException cnfe )
                   System.out.println("ClassNotFound: " + cnfe.getMessage() );
         public static final ImageIcon defaultIcon = loadIcon;
         static
              try
                loadIcon = new ImageIcon( Class.forName("cis.editor.xml.nodes.AlNode").getResource("/images/tree_folder_major.gif"));
              catch( ClassNotFoundException cnfe )
                   System.out.println("ClassNotFound: " + cnfe.getMessage() );
         public static final ImageIcon commentIcon = loadIcon;
    //.......... ANd so OnWhy? Because do far it was the only way I could get it to compile.
    And It works..
    However it's a real abortion.. codewise.
    I need to load about 16 Icons that the various subclasses can 'use'
    DefaultTreeCellRenderer - must do somethng similar because it has a bunch of Icons to "Pick from",
    Only How is that done 'properly' ?

  • Exception in static initializer

    Hi,
    I have one class with one static variable.
    I am initializing this variable in static initializer block. But while initializing, it is throwing some checked exception which I dont want to catch in block.
    Static initializer block doesn't support "throws", what should be done?
    Thanks

    hm..
    I think it depends on implementation.. etc
    Anyways, point is not where I should catch the
    exception. Point is, how can I throw the exception to
    caller when I am initializing static members. I don't think this makes sense! The 'caller' has to be the class loader so unless you are using your own class loader then you don't have any real choice.
    You could always wrap the exception in an un-checked exception and let the system handle it but this may just close the application anyway!

  • When trying to launch a Java preferences get this message:  Cannot launch Java application A static initializer of the main class threw an exception: java.lang.NullPointerException"

    I have an IMac 10.5.8 and I am having problems with Java. I have tried todownload Java for Mac OS X 10.5 Update 4 and it looks as if it is doingsuccessfully, but I cannot see where it has put it and get this message when trying to launch Java preferences:
    Cannotlaunch Java application
    A static initializer of the main class threw an exception:java.lang.NullPointerException"
    Couldyou please help?

    Hmm, only way I know would be a relatively painless Archive & Install, which gives you a new/old OS, but can preserve all your files, pics, music, settings, etc., as long as you have plenty of free disk space and no Disk corruption, and is relatively quick & painless...
    http://docs.info.apple.com/article.html?artnum=107120
    Just be sure to select Preserve Users & Settings.

  • Static and non-static variables and methods

    Hi all,
    There's an excellent thread that outlines very clearly the differences between static and non-static:
    http://forum.java.sun.com/thread.jsp?forum=54&thread=374018
    But I have to admit, that it still hasn't helped me solve my problem. There's obviously something I haven't yet grasped and if anyone could make it clear to me I would be most grateful.
    Bascially, I've got a servlet that instatiates a message system (ie starts it running), or, according to the action passed to it from the form, stops the message system, queries its status (ie finds out if its actually running or not) and, from time to time, writes the message system's progress to the browser.
    My skeleton code then looks like this:
    public class IMS extends HttpServlet
        public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
            doPost(request, response);
       public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
          //get the various parameters...
             if (user.equalsIgnoreCase(username) && pass.equalsIgnoreCase(password))
                if(action.equalsIgnoreCase("start"))
                    try
                        IMSRequest imsRequest = new IMSRequest();
                        imsRequest.startIMS(response);
                    catch(IOException ex)
                    catch(ClassNotFoundException ex)
                else if(action.equalsIgnoreCase("stop"))
                    try
                        StopIMS stopIMS = new StopIMS();
                        stopIMS.stop(response);
                    catch(IOException ex)
                 else if(action.equalsIgnoreCase("status"))
                    try
                        ViewStatus status = new ViewStatus();
                        status.view(response);
                    catch(IOException ex)
             else
                response.sendRedirect ("/IMS/wrongPassword.html");
    public class IMSRequest
    //a whole load of other variables   
      public  PrintWriter    out;
        public  int                 messageNumber;
        public  int                 n;
        public  boolean         status = false;  //surely this is a static variable?
        public  String            messageData = ""; // and perhaps this too?
        public IMSRequest()
        public void startIMS(HttpServletResponse response) throws IOException, ClassNotFoundException
            try
                response.setContentType("text/html");
                out = response.getWriter();
                for(n = 1 ; ; n++ )
                    getMessageInstance();
                    File file = new File("/Users/damian/Desktop/Test/stop_IMS");
                    if (n == 1 && file.exists())
                        file.delete();
                    else if (file.exists())
                        throw new ServletException();
                    try
                        databaseConnect();
                   catch (ClassNotFoundException e)
    //here I start to get compile problems, saying I can't access non-static methods from inside a static method               
                   out.println(FrontPage.displayHeader()); 
                    out.println("</BODY>\n</HTML>");
                    out.close();
                    Thread.sleep(1000);
            catch (Exception e)
        }OK, so, specifially, my problem is this:
    Do I assume that when I instantiate the object imsRequest thus;
    IMSRequest imsRequest = new IMSRequest();
    imsRequest.startIMS(response); I am no longer in a static method? That's what I thought. But the problem is that, in the class, IMSRequest I start to get compile problems saying that I can't access non-static variables from a static method, and so on and so on.
    I know I can cheat by changing these to static variables, but there are some specific variables that just shouldn't be static. It seems that something has escaped me. Can anyone point out what it is?
    Many thanks for your time and I will gladly post more code/explain my problem in more detail, if it helps you to explain it to me.
    Damian

    Can I just ask you one more question though?Okay, but I warn you: it's 1:00 a.m., I've been doing almost nothing but Java for about 18 hours, and I don't do servlets, so don't take any of this as gospel.
    If, however, from another class (FrontPage for
    example), I call ((new.IMSRequest().writeHTML) or
    something like that, then I'm creating a new instance
    of IMSRequest (right?)That's what new does, yes.
    and therefore I am never going
    to see the information I need from my original
    IMSRequest instance. Am I right on this?I don't know. That's up to you. What do you do with the existing IMS request when you create the new FrontPage? Is there another reference to it somewhere? I don't know enough about your design or the goal of your software to really answer.
    On the other hand, IMSRequest is designed to run
    continuously (prehaps for hours), so I don't really
    want to just print out a continuous stream of stuff to
    the browser. How can I though, every so often, call
    the status of this instance of this servlet?One possibility is to pass the existing IMSRequest to the FrontPage and have it use that one, rather than creating its own. Or is that not what you're asking? Again, I don't have enough details (or maybe just not enough functioning brain cells) to see how it all fits together.
    One thing that puzzles me here: It seems to me that FP uses IMSReq, but IMSReq also uses FP. Is that the case? Those two way dependencies can make things ugly in a hurry, and are often a sign of bad design. It may be perfectly valid for what you're doing, but you may want to look at it closely and see if there's a better way.

  • Static blocks and synchronization

    Hi,
    I have a question - I have a DAO class which basically caches some master data, and also reads a property file and caches the information. To do this I have written a static block :
    Class MyDAO {
    private static Properties sqlProp = null;
    priate Hashtable countries = null;
    static {
    initialize();
    private void initialize() {
    sqlProp = new Properties();
    //add values to sqlProp
    countries = new Hashtable();
    //add values in countries.
    I understand that a static block gets executed only once when the class gets loaded. Now my question is do we have to synchronize this initialize process, will there be any concurrency issues with the above code.
    If so how could I correct this , please let me know your suggestions..
    Thanks in advance..

    Thank you very much for the response..You are welcome. I hope you read my comment above as "Class initialization is thoroughly synchronized", which is what I intended :-)

Maybe you are looking for

  • IOS 8.1 Photos and/or Messages cursor issue

    I select a photo within the Photos app on my iPhone 5s or my iPad2 Then click the little 'share arrow' and choose Messages app as the sharing method The photo selected does show up in the Messages 'message composition' window However the cursor, inst

  • Stolen iPad 2 and MacBook Pro

    My iPad 2 white 32gb wifi and MacBook Pro still under warranty got stolen because my house got break in last night. I have the serial number and is there any other solution to track it back. I installed Dropbox in my Mac as well as my iPhone. Can I t

  • Deleting document or photos from ipad to save space

    Is there a way to delete a document or photo from my iPad to save space but still keep it in iCloud? I want to be able to have access to it when/if I need it but am trying to maximize space on my iPad.

  • Sound to come out on my television

    I have a new 13 in mac book pro, i bought a mini dvi to dvi and then the dvi to hdmi, the screen is perfect but the sound still comes out through the laptop and not the television, how do i make the sound come out through the screen

  • Layers Magazine tips about After Effects

    Layers Magazine has just posted some tips about several applications in Creative Suite 4, including After Effects CS4.