Learn Java for Web Development

(Tina Meador) #1
CHAPTER 2: Building Web Applications Using Servlets and JSP 79

Expressions

Expressions are similar to scriptlets, but they evaluate a regular Java expression and return a result,
which is a String or something convertible to a String, to the client as part of the response. The
general syntax is as follows:


<%= expression %>


Scriptlets

Scriptlets are blocks of Java code surrounded within the <% and %> delimiters to create dynamic
content. Listing 2-19 illustrates the usage of a declaration with a scriptlet and expression.


Listing 2-19. Usage of Declaration, Scriptlet, and Expression


1.<%!
2.public String hello() {
3.String msg = "Hello World";
4.return msg;
5.}
6.%>
7.Message from Scriptlet: <%hello();%>

8.Message from Expression: <%=hello() %>


   Lines 1 to 6: These lines contain a JSP declaration that declares a hello()
method. Line 1 is the start tag, and line 6 is the end tag of the declaration.
 Line 7: The hello() method declared in lines 1 to 6 is used in an expression
on line 7.

Figure 2-27 illustrates the usage of declaration, scriptlets and expression.


Figure 2-27. Using the declaration, scriptlet, and expression


Implicit Objects

In a web application, multiple web components collaborate with each other and share information by
means of objects that are maintained as attributes of four scope objects. You access these attributes
by using the getAttribute and setAttribute methods of the class representing the scope. Table 2-4
lists the scope objects.

Free download pdf