JSP variable scope issue

I have a page of the form:

== Start ==

<%! int someVariable = 0; %>
<%= someVariable %>
<% someVaribale++; %>

== End ==
Now when I run the page the first time I get 0 then each subsequent
time a higher number... Why?  I should think the scope of someVariable
is local and to make the scope application or session I would need to
do something special. I even clear the cache on firefox and the bloody
thing still increments.

I'm using Netbeans  6.7.1 with Glassfish v3 if it makes a difference.
0
ken473 (54)
12/9/2009 9:52:25 PM
comp.lang.java.programmer 52476 articles. 0 followers. Post Follow

2 Replies
318 Views

Similar Articles

[PageSpeed] 13
Ken wrote:
> I have a page of the form:
> 
> == Start ==
> 
> <%! int someVariable = 0; %>
> <%= someVariable %>
> <% someVaribale++; %>
> 
> == End ==
> Now when I run the page the first time I get 0 then each subsequent
> time a higher number... Why?  I should think the scope of someVariable
> is local and to make the scope application or session I would need to
> do something special. I even clear the cache on firefox and the bloody
> thing still increments.

"<%!" opens a declaration block, so 'someVariable' is an instance variable of 
the servlet.  Servlet containers like to reuse servlet instances whenever 
feasible and permitted.  So you have the same instance with the same member 
incrementing.

Don't use scriptlet in JSP.

-- 
Lew
0
Lew
12/10/2009 12:13:48 AM
Ken wrote:
> I have a page of the form:
> 
> == Start ==
> 
> <%! int someVariable = 0; %>
> <%= someVariable %>
> <% someVaribale++; %>
> 
> == End ==
> Now when I run the page the first time I get 0 then each subsequent
> time a higher number... Why?  I should think the scope of someVariable
> is local and to make the scope application or session I would need to
> do something special. I even clear the cache on firefox and the bloody
> thing still increments.
> 
> I'm using Netbeans  6.7.1 with Glassfish v3 if it makes a difference.
"<%!" starts a class-level declaration. so someVariable is declared at 
the JSP servlet object level.  you could use <% int someVariable = 0; 
%>.  The better alternative is to not use scriptlets at all, and use 
some form of MVC architecture.



-- 
Daniel Pitts' Tech Blog: <http://virtualinfinity.net/wordpress/>
0
Daniel
12/10/2009 12:18:10 AM
Reply:
Similar artilces about - JSP variable scope issue:

calender in jsp
My jsp user interface contains one Textfield and button beside the textfiled. If that button is clicked , a calender should be displayed and the selected date in that particular calender is to be displayed in the textfield. how to do this in JSP? On 24 Jul 2005 10:54:02 -0700, quickcur@yahoo.com wrote: > My jsp user interface contains one Textfield and button beside the > textfiled. If that button is clicked , a calender should be displayed > and the selected date in that particular calender is to be displayed in > the textfield. > how to do this in JSP? The same way you m...

To strip off a prefix in a variable..
Hi all, I have the following variable: $a = "xxx_active_jsmith"; Now I want to strip ohf the prefix, xxx_active_ and want to store only the id, jsmith into the variable $b. That means, it should be $b = "jsmith"; How can I do that? Thanks J On Sun, 03 Feb 2008 21:56:00 -0800, clearguy02 wrote: > Hi all, > > I have the following variable: > > $a = "xxx_active_jsmith"; > > Now I want to strip ohf the prefix, xxx_active_ and want to store only > the id, jsmith into the variable $b. That means, it should be $b = > "jsmith"...

proc logistic with class variables
Hi, My wife and I are using proc logistic to predict medicine use by danish school children and have a bit of a problem figuring out which options to use with the class variables. Basically the model is proc logistic data=school; class grade sex; model medicine_use = age sex age*sex symptoms; run; Where grade is either 5,7 or 9; sex is 1 or 2; symptoms is 1-5. In responses to another question (see link at the bottom of the post) we have received the additional advise to use following variants of the class statement: class grade sex / param=ref; class grade sex / param=glm; We have teste...

