Java Reference
In-Depth Information
Which source code would you rather type in?
Now that know how to forward to a JSP, the trick is that we only want to forward to a JSP after the user has
selected a function and clicked the submit button. In other words, if the user simply requests EnterEmpInfoJSP
(with a get request), we want to display the form. When the user clicks the submit button and invokes EnterEmpInfoJSP
with a post request, we want the form to check which function was selected. We will use the JSTL
if
tag to check for
the request type and the JSTL
choose
tag to determine which function was selected. Both of these tags will use
Expression Language (EL) to access the request object.
The
if
tag syntax is simple:
<c:if test='${
condition
}'>
body
</c:if>
The condition, of course, needs to be specified and the body contains whatever function should be performed
when the condition is true. For example, inserting 1==1 as the condition and the text “Yikes it works” for the body
as follows:
<c:if test='${1==1}'> Yikes it works </c:if>
would result in the text “Yikes it works” appearing in the browser. The body of the
if
tag is not limited to static text.
Tags, scriptlets, expressions, or HTML can all be specified. This example also includes your first look at Expression
Language (EL). Everything within the quotes of the test value is considered EL. The EL syntax dictates that any
condition begin with a $ and be enclosed in braces. Not too tough to remember but it doesn't seem very useful
either. The real power of EL is that it allows you to access information contained in the JSP container (like the implicit
request and response objects, parameters, beans, etc.) without using the cumbersome Java syntax. Also, all the Java
comparison operators (e.g., >, ==, <, etc.) can be used to define conditions. For example, in the servlet we used:
String function = req.getParameter("functionLB");
if (function.equals("Display")) { }
to get the functionLB value and check its value. Now this is a slightly unfair comparison, because in the servlet
example we retrieved the functionLB value and assigned it to a variable and then used the variable in the
if
statements. A fairer comparison would be between the following
if
statement:
if(req.getParameter("functionLB").equals("Display")) {}
and the following
if
tag with EL:
<c:if test='${param.functionLB=="Display"}'> </c:if>
If we strip away the required
if
syntax in the two examples, we are left with the following Java code in the servlet:
req.getParameter("functionLB").equals("Display")
and the following EL code in the
if
tag:
${param.functionLB=="Display"}
It's pretty obvious that EL is simpler than Java.