Static variable gets cached

HI,
I'm having trouble with a java servlet's static variable. I have a jsp page which calls a java servlet. Inside the servlet, I have a global varialbe that I'm using to store information in, however this variable must not be initialized unless the user leaves the site or refreshes the index.jsp page. But thisi isn't happening. When I go to the index.jsp page right after I submit inforamtion, the old value of the variable is still appearing. How can I fix this? I tried MANY things. I tried using sessions to store information, but this was still giving me the same problem. I also tried doing a session.invaldiate() but again, this doesn't fix the problem. Does anyone know where I'm going wrong?
Thanks,
nafina

Show us the code. Remember to use [code] ..[/code] tags.
Or quick things to try: are you sure the browser gets a new page and doesn't display from the browser's cache? Ctrl+reload or shift+reload forces reload in some browsers. Are you sure the variable gets updated -- log the value just after updating it and just before sending it back to the browser. Theoretically, a web server can unload and reload servlets; it may be safer to put statics elsewhere (utility classes). (Though I'm not sure if a sufficiently obnoxious servlet container could unload those as well. The real place to put static data is a database, but that may be overkill.)

Similar Messages

  • Runtime error in linking with static variables....

    Hi,
    I am building a shared library which includes a compiled object generated from a class containing the static variables only and also I have another version of same class with same & some new static variables in it and using that to generate another shared library. Now when I tried to run a program
    which links with both the library it core dumps when it tries to return from the program i.e when it finishes.
    Can someone please help me explain why my program is behaving like that?? Can duplicate inculsion of static variables in different scope can cause problem ?? How can this be avoided ?
    Also please be advised that the class with static variables gets generated at the compile time using a script which uses a DTD whose version (specification) can be different in both the libraries therefore I can't just seperate the common stuff into one class and specific into another.
    Thanks.
    Rajeev.

    Not to worry...found the answer in another post. Seems like patches need to applied to the OS.

  • Static variable behaviour in memory

    Hi,
    My question is :
    When you compile a java code, does the static variable gets the memory allocated while creating the byte code or is it on run time that a static variable gets the memory allocation and then it is shared for all instances.
    Thanks
    Melvyn.

    Good !!! I expected this question from you.
    Instantiation and Initialization are different.
    A class or interface type T will be initialized immediately before the first occurrence of any one of the following:
    1) T is a class and an instance of T is created.
    2) T is a class and a static method declared by T is invoked.
    3) A static field declared by T is assigned.
    4) A static field declared by T is used and the reference to the
    field is not a compile-time constant. References to
    compile-time constants must be resolved at compile time to
    a copy of the compile-time constant value, so uses of such a
    field never cause initialization.
    Regards
    Raghu

  • Global static variable. I just CANNOT get global for everything

    Hi,
    I copied a connection pool example from oracle web site. It uses static variable. Its not a servlet, its a javabean. I can run a million times in one session and everything is great. If I open up another session, it creates another instance and creates more connections when it should be seeing the previous instance.
    My question is how to make a static variable global to the entire application? Do i have to initialize it in the servlet container? All im doing is calling a JSP page which calls this bean. If instance is null, create 5 new connections. Well like i stated above, it works for a single session. It appears that each session gets its own instance. I have been working and debugging this for a long time and I just cannot come up with a solution...
    Any ideas???
    Thanks as always

    Declar it as static within the servlet class.
    public class MyServlet extends HttpServlet {
    public static ConnectionPool pool;
    Then you can access it from any JSP/Servlet using MyServlet.pool but you may have to import the class into the JSP/Servlet.
    Be aware that there may be synchroniztion issues when you access this static object so you may want to synchronize access to the pool.
      synchronized (application) {
           if (MyServlet.pool == null) { //initialize pool code here }

  • Caching / Static Variables

    Can anyone suggest a strategy for caching the results of an expensive operation, and making them available from one invocation of a bpel process to the next?
    I have a Java Embedding Task running custom code to do proprietary authentication, and I'd like to cache the results.
    Any mechanism for getting a handle to something static? Any way to cache something in memory, and access it across bpel processes invocations?
    thanks!
    Mike

    Here's one solution. Clearly a hack, but seems to work for now.
    1- Create a java class to be your static cache:
    package com.uglyhack.Cache;
    import java.util.*;
    public class Cache{
    private static HashMap map = new HashMap();
    public static synchronized void put (String key, Object val){
    map.put(key, val);
    public static Object get(String key){
    return map.get(key);
    2- Compile it, and package it up in a jar file
    2a. Add jar to JDev by putting a reference to it in ProjectProperties/libraries
    2b. Add class to server with Copy/Paste to OracleAS_1/bpel/system/classes/com/uglyhack/Cache.class
    3- Create a Java Embedding task to store or retrieve your static vars:
    String myKey=(String)getVariableData("myBpelVar1");
    String myVal=(String)getVariableData("myBpelVar2");
    com.uglyhack.Cache.put(myKey, myVal);
    and later
    String myKey=(String)getVariableData("myBpelVar1");
    String cachedVal = (String)com.uglyhack.Cache.get(myKey);
    setVariableData("myBpelVar2", cachedVal);
    Message was edited by:
    Mike_(523682)

  • Non-static variable from a static context

    This is the error i get . If i understand the error correctly it says im using a static variable when i shouldnt be? Or is it the other way round? below the error is the actual code....
    The error...
    Googler.java:27: non-static variable this cannot be referenced from a static context
              submitButton.addActionListener(new ButtonHandler());The code...
              JButton submitButton = new JButton("Submit Query");
              submitButton.addActionListener(new ButtonHandler());

    thanks for the response.
    I have already tried what you said but I tried it again anyway and i get the same error more less...
    Googler.java:28: non-static variable this cannot be referenced from a static context
              ButtonHandler buttonHandler = new ButtonHandler();here is part of my code
    public class Googler
      static JTextField input1, input2;
         public static void main(String[] args)
              JFrame myFrame = new JFrame("Googler v1.0");
              Container c = myFrame.getContentPane();
              JLabel lab1 = new JLabel("Enter Google Query:");
              JLabel lab2 = new JLabel("Enter Unique API Key:");
              input1 = new JTextField(15);
              input2 = new JTextField(15);
              JRadioButton radSearch = new JRadioButton("Search Query");
              JRadioButton radCached = new JRadioButton("Cached Query");
              JButton submitButton = new JButton("Submit Query");
              ButtonHandler buttonHandler = new ButtonHandler();
              submitButton.addActionListener(buttonHandler);
              ButtonGroup group = new ButtonGroup();
              group.add(radSearch);
              group.add(radCached);Ive tried declaring buttonHandler as a static variable and this dosn't work either. I've never had this problem before it must be something silly im missing...?
    Thanks
    Lee

  • Static variable, a bug in applet classloader, Java plug-in?

    I found a potential bug in java plug-in.
    Environment,
    1. IE 6.0
    2. Windows XP
    3. JRE 1.3.1.06 and JRE 1.4.1.01
    Steps,
    1. build a very simple applet (attached below)
    2. embed the applet into a .html page.
    3. enable java plug-in for IE and Netscape.
    4. launch the .html page in either of the two browsers.
    5. for the 1st time, I can see 'tmp = 0' in the java console window.
    6. keep the browser open, browse to 'www.google.com'
    7. click 'Back' button of the browser.
    8. I notice 'tmp = 1' in the java console window.
    9. if I browse to google.com and back again, it will display 'tmp = 2'. and the number will keep on increasing if I repeat those steps.
    10. But if I press F5 to refresh the page, the log message will go back to 'tmp = 0'. and if I press 'x' inthe console window to clean up the classloader cache, I will get 'tmp = 0'. If I close the browser and open a new one, I will still get 'tmp = 0', which is what the applet should output.
    11. If I click 't' in the console window to list the thread while I am in the 'google' page, I can't see the applet thread, which means the applet should have been destroyed.
    12. No matter I try 'g' to do garbage collect, or 'f' to finalize objects, the problem still happens. the only solution is what I did in the step 10.
    Is it a bug in the classloader or the JRE itself? Why the value of the static variable won't be cleaned up along with the applet?
    ----------- HERE IS THE APPLET --------------------
    import java.applet.Applet;
    public class AA extends Applet
    private static long tmp = 0;
    public void init() {
         System.out.println("tmp value = " + tmp);
    tmp++;
    public void start() {}
    public void stop() {}
    public void destroy() {}

    Static values are stored in the class. Once a class is loaded into a classloader, it cannot be unloaded (the only thing you can do is use another classloader).
    Apparently, the classloader cache allows sharing of classloaders between applet instances. Perhaps F5 (reload) causes the classloader cache to be cleared.
    I don't see any bug. When developing applications or applets that must run in the same JVM, you should program defensively and avoid using static values which can change over time.

  • Shared java static variables

    I have an application where I would like to
    read from some small configuration tables
    and cache them into java variables, in order to avoid each stored procedure call to redo
    those queries. The configuration data is
    pretty static, so I don't worry about refresh
    problems.
    My first attempt to do that was using static
    final variables (like Vector). In our oracle
    environment however (8.1.7) each session
    seems to have its own copy of static final
    variables, resulting in each session to
    perform those queries for initializing all
    over again.
    firstly, i would like to find out if there is another way to share this data among java
    sessions, but otherwise I am curious how
    I can get the claims made in http://technet.oracle.com/products/oracle8i/pdf/8ir2java.pdf , page 6 to work.
    Specifically, here is what the document says:
    "In Oracel8i Release 2, JServer introduces the concept of "hotloaded" classes. Various core classes that
    initialize static variables known to be constant are pre-initialized during database creation time. When you use
    one of these classes in your program, the class loader loads the pre-initialized form. In many cases, the time
    required to initialize the static variables is itself quite significant, and now with the introduction of hotloaded
    classes that time is completely eliminated. In addition, the objects in these particular static variables are shared
    among all sessions. Hotloaded classes therefore improve performance by eliminating class initialization and
    they reduce per-user-session footprint by increasing the amount of data shared between sessions. Hotloaded
    classes provide improved performance and scalability "for free", with no user intervention. "
    the kind of initialization I have been
    trying is like:
    public static final int inti = func();
    this also didn't seem to work:
    public static final int inti;
    static {
    inti = ....;
    thanks,
    null

    I have an application where I would like to
    read from some small configuration tables
    and cache them into java variables, in order to avoid each stored procedure call to redo
    those queries. The configuration data is
    pretty static, so I don't worry about refresh
    problems.
    My first attempt to do that was using static
    final variables (like Vector). In our oracle
    environment however (8.1.7) each session
    seems to have its own copy of static final
    variables, resulting in each session to
    perform those queries for initializing all
    over again.
    firstly, i would like to find out if there is another way to share this data among java
    sessions, but otherwise I am curious how
    I can get the claims made in http://technet.oracle.com/products/oracle8i/pdf/8ir2java.pdf , page 6 to work.
    Specifically, here is what the document says:
    "In Oracel8i Release 2, JServer introduces the concept of "hotloaded" classes. Various core classes that
    initialize static variables known to be constant are pre-initialized during database creation time. When you use
    one of these classes in your program, the class loader loads the pre-initialized form. In many cases, the time
    required to initialize the static variables is itself quite significant, and now with the introduction of hotloaded
    classes that time is completely eliminated. In addition, the objects in these particular static variables are shared
    among all sessions. Hotloaded classes therefore improve performance by eliminating class initialization and
    they reduce per-user-session footprint by increasing the amount of data shared between sessions. Hotloaded
    classes provide improved performance and scalability "for free", with no user intervention. "
    the kind of initialization I have been
    trying is like:
    public static final int inti = func();
    this also didn't seem to work:
    public static final int inti;
    static {
    inti = ....;
    thanks,
    null

  • Re: static variables in beans

    That's GoF. Again I was responding to the question posted earlier and could not
    see it near by and not commenting on yours. I was questioning the original design
    of having to keep singletons as static fields in SLSBs.
    S
    "Cameron Purdy" <[email protected]> wrote:
    Is there a problem if you get the singleton (through a static methodas
    in GoF) objects in the methods as required and not store it as static
    variables in the SLSB?I am acronymically challened ("AC"). What is GoF? I know I've seen it
    before, but I can't remember what it means.
    Singletons should store their own reference. You should probably have
    a
    private constructor and a static "instance" accessor.
    Peace,
    Cameron Purdy
    Tangosol, Inc.
    http://www.tangosol.com/coherence.jsp
    Tangosol Coherence: Clustered Replicated Cache for Weblogic
    "sri" <[email protected]> wrote in message news:[email protected]..
    >

    You are right. An EJB (all kinds) is restricted from using writtable static fields.
    Read only fields are allowed but recommended to use 'final' to denote so.
    S
    "Cameron Purdy" <[email protected]> wrote:
    That's GoF. Again I was responding to the question posted earlier and
    could not see it near by and not commenting on yours. I was questioning
    the original design of having to keep singletons as static fields inSLSBs.
    It gets difficult to follow these threads. I use Outlook Express (motto:
    "There's no message out there that we can't add a top-post to!") which
    isn't
    the world's best newsreader.
    Regarding static fields in SLSBs, you are right that it is certainly
    something to avoid. I believe that some containers even refuse to deploy
    EJBs that have static fields like that. (I believe it's a purposed
    limitation in the spec.)
    Peace,
    Cameron Purdy
    Tangosol, Inc.
    http://www.tangosol.com/coherence.jsp
    Tangosol Coherence: Clustered Replicated Cache for Weblogic
    "Sri" <[email protected]> wrote in message news:3ea5b88e$[email protected]..
    >

  • Using a static variable declared in an applet in another class

    Hi guys,
    I created an applet and i want to use one of the static variables declared in teh applet class in another class i have. however i get an error when i try to do that...
    in my Return2 class i try to call the variable infoPanel (declared as a static JPanel in myApplet...myApplet is set up like so:
    public class myApplet extends JApplet implements ActionListener, ListSelectionListener
    here are some of the lines causing a problem in the Return2 class:
    myApplet.infoPanel.removeAll();
    myApplet.infoPanel.add(functionForm2.smgframeold);
    myApplet.infoPanel.validate();
    myApplet.infoPanel.repaint();
    here are some of the errors i get
    dummy/Return2.java [211:1] package myApplet does not exist
    myApplet.infoPanel.removeAll();
    ^
    dummy/Return2.java [212:1] package myApplet does not exist
    myApplet.infoPanel.add(functionForm2.smgframeold);
    ^
    dummy/Return2.java [213:1] package myApplet does not exist
    myApplet.infoPanel.validate();
    ^
    dummy/Return2.java [214:1] package myApplet does not exist
    myApplet.infoPanel.repaint();
    ^
    please help! thanks :)

    I don't declare any packages though....i think it just doesn't recognize myApplet for some reason..
    other errors i got compiling are:
    dummy/Return2.java [82:1] cannot resolve symbol
    symbol : variable myApplet
    location: class Return2
    updateDesc.setString(3, myApplet.staticName);
    I Don't get why i'm getting this error cuase they worked fine when myApplet was a standalone application, not an applet.
    myApplet is in the same folder as Return2 and it compiles properly.

  • How can I write an instance of a class in a static variable

    Hi !
    I have an instance of a class
    Devisen dev = new Devisen();
    In an other class I have a static method and I need there the content of some variables from dev.
    public static void abc()
    { String text=dev.textfield.getText()
    I get the errormessage, that the I cannot use the Not-static variable dev in a static variable.
    I understand that I cannot reference to the class Devisen because Devisen is not static I so I had to reference to an instance. But an instance is the same as a class with static methodes. (I think so)
    Is there a possibility, if I am in a static method, to call the content of a JTextField of an instance of a class ?
    Thank you Wolfgang

    Hallo, here is more code for my problem:
    class Login {
       Devisen dev=new Devisen();
    class Devisen {
       JTextField field2;
       if (!Check.check_field2()) return; // if value not okay than return
    class Check {
       public static void check_field2()
         HOW TO GET THE CONTENT OF field2 HERE ?
    One solution ist to give the instance to the static function, with the keyword "this"
    if (!Check.check_field2(this)) return;and get the instance
    public static void check_field2(Devisen dev)BUT is that a problem for memory to give every method an instance of the class ? I have 50 fields to control and I dont want do give every check_method an instance of Devisen, if this is a problem for performance.
    Or do I only give the place where the existing instance is.
    Hmm...?
    Thank you Wolfgang

  • Using Static Variable against Context Attribute for Holding IWDView

    Dear Friends,
    I have a method which is in another DC which has a parameter of the type IWDView. In my view, I will have an action which will call the method in another component by passing the value for the view parameter. Here, I can achieve this in 2 types. One is - I declare a static variable and assign the wdDoModifyView's view as parameter value and I can pass this variable as parameter whenever calling that method or the second way - create an attribute and assign the same wdDoModifyView's view parameter as its value. Whenever I call this method, I can pass this attribute as parameter. What is the difference between these two types of holding the value since I am storing the same value i.e., wdDoModifyView's view parameter. But when I trigger the action from different user sessions, the first type of code (using static variable) prints the same value in both the sessions for view.hashCode() and View.toString(), but the same is printing the different values when I pass the attribute which holds the view parameter.
    Clarification on this is highly appreciated
    The problem I face is when I use static variable to get the view instance and export the data using the UI element's id, the data belonging to different user sessions is mixed up where as when I use Context Attribute, the same problem doesn't arise. I want to know the reason why it is so. Is there any other place or way where I can get the current view instance of each session instead of wdDoModifyView?

    Hi Sujai ,
    As you have specified the problem that we face when we use  static attributes, when end users are using the application .
    Static means i  have n number of objects but the static variable value will remain same every where.
    when it is context attribute for every object i.e nth object you have a nth context attribute i mean nth copy of the context attribute.
    so every user has a unique Iview parameter , when context is used and
    when static is used  , assume you have userA , his iview is set this intially  and u have another user B , when he is using  , since the variable is static and when you access this variable you will get the value of userA.
    Regards
    Govardan Raj

  • Resetting a variable deletes cache in all subject areas.

    I have a static variable as maxdatadate which I use in only one BM LTS to filter data. (There are about 30 BMs in the repository) When I reset this variable to a new date, I lose cache related to all the BMs. Has anyone experienced the same? Version is 7.8.4. Is this corrected in newer versions?
    Thank You

    No need to available it , you just need to use it using expression where ever it is possible.
    Check this http://docs.oracle.com/cd/E23549_01/bi.1111/e10540/variables.htm
    To keep it Physically as you need you may need to create a new logical column Time Logical table in BMM and then use expression as repository variable and put that column in all subject areas
    ~ http://cool-bi.com

  • Non-static variable Help needed

    Hi, I am creating a multi threaded web server but get the following error
    non-static variable this cannot be referenced from a static context
    HttpRequest request = new HttpRequest(connectionSocket);
    Please could someone help.
    Many Thanks
    import java.io.* ;
    import java.net.* ;
    import java.util.* ;
    public final class MultiWebServer
    public static void main(String argv[]) throws Exception
         // Set the port number.
         int port = 6789;
    // Establish the listen socket.
                   String fileName;
                   ServerSocket listenSocket = new ServerSocket(port);
    // Process HTTP service requests in an infinite loop.
    while (true) {
         // Listen for a TCP connection request.
         Socket connectionSocket = listenSocket.accept();
    // Construct an object to process the HTTP request message.
    HttpRequest request = new HttpRequest(connectionSocket);
    // Create a new thread to process the request.
    Thread thread = new Thread(request);
    // Start the thread.
    thread.start();
    final class HttpRequest implements Runnable
         final static String CRLF = "\r\n";
         Socket socket;
    String requestMessageLine;
    String fileName;
    Date todaysDate;
         // Constructor
         public HttpRequest(Socket socket) throws Exception
              this.socket = socket;
              socket = null;
    // Implement the run() method of the Runnable interface.
    public void run()
         try {
              processRequest();
         } catch (Exception e) {
              System.out.println(e);
    private void processRequest() throws Exception
         // Get a reference to the socket's input and output streams.
         //InputStream is = new InputStream(socket.getInputStream());
         //DataOutputStream os = new DataOutputStream(socket.getOutputStream());
    BufferedReader inFromClient =
                        new BufferedReader(new InputStreamReader(
                             socket.getInputStream()));
                   DataOutputStream outToClient =
                        new DataOutputStream(
                             socket.getOutputStream());
         // Set up input stream filters.
         requestMessageLine = inFromClient.readLine();
         //BufferedReader br = null;
         // Get the request line of the HTTP request message.
    String requestLine = null;
    // Display the request line.
    System.out.println();
    System.out.println(requestLine);
    StringTokenizer tokenizedLine =
                             new StringTokenizer(requestMessageLine);
                   if (tokenizedLine.nextToken().equals("GET"))
                        fileName = tokenizedLine.nextToken();
                        if ( fileName.startsWith("/")==true )
                             fileName = fileName.substring(1);
    File file = new File(fileName);
                        int numOfBytes = (int)file.length();
                        FileInputStream inFile = new FileInputStream(fileName);
                        byte[] fileInBytes = new byte[numOfBytes];
                        inFile.read(fileInBytes);
                        /* Send the HTTP header */
                        outToClient.writeBytes("HTTP/1.1 200 Document Follows\r\n");
                        if (fileName.endsWith(".jpg"))
                             outToClient.writeBytes("Content-Type: image/jpeg\r\n");
                        if (fileName.endsWith(".jpeg"))
                             outToClient.writeBytes("Content-Type: image/jpeg\r\n");
                        if (fileName.endsWith(".gif"))
                             outToClient.writeBytes("Content-Type: image/gif\r\n");
                        if (fileName.endsWith(".html"))
                             outToClient.writeBytes("Content-Type: text/html\r\n");
                        if (fileName.endsWith(".htm"))
                             outToClient.writeBytes("Content-Type: text/html\r\n");
                        outToClient.writeBytes("Content-Length: " + numOfBytes + "\r\n");
                        outToClient.writeBytes("\r\n");
                        /* Now send the actual data */
                        outToClient.write(fileInBytes, 0, numOfBytes);
                        socket.close();
                   else
                   System.out.println("Bad Request Message");
                   todaysDate = new Date();          
                   try {
                        FileInputStream inlog = new FileInputStream("log.txt");
                        System.out.println(requestMessageLine + " " + todaysDate );
                        FileOutputStream log = new FileOutputStream("log.txt", true);
                        PrintStream myOutput = new PrintStream(log);
                        myOutput.println("FILE -> " + requestMessageLine + " DATE/TIME -> " + todaysDate);
                   catch (IOException e) {
                   System.out.println("Error -> " + e);
                   System.exit(1);
    socket.close();

    import java.io.* ;
    import java.net.* ;
    import java.util.* ;
    public final class MultiWebServer
    public MultiWebServer(){
    try{
    // Set the port number.
    int port=6789;
    // Establish the listen socket.
    String fileName;
    ServerSocket listenSocket=new ServerSocket(port);
    // Process HTTP service requests in an infinite loop.
    while(true){
    // Listen for a TCP connection request.
    Socket connectionSocket=listenSocket.accept();
    // Construct an object to process the HTTP request message.
    HttpRequest request=new HttpRequest(connectionSocket);
    // Create a new thread to process the request.
    Thread thread=new Thread(request);
    // Start the thread.
    thread.start();
    }catch(IOException ioe){
    }catch(Exception e){
    public static void main(String argv[]) throws Exception
    new MultiWebServer();
    final class HttpRequest implements Runnable
    final static String CRLF = "\r\n";
    Socket socket;
    String requestMessageLine;
    String fileName;
    Date todaysDate;
    // Constructor
    public HttpRequest(Socket socket) throws Exception
    this.socket = socket;
    socket = null;
    // Implement the run() method of the Runnable interface.
    public void run()
    try {
    processRequest();
    } catch (Exception e) {
    System.out.println(e);
    private void processRequest() throws Exception
    // Get a reference to the socket's input and output streams.
    //InputStream is = new InputStream(socket.getInputStream());
    //DataOutputStream os = new DataOutputStream(socket.getOutputStream());
    BufferedReader inFromClient =
    new BufferedReader(new InputStreamReader(
    socket.getInputStream()));
    DataOutputStream outToClient =
    new DataOutputStream(
    socket.getOutputStream());
    // Set up input stream filters.
    requestMessageLine = inFromClient.readLine();
    //BufferedReader br = null;
    // Get the request line of the HTTP request message.
    String requestLine = null;
    // Display the request line.
    System.out.println();
    System.out.println(requestLine);
    StringTokenizer tokenizedLine =
    new StringTokenizer(requestMessageLine);
    if (tokenizedLine.nextToken().equals("GET"))
    fileName = tokenizedLine.nextToken();
    if ( fileName.startsWith("/")==true )
    fileName = fileName.substring(1);
    File file = new File(fileName);
    int numOfBytes = (int)file.length();
    FileInputStream inFile = new FileInputStream(fileName);
    byte[] fileInBytes = new byte[numOfBytes];
    inFile.read(fileInBytes);
    /* Send the HTTP header */
    outToClient.writeBytes("HTTP/1.1 200 Document Follows\r\n");
    if (fileName.endsWith(".jpg"))
    outToClient.writeBytes("Content-Type: image/jpeg\r\n");
    if (fileName.endsWith(".jpeg"))
    outToClient.writeBytes("Content-Type: image/jpeg\r\n");
    if (fileName.endsWith(".gif"))
    outToClient.writeBytes("Content-Type: image/gif\r\n");
    if (fileName.endsWith(".html"))
    outToClient.writeBytes("Content-Type: text/html\r\n");
    if (fileName.endsWith(".htm"))
    outToClient.writeBytes("Content-Type: text/html\r\n");
    outToClient.writeBytes("Content-Length: " + numOfBytes + "\r\n");
    outToClient.writeBytes("\r\n");
    /* Now send the actual data */
    outToClient.write(fileInBytes, 0, numOfBytes);
    socket.close();
    else
    System.out.println("Bad Request Message");
    todaysDate = new Date();
    try {
    FileInputStream inlog = new FileInputStream("log.txt");
    System.out.println(requestMessageLine + " " + todaysDate );
    FileOutputStream log = new FileOutputStream("log.txt", true);
    PrintStream myOutput = new PrintStream(log);
    myOutput.println("FILE -> " + requestMessageLine + " DATE/TIME -> " + todaysDate);
    catch (IOException e) {
    System.out.println("Error -> " + e);
    System.exit(1);
    socket.close();

  • Non-static variable being used in static context

    I am currently attempting to write a basic user login system using basic applets. I have two JTextFields named "userText" and "passText".
    What i am attempting to do is use the ".getText()" method to get the text out of the JTextField and verifying the string against a string already in a file using the bufferedReader, etc.
    However when i try to compare the string in the file with the one in the text field using the following code:
    if ((line.compareTo(username)) == 0)
    i get the following error...
    "non-static variable being used in a static context"
    Any ideas?

    The static method doesn't know about instances of the class instead you pass the instance to the method:
    static public void myMethod(MyClass instance, String var) {
      if(instance.line.compareTo(var))
    And then the call would be:
    MyClass.myMethod(anInstance, userName);

Maybe you are looking for