• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

enthuware question

 
trivikram Kumar
Ranch Hand
Posts: 172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Which of these two is a valid JSP code fragment?

<%!
Hashtable ht=new Hashtable();
{
ht.put("max","10");
}
%>

OR

<%!
Hashtable ht=new Hashtable();
ht.put("max","10");
%>
 
Wei-ju Wu
Ranch Hand
Posts: 147
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The first one is correct, that one would have the effect:



The code within the curly braces is an instance initializer which will be called when the servlet is created.

In the second case the code is not placed in curly braces so it stands where the compiler would expect a declaration - so it is illegal.
 
trivikram Kumar
Ranch Hand
Posts: 172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thankyou Wei-ju Wu for your reply...
Can't we write the code (which you said illegal)in that way??...and can't it be called when MyServlet is called??
Should it definetely be defined in an initializer??
But your answer is perfectly correct.

Thanks,
Javainn
 
Wei-ju Wu
Ranch Hand
Posts: 147
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
One needs to imagine how the container will transform and handle your JSP: it will first try to transform it into a servlet class, placing scriptlets and expressions within _jsp_service() and jsp declarations outside of the service method, but as members of the servlet class.

Then you regard it as a regular Java class and just try to figure out if it is legal Java syntax and therefore, compilable.

You can try that by writing a simple class which does the creation and setting the value, in one case putting the code in curly braces, in the other without and try to compile it.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic