- Server-side Basics
- Using Included Files
- Using Variables
- Using Flow Control
- Be Creative
Using Flow Control
The primary method of flow control for designers is what is referred to as if/else statements. These statements can check for something, such as the existence of a variable, and control what is output based on what it finds. Take a look at the following code:
<TITLE> <% if (Title != null) { %> <%= Title %> <% } else { %> Default Title <% } %> </TITLE>
This code will check first to see if the Title variable exists. The condition is the code in the parentheses: (Title != null). In this example, it checks the Title variable to see if it is not equal to null (an exclamation mark means "not" in Java) or the value of a nonexistent variable. In other words, it checks to see if the variable exists. If it does exist, that value will be output in the title tag, like this:
<TITLE>This is the Title value.</TITLE>
If not, the value from the else statement will be output, such as this:
<TITLE>Default Title</TITLE>
The squigglies ({}), called brackets in geekspeak, are what contain the information relating to the appropriate if or else condition. It seems odd in this case because the JSP scriptlet elements are separating the JSP code with the normal HTML code. So the start bracket is in the first JSP scriptlet:
{ %>
And the end bracket is in another, with the output HTML in between:
} %>
NOTE
The HTML in between will not be included in the HTML page output if the if or else statement it belongs to is not the correct one. Only one, if or else, can be output.
A really effective method of creating subnavigation is to determine sublinks based on the section the user is currently in. For example, suppose that in the About Us section of your company's Web site, you have the following links:
If you set a variable in all your files called "group", you could simply perform a check to see if the user is in a specific group. If she is, you could then simply output the subnavigation links. To set a variable called "group", use the following line:
<% String group = new String("about"); %>
To perform the group checking, your JSP code would look like this:
<a href="/about/">About Us</a> <% if (group.equals("about")) { %> <a href="/about/company.jsp">Company History</a><br /> <a href="/about/investors.jsp">Investor Info</a><br /> <a href="/about/locations.jsp">Locations</a><br /> <% } %>
If the group variable is equal to "about", the information in the if block executes, and thus your subnavigation is shown. Simply change the value of the group variable and what you are checking for; you can do this for all the navigation groups that you want to display subnavigation for.
NOTE
Remember to set this variable in every page or you will receive an error.