JSP Elements


A JSP is an HTML page with special tags embedded in it to allow the page to access the Web stream or enable it to access other Java objects.

There are different types of JSP tags depending on their use:

  • Expressions are of the form <%= expression %> . They are evaluated by the JSP compiler, and they output a java.lang.String . If the result of the expression is not already a string, the JSP compiler automatically converts it.

  • Declarations look like <%! code %> . They are normally used with expressions or scriptlets. A declaration creates a member variable in the servlet that is defined for the JSP.

  • Scriptlets are of the form <% code %> . They are used for regular Java code that is inserted into the JSP output stream.

Predefined Variables

The JSP specification defines a set of predefined variables that can be used in a JSP. These variables help you access the request, the session, and other variables in the JSP runtime. The variables are part of the servlet that is created from the JSP:

  • request ” This is the javax.servlet.http.HttpServletRequest that is associated with the page request. It provides all the methods available when you're using this class with servlets.

  • response ” This is the HttpServletResponse associated with the Web stream. It can be used to set HTTP status codes (for example, 404 - file not found ) and to specify the content type of the response. Of course, this variable has access to all the methods on the HttpServletResponse as well.

  • out ” A javax.servlet.jsp.JspWriter is used to put data into the output stream. It works similarly to servlets when the output to the ServletOutputStream is retrieved from the HttpServletResponse . This variable is usually used only in scriptlets because normal HTML or text can be output without directly using any of the JSP facilities.

  • session ” The javax.servlet.http.HttpSession object is associated with this session. As mentioned in Chapter 17, "Introduction to Servlets," an HttpSession is used to identify a user between invocations of a servlet. It can be used in the same way for a JSP. This is an easy way to have a stateful session with the client browser.

  • application ” The javax.servlet.ServletContext of the JSP. This is the same variable that can be obtained in a servlet by calling getServletConfig().getContext() . A ServletContext defines a set of methods that the servlet or JSP uses to communicate with the servlet container they are located in. For example, servlets have a common log file that can be accessed via this object. To use the log file, you would, in a JSP, write

     
     application.log( "Something didn't work" ); 

This statement writes the specified message to the servlet log file.

  • config ” The javax.servlet.ServletConfig for the JSP. It can be used to retrieve initialization parameters for the JSP in much the same way that initialization parameters are retrieved for a servlet.

  • pageContext ” A javax.servlet.jsp.PageContext . To an extent, a pageContext is a wrapper for all the other attributes. It provides access to most of the page attributes and provides a place to store shared data.

Expressions

Expressions are used to insert strings and other variables into the output of the JSP stream. A variable is converted to a string by the JSP engine if needed. Expressions allow dynamic information to be embedded into an HTML page by being interpreted with the HTML stream. For example, you can modify the Chapter 17 example so that it's a JSP. To do so, you write HTML code with embedded expressions that generate the same output as the servlet did, as shown in Listing 18.1.

Listing 18.1 HTML Code with Embedded Expressions
 <html> <head> <title>Hello!</title> </head> <body> <!--- get the remote host, very similar to the servlet example --> Welcome <%= request.getRemoteHost() %> <br> <!--- get the User-Agent - also similar to the servlet example --> Your browser id string is <%= request.getHeader( "User-Agent" ) %> </body> </html> 

In this case, the JSP engine does not need to coerce the result of the call to getRemoteHost() because it already is a string. However, you can now add code to display the content length by calling getContentLength() on the request. This code returns an integer that is simply the length in bytes of the content after the HTTP header (see Listing 18.2).

Listing 18.2 Displaying Information from the HttpServletRequest
 <html> <head> <title>Hello!</title> </head> <body> <!--- get the remote host, very similar to the servlet example --> Welcome <%= request.getRemoteHost() %> <br> <!--- display the Content-Length HTTP header element --> The Content-Length field is <%= request.getContentLength() %><br> <!--- get the User-Agent - also similar to the servlet example --> Your user agent string is <%= request.getHeader( "User-Agent" ) %> </body> </html> 

