Using static variables in JSP

Hi All,
I have written the following code, but its not compiling saying that "Class or interface declaration expected. static "
I dotn know whats wrong in this scriplet though.. any help is greatly appretiated.
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>JSP Scriplet</title>
</head>
<body>
<%
static int counter = 15;
for(int i = 0; i < 15; i++){
int p = returnCounter();
if(p == 0)
System.out.println("I am the 15th user");
public static int returnCounter(){
counter = counter - 1;
System.out.println("counter : " + counter);
return counter;
%>
</body>
</html>

Simply put, you're Java code is wrong.
The detail is that essentially all of the code in your JSP file is in one big method.
So, here's what your code looks like to the compiler:
public void _internalJspDoPageCode() {
    static int counter = 15;
    public static int returnCounter() {
}You can't simply nest methods like this in Java.
If you want to, you can try this:
<%
    public class mycounter {
        static int counter = 15;
        public static int returnCounter() {
            counter = counter - 1;
            return counter;
    for (int i = 0; i < 15; i++) {
        int p = mycounter.returnCounter();
        if(p == 0)
            System.out.println("I am the 15th user");
%>That will create an inner class with a static member, which is basically what you're trying to do.
But note that this inner class is only accessible from this JSP page, and no where else.

Similar Messages

  • 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

  • How to use bind variables in JSP applications ?

    Hi,
    How will i use bind variables in jsp applicaions ?
    Any links that give a clear understanding ?
    TIA,
    jj

    Hi,
    Try this link, this may help you.
    http://www.oracle-base.com/articles/misc/WebScriptingForOracle.php
    Thanks

  • When should I use static variable and when should not? Java essential

    When should I use static variable and when should not? Java essential

    Static => same value for all instances of the class.
    Non-static => each instance can have its own value.
    Which you need in which circumstances is completely up to you.

  • Using JSTL variables in JSP or Javascript. Possible ?

    Hi All,
    Is it possible to share or use the variables which are declared are used by JSTL in JSP expression or scriplet code and in Java Script.
    Example:
    This Works:
    <fmt:set var="test" value="JSTL" />
    <fmt:out value="${test}" />
    But, this gives error:
    <% out.println(test) %>
    And passing the value of variable 'test' to Java Script code also gives error.
    How to use JSTL variables in JSP and in Javascript ?
    Yours,
    Sankar.B

    By default, JSTL variables are kept in servlet
    attributes. Default is to store it in the page
    context. You can make it request/session/application
    scope as required by an attribute of the set tag.Hi there,
    Can anyone advise how to access JSP variables in JSTL?
    Can it be done as the same method through request/session/application scope?
    Thnks...

  • Can I use static variable in EJB?

    Many books suggest developer don't use static variable in EJB,I want to know why?
    I know there isn't any problem if the static varibale is read only
    For writable static varible ,what will happen if I use a static Hashtable for share data
    Help me!Thank you very much!!

    Greetings,
    I know that "EJB business methods are not allowed to
    block on synchronized resources" Just where do you "know" that from?? The EJB 2.0 Specification, at least, is nowhere in agrement with this statement. If it comes from a book I would question the author's reasoning. Contractually, there's no sound basis for this. In the case of Session Beans, they have an expressedly direct and single-threaded association with a client. From a design viewpoint, it certainly seems unnecessary for a bean to "block" its one-and-only client, but to say that it "is not allowed to" do so is without merit. Entity Beans, on the other hand, are concurrently accessible. Yet, with regard to a transactional context being in effect, the container does indeed block on a bean's business methods. For the bean to do so itself is, therefore, unnecessary. Furthermore, the specification explicitly concedes that a "Bean Provider is typically an application domain expert" and "is not required to be an expert at system-level programming." (EJB 2.0 Spec. 3.1.1) From these statements alone it is reasonable to assume the above statement is meritless since the Bean Provider is not expected to even consider synchronization issues when developing a bean.
    But I'm mixed up why we could use "Hashtable" or otherApparently, because your sources are as well...
    collection classes in the EJB ,in these method many
    methods are synchronized In fact, not only "can we use" them but, with respect to multiple-row finders in Entity Beans we are [i]required to use them (or an iteration of them)! Not all Collection classes are synchronized (so called "heavy-weight collections"). As shown above, that the choice of a particular Collection class might be synchronized is of little consequence since a bean designed under strict adherence to the specification ensures that it is never concurrently writeable.
    Could someone provide a good way for this problem?
    Please Help Me!!!Regards,
    Tony "Vee Schade" Cook

  • Is is better to use static variables?

    Hi,
    Does anyone know if it's better to use static variables or to use normal variables?
    Concerning the size of the code, it seems that declaring a variable as static is more consuming (for example plus 6 bytes for an object reference).
    So this could mean that declaring variables as static should be avoided, but what about the execution time?
    Some years ago, some javacard gurus were claiming that it's was better to use static variables (less processing required by the JVM to resolve adresses of static variables), but is it still the case?

    Hi Lexdabear,
    Thanks for the answer.
    I did the test (I converted my all code to use static variables and methods as much as possible), and did a bench before and after, on a JCOP31 card.
    The conclusion is that today JVMs and processors are much powerful than 5 years ago, and that the difference is really difficult to measure, which anyway is a good thing for us ;-)

  • How to use session variable in JSP function  & How to use both JSP  Servlet

    Hi,
    I am new to JSP and servlets
    Still I am devloping a website in JSP. I am not mixing JSP with servlets, but I do create Java files for bean, logic and database works.
    I try to keep the hard coding part out of JSP.
    I dont how to use both JSP and Servlets in combination.
    Hence If needed I write some functions in JSP.
    but it gives me error
    +<%! public void abc()+
    +{+
    int intUserId = Integer.valueOf((Integer) session.getAttribute("MySession_UserID"));
    +}+
    +%>+
    Saying cannot find symbol session
    1) So can u please tell how can I access session variables within JSP function
    2) And also give me some links/tutorials about useing both JSP and Servlets in combination.
    Thanks
    Venkat

    The application architecture when you use Servlets and JSP in a standard MVC pattern is explained here (under the heading "Integrating Servlets and JSP Pages") and here ...

  • "requires unreachable" warning emitted when using static variables and the singleton pattern

    I'm implementing code contracts on an existing code base and I've come across this situation in a few places. Wherever we have additional logic with code contracts where a singleton instance is instantiated, all code contracts emit a "reference use
    unreached", or "requires unreachable" warning.
    The code below demonstrates this.
    static string instance = null;
    static string InstanceGetter()
    if (instance == null)
    instance = "initialized";
    AdditionalLogic(instance); // requires unreachable warning on this line
    return instance;
    static void AdditionalLogic(string str)
    Contract.Requires(str != null);
    Console.WriteLine(str);

    Would the class get unloaded even if the Singleton object has some valid/reachable references pointing to it?
    On a different note, will all the objects/instances of a class get destroyed if the class gets unloaded.That's the other way round, really: instances cannot be garbage-collected as long as they are strongly reachable (at least one reference pointing to them), and classes cannot be unloaded as long as such an instance exists.
    To support tschodt's point, see the JVM specifications: http://java.sun.com/docs/books/jvms/second_edition/html/Concepts.doc.html#32202
    *2.17.8 Unloading of Classes and Interfaces*
    A class or interface may be unloaded if and only if its class loader is unreachable. The bootstrap class loader is always reachable; as a result, system classes may never be unloaded.
    Will the same case (Custom ClassLoader getting unloaded) occur if I write the singleton using the code wherein we lazily initialize the Singleton (and actually create a Singleton instance rather than it being a Class/static variable).You should check the meaning of this vocabulary ("object", "instance", "reference"): http://download.oracle.com/javase/tutorial/java/javaOO/summaryclasses.html
    The difference between the lazy vs eager initializations is the time when an instance is created. Once it is created, it will not be garbage collected as long as it is reachable.
    Now I'm wondering, whether being referenced by a static attribute of a class guarantees being reachabe. I'm afraid not (see the JLS definition of reachable: http://java.sun.com/docs/books/jls/third_edition/html/execution.html#44762). That is, again, unless the class has been loaded by the system class loader.

  • How to use a variable of jsp custom tag in my java code?

    hi folks,
    i got a folderList tag like this:
    ArrayList list = new ArrayList(20);
    %>
    <foo:folderList path="${attributes.newsPath}" var="year" contentType="folder">
    <%
              list.add(${year.contentEntryName});   // of course, this doesn't work
    %>
    </foo:folderList>I think, its clear what I want to do. I am just wondering how I can use my Variable "year" in the Java code between <% %>...

    <% list.add(year.getContentEntryName()); %>
    You have to have defined in the custom tag that "var" relates to a scripting variable that you want defined.
    <tag>
      <variable>
        <name-given>var</name-given>
        <variable-class>myPackage.myClass</variable-class>
        <declare>true</declare>
        <scope>NESTED</scope>
      </variable>
    </tag> Cheers,
    evnafets

  • I want to use static variable instead of using variable in servlet context

    Hi all,
    In my web application i have to generate a unique Id.
    For this, At the application startup time i am connecting to the database and getting the Id and placing it in the servlet context.
    Every time i am incrementing this id to generate a unique id.
    But, now i want to place this id in a static variable which is available to all the classes.
    why i want to do this is to reduce burden on servlet context.
    my questing is, is this a best practice ? If not please give me your valuable suggestion.
    thanks
    tiru

    There isn't a problem with this as long as you want to share the value of that variable with all requests. If this is read-only except when it is first set then you're fine. The only real issue will be how to initialize and/or reinitialize the variable. When the servlet is started, how will you get the value for the variable? If the servlet is shutdown and restarted (a possibility in any application server) how will you re-read the variable? You need to answer these questions to decide the best route. It may be as simple as a static initializer or it may be more complex like a synchronized method that is called to see if the variable is set.

  • How to use enviroment variables in JSP code?

    I�m developing a web server with JSP�s, and I need to move the application to others computers. I need to access to a directory, but I don�t know it because the user can install the Application in the directory he wants. So I need to access to that directory in the JSP code.
    The directory is "C:\Program Files\....\tomcat\webapps\ROOT\upload". I have the CATALINA_HOME enviroment variable defiened as "C:\Program Files\....\tomcat\", so I need to use something like "CATALINAHOME\\webapps\upload\", but I don�t know how to mekr the JSP code to understand the enviroment variable CATALINA_HOME.
    I�ve tried with %CATALINA_HOME%, but the Tomcat server doesn�t recognize it. How can I access to that directory?
    Thanks (Sorry about my english)

    My JSP�s are in: %CATALINA_HOME%\webapps\ROOT\
    I wan�t to access to %CATALINA_HOME%\webapps\ROOT\upload\
    My JSP code:
    <% ...
    String DPATH = "C:\\Program Files\\JBuilder7\\jakarta-tomcat-4.0.3\\webapps\\ROOT\\upload\\";
    File newfile = null;
    newfile = new File(DPATH+filename);
    %>
    I want the JSP to locate the directory \webapps\ROOT\upload\ without knowing the complete route "c:\Program Files\...", because I have the enviroment variable CATALINA_HOME with the value "C:\Program Files\JBuilder7\jakarta-tomcat-4.0.3\". SO the user of the aplication only has to set the CATALINA_HOME variable and the aplication should access the upload directory throught the CATALINA_HOME variable.
    I can�t explain it better. Sorry.

  • Using Javascript variable in JSP

    I m setting a variable named btn to the value of the button which was clicked but the problem here is that i m nt getting its value whn i want to set it to a request.setAttribute() method.

    > Yes... nw i get the prob... thanx yaar .... bt cn u
    suggest me wht cn i do fr this situation
    My first suggestion, beyond all others, is to use real words. Your writing is practically unintelligible.
    Please make the extra effort to write out words such as "now", "problem", "thanks", "but", "can", "you", and "for" (I have no idea what "yaar" means). The extra keystrokes won't cost much in the way of time, and the enhanced clarity will be appreciated by those communicating on a forum with international readership. Also, it will give the appearance that you take your question seriously, which will in turn make your question look more interesting to answer.
    ~

  • Declaring static variable in JSP

    <%
    static Logger browserDetectLog      = Logger.getLogger(ScoConstants.LOGGER_BROWSERDETECT);
    %>
    I m declaring the logger variable like dis.
    It gives me error, whereas in java class it does'nt.
    Please tell me the difference.

    Anything in <% %> delimiters is put inline.
    Anything in <%= %> is put inline but without closing the current out.print().
    Anything in <%! %> is put outside of the _jspservice() method.You should be doing
    <%!
        static Logger browserDetectLog = Logger.getLogger(ScoConstants.LOGGER_BROWSERDETECT);
    %>

  • Using static variables in ejb

    I'm interested in the rule from the EJB spec:
    � An enterprise bean must not use read/write static fields. Using read-only static fields is
    allowed. Therefore, it is recommended that all static fields in the enterprise bean class be
    declared as final.
    This rule is required to ensure consistent runtime semantics because while some EJB containers may
    use a single JVM to execute all enterprise bean�s instances, others may distribute the instances across
    multiple JVMs.
    question 1
    Can you call "Math.random();" in ejb code???
    The javadoc for this method says
    When this method is first called, it creates a single new
    * pseudorandom-number generator
    This means that you can't use it right?
    This is not a problem for me, I know that you can go (new Random()).nextDouble();
    What I'm interested in is, does the EJB spec permit use of this method, and how are you supposed to know when you're breaking the spec like this.
    question 2:
    how about if you have a class
    class MyClass{
    public static final ArrayList MY_LIST = new Arraylist();
    Surely you can't read and write to MY_LIST from EJB's cause you're breaking the rule.
    But at what point are you actually breaking the rule?
    Can anyone out there spell this out for me??

    � An enterprise bean must not use read/write static fields. Using read-only static fields is
    allowed. Therefore, it is recommended that all static fields in the enterprise bean class be
    declared as final.
    Note that the rule covers usage of ALL static fields, not just fields on the implementation class.
    If I use
    MYBeanStaticVariableHolder.myStaticVariable
    for read/write.
    I understand that it's not a good idea, and I would never do it.
    But, does it actually break the spec. yes or no!!! - YES
    If yes, then fine I'm happy, what about my Math.random() question?
    Can you call "Math.random();" in ejb code???
    Math.random() is effectively read-only, because you never write to the result returned and therefore does not break the rule, so calling Math.random() would be allowed.
    how about if you have a class
    class MyClass{
    public static final ArrayList MY_LIST = new Arraylist();
    Surely you can't read and write to MY_LIST from EJB's cause you're breaking the rule.
    But at what point are you actually breaking the rule?
    Can anyone out there spell this out for me??
    If you write to a static field, update the state of an object in a static field, or update the state of an object returned by a static method, when the method does not return a unique instance at each invocation, you are breaking the spec
    public class Sample
        public static final int START_MODE = 0;    // OK
        public static final int STOP_MODE = 1;      // OK
        public static int DEFAULT_MODE;           // updating this is BAD
        private int currentMode;
        public int getMode(){ return currentMode; }
        public void setMode(int mode){ currentMode = mode; }
        // Updating instance is BAD
        public static Sample instance = null;
        // Updating returned instance is BAD
        public synchronized static getInstance()
            if( instance == null ) instance = new Sample();
            return instance;
        // Updating returned instance is OK
        public synchronized static getUniqueInstance()
            Sample instance = new Sample();
            instance.setMode(Sample.MODE_START);
            return new Sample();
    }Hope that helps.

Maybe you are looking for