JSP/MySQL debugging issue
Not exactly JavaBeans, but pretty close... If anybody knows a better resource on usenet for just JSP, please feel free to let me know. Another day, another stupid question proving how little I know about this language that I'm supposed to be coding in right now... I have a 'subroutine' in the jsp that I'm currently working on that works with about 20-30 different variables; general manipulation, tossing them in to various database tables, etc... Anyway, there's a whole load of SQL queries, inserts, and updates going on in this piece of code, too. One of them (a...

US-TX-Austin: QA Developer, JSP, Java, HTML, JUnit, HttpUnit, SilkTest, SQL; DH (45320457601)
US-TX-Austin: QA Developer, JSP, Java, HTML, JUnit, HttpUnit, SilkTest, SQL; DH (45320457601) ============================================================================================= Position: QA Developer Reference: SMC01667 Location: Austin TX Duration: DH Skills: 2+yrs SW development exp with Java, JSP, HTML and change management in a Linux environment. 2+yrs exp with test automation tools (e.g., JUnit, HttpUnit, WinRunner, SilkTest). 2+yrs exp with scripting (PERL, Python, shell). 1 or more y...

Environmental Variables
In which physical file are the python environmental variables located? I know I can access them using the: os.environ.get('PYTHONSTARTUP') or os.environ.get('PYTHONPATH') to get their values. But out of the program, if I need to look at them and alter their values, where do I find them? Are they the OS environmental variables as I suspect? If they are, then I'll find them with the other OS environ variables in My Computer->System->Properties->Advanced->Environmental Variables. But I checked that place and did not find any default values for them. Sathya...

Cross-platform issue with .mat files
Hello everyone, I am trying to use on the Windows platform some .mat files produced and saved on a linux machine. When I try to open such .mat files, I receive the following error message: ----------------------------------------- Unable to read MAT file <file.mat> File may be corrupt. ----------------------------------------- If I run the 'file' command (on windows) with the parameter <file.mat> it does recognize that <file.mat> is a Matlab file (encoding and matlab version). Since the execution of the original scripts, used to produce the .mat f...

save variables in multiple excel files
I am having lot of text files. The data in each file is in the format '511E7D7C:13,IIMWV,023,R,18.5,M,A*1D~05'; I want third and fifthcolumn. For that i used textscan and saved that data in separate variable. As i am having multiple files in directory, I have run for loop and I want to save those variables in excel files in the loop. Im using eval and xlswrite but it is not working. Please guide me if any one knows the correct answer. Here is the code: files = dir('*.txt'); for i = 1:numel(files); filename = files(i).name; fid = fopen(filename); C = textscan(...

scope inquiry
Example 1: This code behind the form: Private Function AAA() MsgBox "hey, I made it!" End Function Private Sub Form_Load() Dim strAAA as String strAAA = "AAA()" Eval (strAAA) End Function Results in error 2425 "The expression you entered has a function name that <application title> can't find" Example 2: When the code behind the form is: Private Sub Form_Load() Dim strAAA as String strAAA = "AAA()" Eval (strAAA) End Function and mod1 is in the project and it has the following code Function AAA() MsgBox "hey...

Variables not passed out of WHILE
Dear all I have something new... :-) I recognize, that values of a string are not passed out of a WHILE loop. (See below script for example). My script will not ECHO the value of $var at the end. .. Why? How can I make variables "global" ? Kind Regards Oliver ------------ TEST.SH ------------ #!/bin/sh # Sun Solaris UNIX mystring="token1: token2 tokena: tokenb"; echo $mystring | while IFS=: read a b; do var="mein Wert"; # Was trying with 'set' and 'export' too done echo "Mein WERT: $var"; ------------ TEST.SH ------------ O...

GUI global variable code help button popupmenu
Dear All, i have a problem with a code of a GUI. I have a GUI called "Index" with one pushbutton called "Start" and one pop-up menu called "Target". When i click on Start button runs a function that give me an output parameter called "Trial". So in the Start_Callback i write this function code: [Trial]=sample where "sample" is the function. Now when i choose an element on the pop-up menu, runs another function that get how input the parameter "Trial". So my question is: How i can use the parameter "Trial" also in the Target_...

Tomcat, JSP and AS400JDBCDriver
Hello group, I have managed to install and configure Tomcat 5.5 on V5r3 and it is running great. I also have some simple test JSP page to read and populate database table from browser. It is also working great except one thing...character encodning. Please, if anyone knows how to solve the problem?! We are using CCSID 870 on our table also as on our system and this codepage need to be converted to WINDOWS-1250 or UTF-8 to get Eastern European characters. There is configuration parameters of context.xml <?xml version="1.0" encoding="UTF-8"?> <Context> <...

Variable renaming in Editor
Hi, Another newbie question. I've imported some data in from an Excel file using the Import Wizard, and from this I've generated an M-file using the "Generate MATLAB code" tickbox. I've then added further code in the M-file to perform some simple maths/analysis of the data in the variables that are created. In these later sections of code I call different variables. When I initially did this with my test Excel file, it worked fine, but now I'm trying to use it on another Excel file, the says that the variable I've called is undefinied. When the importfile secti...

applet -- new to security issues...
nothing has ever frustrated me more than trying to connect to a server (in this case a jabber server..) with an applet.. I'm importing smack package to write an applet client (http://www.jivesoftware.org/smack/, http://www.jivesoftware.org/builds/smack/docs/latest/javadoc/) just to test I wrote a jsp, can connect to jabber.org server fine w/jsp.. but with an applet it's been like pulling teeth, I swear... we signed all three smack jars, but still can't connect to server.. (get SocketPermission error..) so someone told me I need to put some code in applet from here.. htt...

FAQ 7.14 What is variable suicide and how can I prevent it? #10
This is an excerpt from the latest version perlfaq7.pod, which comes with the standard Perl distribution. These postings aim to reduce the number of repeated questions as well as allow the community to review and update the answers. The latest version of the complete perlfaq is at http://faq.perl.org . -------------------------------------------------------------------- 7.14: What is variable suicide and how can I prevent it? This problem was fixed in perl 5.004_05, so preventing it means upgrading your version of perl. ;) Variable suicide is when you (temporarily or permanent...

Peak filter with small bw issue...
Hello! I have some issue showing up at below 100Hz area when small bw is used with peak filter. There are negative values present when using positive gain value (and vice versa). I'm using formulas from the eq-cookbook.txt, long double variables + Fs = 96000.0 peak filter center freq = 18Hz bw = 0.010 (equals to Q = ~144.269) gain +18.0 dB I get these results (an example): sample/frequency dB sample 13 value = 0,0109341784181966 sample 14 value = 0,01607368377577 sample 15 value = 0,0268763954733991 sample 16 value = 0,057303123113535 sample 1...

Using variables in a macro call
-----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hello, I am facing the following problem with Common Lisp's defmacro: I want to call a macro with the contents of a variable, not with the variable itself. For example: (defparameter *bar* '(1 2 3)) (defmacro foo (l) (car l)) Now this won't work: (foo *bar*) Is there any sensible way to define *bar* or call foo in such a way that 2 would be the result. Redifining foo to (defmacro foo (l) `(car ,l)) is not really what I have in mind, because I really want to have the macro do its work with the list here. Thanks. Regards, Christia...

How to start a new session in JSP?
Hello, I wrote a JSP application - I want to start a new session on my first page. I wrote a code: <% session.invalidate(); session = request.getSession(true); %> I am getting a long error starts like that: [8/23/08 9:34:17:453 EDT] 0000003a ServletWrappe E SRVE0068E: Could not invoke the service() method on servlet /Select_env.jsp. Exception thrown : java.lang.IllegalStateException: Session Object Internals: id : 9r0eE_QJbYsM_m5irgLbanq hashCode : 1516111642 create time : Sat Aug 23 09:29:53 EDT 2008 last access : Sat Aug 23 09:29:53 EDT 2008 max inactive interval : 1800 user ...

