1

Consider this example:

<% int testNumber = 1; %>
//Some HTML goes here
<%=testNumber%>

I get compile error:

testNumber cannot be resolved to a variable

Can someone explain what is going on?

Eleeist
  • 6,891
  • 10
  • 50
  • 77
  • You are not importing int class.(java.lang.Integer). Writing Java code inside JSP is not a good way. – vikiiii May 01 '12 at 16:25
  • @vikiiii If I do everything in a single pair of <% %> then it works. Amit Bhargava - That is the content of my test.jsp file. – Eleeist May 01 '12 at 16:28

2 Answers2

3

You need to make sure that you understand variable scoping. It's in scriptlets the same as in normal Java classes.

So if you actually have for example

<%
   if (someCondition) {
       int testNumber = 1;
   }
%>

...

<%=testNumber%>

Then you will get exactly this error (also in a normal Java class!). To fix this, you'd need to make sure that the variable is declared in the very same scope, if necessary with a default value.

<%
   int testNumber = 0;

   if (someCondition) {
       testNumber = 1;
   }
%>

...

<%=testNumber%>

Unrelated to the concrete problem, using scriptlets is considered poor practice.

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • What if I need HTML to go between declaration and variable use? – Eleeist May 01 '12 at 16:29
  • It should not matter. The point is that the variable needs to be declared in the same scope as where you need to access it. You've apparently declared the variable in a different and narrower scope (e.g. inside `if` or `for` block, etc) while you're trying to access it from outside. It's not different from in a normal Java class. Using a normal Java class is only easier to understand and maintain the code. – BalusC May 01 '12 at 16:33
  • BalusC, thanks for the link. It contained a lot of useful info I had no idea about. In that case I will have to rewrite my code to remove all/most scriptlets. – Eleeist May 01 '12 at 16:43
-1

Design problems aside, try declaring the variable as a global:

<%! int testNumber = 0; %>
Alexander Pavlov
  • 31,598
  • 5
  • 67
  • 93
  • This is a very bad idea! Instead of a local variable in the service method this gets placed as a member on the servlet class. Threads will mess this up on concurrent requests. Servlets are not thread safe so you will get into issues if you add state to a servlet instance. – Bogdan May 01 '12 at 16:41
  • I never said it was a good idea (and I also mentioned this in the foreword to the answer), just suggested an alternative solution for the particular problem in question, leaving it up to the OP to decide. – Alexander Pavlov May 02 '12 at 08:53