Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Valid JSP code fragments

 
Kedar Dravid
Ranch Hand
Posts: 333
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Which of the following are valid JSP code fragments?

1.
<%@ page import="java.util.*" autoFlush="true"%>
<%@ page import="java.io.*" autoFlush="false"%>

2.
<%Date d = new Date();
out.println(d);
%>

3.
<%= String val = request.getParameter("hello");
out.println(val);
%>

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

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


Select 2 correct options
a 1
b 2
c 3
d 4
e 5

Given answers: b, d
My question:
Why are options e(5) and option a(1) invalid?
 
Vengan Krish
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I don't see anything wrong in option 1.
But obviously option 5 would fail during compilation of the translated jsp class.
Here is how the translated code would look like with option 5 in a JSP.



Please note the statement ht.put("max", "10"); is invalid in a class body without opening/closing braces.

Regards
 
Mohit Agarwal
Ranch Hand
Posts: 88
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why opening and closing braces are mandatory with regard to option 5?
Please provide some reason for this ?

Tx .
Mohit.
 
shiva viswanathan
Ranch Hand
Posts: 152
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Mohit

The reason for this that statements are not valid in a class body outside
methods

However , if you put a statement withing { (brackets ) then
they are treated as intitializer code , ie run when the class is loaded

Hence statements outside method , in class body are valid only if they are within class initializers ie within { and }

Hope this helps
Catch You Later
Shiva
 
Mohit Agarwal
Ranch Hand
Posts: 88
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Got your point .
I really missed that .
Tx Shiva.
 
Catherine van Borselaer
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

The first answer is not right because you can't set the attribute autoFlush twice in one page. That won't work.

<%@ page import="java.util.*" autoFlush="true"%>
<%@ page import="java.io.*" autoFlush="false"%>
 
Radmika Arunachalam
Ranch Hand
Posts: 45
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
option 1 is invalid because autoFlush attribute is defined two times... remember in page directive only import is allowed to declare many times..

Radhika
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic