JSP scripting questions
I'm studying SWCD by Charles Lyons (2nd edition) and i'm reviewing some questions about JSP. On page 262, here's the following question:
Which of the following ca开发者_Python百科use the value 'yes' to be written to the response if the state scripting variable is true and 'no' otherwise?
A. <%=
if (state) {
"yes";
} else {
"false";
}
%>
B. <%=state? "yes" : "no"%>
C. <% if (state) %>yes<%else%>no
D. <% if (state) out.write("yes");
else out.write("no");%>
E. <% state? out.write("yes") : out.write("no");%>
Answer is B & D. I do understand the explanation to the answer given. However nothing is mention about why A is incorrect? I don't see why A is incorrect. Any help is appreciated.
This is the difference between the expression ( <%= expressions %>
) and scriptlets ( <% code %>
) .
For the expression ,anything inside <%= %>
will be get evaluated to a string and this string is inserted into the servlet's output stream directly when the JSP is converted to the servlet. So <%= expressions %>
will convert to out.println(expressions)
. There should be no semicolon at the end of the expression , because out.println(expressions;)
has the syntax error after the JSP is converted to the servlet.
For the scriptlets , anything inside <% %>
will directly inserted as raw Java code in the service method of the generated Servlet. So <% code(); %>
will convert to code();
So , for the option A , <%= if (state) { "yes"; } else { "false"; } %>
will convert to the out.println(if (state) { "yes"; } else { "false"; } )
, which have syntax error .So A is incorrect
精彩评论