Java Reference
In-Depth Information
Listing 3-2 shows the fragment of a servlet that uses attributes.
Line 3 : This retrieves the userName from the request.
Line 4 : This sets the userName as an attribute in the request.
Line 5 : This retrieves the RequestDispatcher from the request.
Line 6 : This forwards to the view, passing request and response object. Note
that this request object has an attribute set in it for the userName . The view can
now make use of this attribute
Listing 3-3. The First JSP
1.<html><body> Hello
2.<%= request.getAttribute("name") %>
3.</body></html>
4.<html>
5.<body>
6.<% User u = (User) request.getAttribute("user"); %>
7.User is: <%= u.getName() %>
8.</body>
9.</html>
The separation of the view from the business logic depends on the attributes, as illustrated in
Listing 3-2 and Listing 3-3. JSP, in this manner, solved the problem of presentation cross-cutting
business logic in servlets. But as you can see in Listing 3-4, with the scriptlets (Java code) intermingled
in the presentation code (JSP), now the business logic cross-cuts the presentation concern.
Listing 3-4. Using a Scriptlet and an Expression in JSP
1.<% User u = new User(); %>
2.User is: <%= u.getName() %>
Line 1 : The scriptlet creates an instance of a class called User .
Line 2 : This outputs the user name using Expression.
What went wrong? Scriptlets and expressions brought Java code into JSP. Prior to JSP, the
presentation code cross-cut the business code. With JSP, the business code cross-cuts the
presentation code. So JSP, inadvertently, didn't actually solve anything but turned the problem of
cross-cutting the business and presentation logic upside down. The scriptlet and expression in
Listing 3-4 could indeed be easily replaced by JSP standard actions ( <useBean> ), as shown in Listing 3-5.
Listing 3-5. Using JSP Standard Action sand Expression Language
1.<jsp:useBean id="user" class="com.apress.User"/>
2.User is: ${user.name}
Listing 3-5 does the same thing that Listing 3-4 does but without using any Java code inside the
JSP page.
 
Search WWH ::




Custom Search