By automatically converting the result of getContentLength() to a string from an integer, the JSP engine further simplifies the task of writing a JSP page. The code does not require you to write something like this:

 
 The Content-Length field is <%= Integer.toString( request.getContentLength() ) %><br> 

Again, the goal is to minimize the amount of Java code that a JSP developer needs to write. Ultimately, all the output from the JSP page is a string that will be rendered by the browser like in Figure 18.1.

Figure 18.1. Output from the sample JSP.

graphics/18fig01.gif

Expressions can also be included in a JSP with XML syntax. The syntax in Listing 18.1 would then be changed to that shown in Listing 18.3.

Listing 18.3 Using JSP XML Expressions
 <html> <head> <title>Hello!</title> </head> <body> <!--- get the remote host, very similar to the servlet example --> Welcome <jsp:expression> request.getRemoteHost() </jsp:expression> <br> <!--- get the User-Agent - also similar to the servlet example --> Your user agent string is <jsp:expression> request.getHeader( "User-Agent" ) </jsp:expression> </body> </html> 

XML syntax improves the machine readability of the document and provides the flexibility of performing an XML transformation to programmatically change the page from one style to another, but can make it more difficult for human readability. However, the JSP engine treats both forms exactly the same, so it is up to you to determine the best form.

Declarations

A JSP declaration defines a variable to be used in a later scriptlet or expression. It has the form <%! declaration %> (see Listing 18.4).

Listing 18.4 Using JSP Declarations
 <html> <head> <title>Hello!</title> <body> <%! private String lastVisitor = null; %> <b>Hello <%= request.getRemoteHost() %></b><br> The last visitor to our site came from <%= lastVisitor %> <% lastVisitor = request.getRemoteHost(); %> </body> </html> 

In Listing 18.4, the string, lastVisitor , is defined by the declaration and then used later in the expression. The last line sets the lastVisitor variable to the current visitor's remote host.

It is important to understand that the JSP compiler translates declarations into member variables in the servlet. This means that multiple invocations of the same JSP use the same variable. Recall from Chapter 17 that the default behavior for servlets is for all requests to be serviced by the same servlet but through multiple threads. The same is true of JSP pages because they are servlets.

However, this means that the same caveats that apply to servlets and threads also apply to JavaServer Pages. Listing 18.4 does not use synchronization techniques to serialize access to the variable lastVisitor . If multiple simultaneous requests come in to this JSP from different remote machines, the variable could be overwritten with incorrect information.

One way to add thread safety to Listing 18.4 is to use standard Java synchronization techniques. Listing 18.5 shows using these techniques.

Listing 18.5 JSP Declaration Example Using Synchronization
 <html> <head> <title>Hello!</title> <body> <%! private String lastVisitor = null; %> <b>Hello <%= request.getRemoteHost() %></b><br> The last visitor to our site came from <% synchronized( this ) { %> <%= lastVisitor %> <% lastVisitor = request.getRemoteHost(); } %> </body> </html> 

As with JSP expressions, there is an XML syntax for declarations too:

 
 <jsp:declaration> // // an alternate way to declare the same variable as in // Listing 18.4 // private String lastVisitor; </jsp:declaration> 

After you restart the server and run the JSP, the lastVisitor variable is null; hence, you will see the output shown in Figure 18.2.

Figure 18.2. Output from the first run after a server restart.

graphics/18fig02.gif

After the JSP has been run once, the lastVisitor variable is set correctly, as shown in Figure 18.3.

Figure 18.3. Output from the second run after a server restart.

graphics/18fig03.gif

Scriptlets

The last line of the syntax shown in Listing 18.4

 
 <% lastVisitor = request.getRemoteHost() %> 

is slightly different because it represents a JSP scriptlet . A scriptlet allows the developer to embed any Java code within the JSP page. In this example, you reset the contents of the lastVisitor variable to be the current visitor so that on the next visit to the page the variable will display the correct output.

