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?

2
  • You are not importing int class.(java.lang.Integer). Writing Java code inside JSP is not a good way. Commented May 1, 2012 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. Commented May 1, 2012 at 16:28

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

What if I need HTML to go between declaration and variable use?
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, 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.
-1

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

<%! int testNumber = 0; %>

2 Comments

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.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.