Re: Quoting macro variables in set satement
On Tue, 27 Apr 2004 18:06:14 +0100, =?iso-8859-1?q?taran=20gujral?= <taran_jit@YAHOO.COM> wrote: >Hi All > >I am trying to concatenate data sets using data set name as macro variable; >%let dsd1 = = SASLIB.SALES_&dept._&year._&season._&weeks._wks; > >macro concatenate_data ; > data &com_data; > set > %do i = 1 %to &num_dept. ; > &&dsd&i. > %end; > ; > run; > %mend concatenate_data ; > >Invalid variable specification, SASLIB.SALES_144_2003_holiday_4_wks. > Varia...

Design/Configuration issue
Hi all. I have a problem that starts to appears in different places, and I'm trying to understand where the real question is. I'll try to explain it with an example. It would be very nice to have a code like this Mail mail = new Mail("from", "to"); mail.setSubject(...) mail.setBody(...) mail.send(); The problem is in the send method. It could be this way MailSender.getInstance().send(this) or like this connect(smtpServer) placeMsg send I really prefer the second option: MailSender looks a lot like "a method with a class around". Yes, MailSender...

Applet to Servlet to JSP communications
Hi all, I'm still somewhat new to servlet/JSP programming, but I want to my application to use the MVC model. I have some simple JSP pages that dynamically open an applet that the user uses for data entry. The applet then opens a channel to the servlet and passes the data to the servlet in a serialized object. I have tested this part of the communication by having the servlet send the data back to the applet to display. This next step is giving me a problem. What I want to do is have the servlet perform database searches based on the data from the applet and forwarding the formatted ...

referencing this in a JSP page
Can you reference "this" in a JSP page. I am using log4j to log errors but this wants the class name so I was looking to user this.getClass().getName() to do this. If there another way? Many Thanks Mike "Jon Smith" <usenet123@ntlworld.com> writes: > Can you reference "this" in a JSP page. Yes, but it's not that useful. "this" will be an instance of the autogenerated servlet class the JSP compiler produces the source for. "Jon Smith" <usenet123@ntlworld.com> wrote in message news:420b2a58$0$38039$5a6aecb4@news.aais...

JSP compilation time difference?
I'm currently experiencing a problem while viewing a JSP page immediately after restarting. I log into the web front and view the pages, wherein I experience a problem of expected data/object not displaying. However, if I refresh the page the data is displayed. I'm trying to fathom if this is due to an interaction between the container and certain children compiling and displaying faster than the inline content (being generated by a server-side application method). Has anyone else experienced something similiar? jdhovland wrote: > I'm currently experiencing a problem while v...

XML AND JSP
Is it easy to integrate these two platforms to create web-database type applications. How is the interaction with the database handled, the output, formatting and presentation of data??? My two cents... Writing XSLT which renders as XHTML is easy. But simply writing JSPs is easy too. If there is a chance of porting the application, and say changing it so that it will use web services some day instead of a direct connection to a database, then yes, XSLT in that instance may be better to use. But basically JSP is the way to go since most developers can more readily support it. > Is i...

suggestions to debug JSP pages
I am using tomcat to run JSP pages. The problem is I have a hard time to trace the code. I just change the code, and run in the browser. I always experienced HTTP Status 500 Error. any suggestions to help me debug the JSP pages easier? Please advise. Thanks!! > I am using tomcat to run JSP pages. The problem is I have a hard time to trace > the code. I just change the code, and run in the browser. I always experienced HTTP > Status 500 Error. any suggestions to help me debug the JSP pages easier? > > Please advise. Thanks!! Read Tomcat server log files for the exception me...