Scriptlets can be used anywhere within the JSP. They must be used for code that is not meant to be converted into a string and inserted into the output HTML stream. In Listing 18.4, when you reassigned the lastVisitor variable, no output needed to be generated; only code needed to be executed in this case.

Other Scripting Elements

When creating a JSP with scriptlets, you may need to import classes to use within the JSP. You do so with the page directive:

 
 <%@ page import="java.util.*, java.math.*" %> 

This directive generates an import statement in the resulting servlet. Page directives traditionally live at the top of the JSP.

Several other page attributes are commonly used:

  • buffer ” Specifies the buffering model for the predefined out variable. It can be either "none" to turn off all buffering of the JSPWriter or a size in kilobytes. For example, having buffer="16kb" after the page directive specifies a buffer size of 16 kilobytes. The suffix kb is required by the JSP 1.2 spec. The buffer attribute is used to control the size of the output buffer of the out variable. It defaults to 8 kilobytes. This means that every 8KB of output generated will be sent to the browser. It is more efficient to send data in larger packets, however, if your JSP page generates only small amounts of data; setting the size too high will result in wasted memory. Setting it to the string "none" results in no buffering.

    Tip

    You can use buffer for debugging when you want to see partial results from the JSP by setting the buffer to none . The results from the JSP will be sent to the browser as they are generated. This setting should not be used in a production environment as it will put a greater strain on network and CPU resources.


  • isThreadSafe ” Tells the JSP compiler whether the generated servlet should implement SingleThreadModel . The default is "false" . Set this attribute to "true" if your JSP needs to be single threaded. As mentioned in Chapter 17, servlets are, by default, shared within WebLogic Server. Because JSP pages are converted to servlets, they are shared also. If your JSP page accesses a resource that requires serial access, setting this attribute to "false" tells the servlet container that only one thread at a time should access this JSP page. However, the same caveats exist for JSP pages as for servlets, namely that the servlet container is allowed to create multiple instances of the servlet to service requests. Each instance will have only one thread using it at a time, but multiple instances may exist at the same time. Listing 18.5 could use this technique as an alternative to synchronize access to the JSP.

  • info ” Contains an arbitrary string that can be retrieved by calling getServletInfo() within the JSP page. This variable can be used to provide information about the JSP page to the WebLogic console. Commonly, version information is stored in this variable.

  • contentType ” Specifies the MIME type of the resulting page. This value can also be set by calling response.setContentType() from within the JSP. It can be used to set the content type to something besides "text/html" . For example, if your JSP page returns only textual information, you can set the contentType to "text/plain" .

  • pageEncoding ” Defines the character encoding for the JSP. The default value is "ISO-8859-1" , but you should set it to the character encoding that you will use in your pages. This value can also be set by calling response.setLocale() in your JSP. This attribute is commonly used to specify an alternate character encoding for the page. If you return characters in the UTF8 character set, you can include pageEncoding="utf8" in your JSP page.

Another directive is include , which allows you to include another file within your JSP. There are two types of include directives. The first uses syntax similar to the page directive. It looks like this:

 
 <%@ include file="header.html" %> 

This directive tells the JSP compiler to include the entire contents of the header.html line in the JSP. The JSP compiler does not compile the JSP until it has included all files specified with the include directives. After the compiler includes all the files, it translates the JSP.

The other include directive uses a different type of syntax, similar to the XML syntax you have seen already. It has this form:

 
 <jsp:include page="header.txt" /> 

This directive includes the header.txt file, but only at runtime. The JSP compiler does not parse or otherwise interact with this file. The entire contents of the file are included in the output stream for the JSP without being interpreted at all on the Web server.

The last directive is taglib . We will cover tag libraries later in this chapter.



BEA WebLogic Platform 7
BEA WebLogic Platform 7
ISBN: 0789727129
EAN: 2147483647
Year: 2003
Pages: 360

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net