Java Server Pages

We will conclude this tour of server-side Java with a description of Java Server Pages (JSP), and an example JSP program. One way of understanding JSP is to say that JSP is ASP, without the restriction to Windows only. Another way of understanding it is to say that JSP programs are a variant on ordinary servlets, where some of the simple tasks are automated for you. In fact, the container implements JSPs by automatically translating them into the equivalent servlet which is then run in the usual way.

A JSP is a slick way of writing a servlet

An ordinary unchanging web page contains HTML (plus Javascript perhaps). A servlet is a compiled Java program. A JSP program is a hybrid of these two. It lets you mix individual Java statements in with your HTML code. The Java code will be executed on the server when the page is browsed, and it will provide some dynamic content to the page. You might do some calculations, or put something in a loop.

Your JSP Java code fragments automatically have the missing boilerplate code added, to make a complete servlet. This servlet is automatically compiled for you by the JSP container when the page is browsed. As with servlets, JSP code is compiled once and loaded into memory on first use. A developer will typically browse all the JSP pages when deploying a system, so that users don't see the “first time through” compilation time penalty.

JSP syntax

A large part of a servlet is “boilerplate,” meaning text that is the same in all servlets. The class declaration, the method signatures, and so on, are needed to make sure your code compiles, but they are the same in every servlet. JSP eliminates all that standard context. It is provided for you automatically. This can dramatically shorten the amount of code you need to write, and also makes it simple enough for non-programmers to produce JSP.

JSP uses special tags to separate the Java from the HTML. The JSP opening tag is “<%” and the closing tag is “%>”. The opening tag “<%” might be followed by another character such as “!” or “@” or “=”to further specialize its meaning. A very brief example here will show you best. These lines in a JSP file:

<b> current time is:
    <%=  new java.util.Date() %>
</b>

will produce a line of output like this when you browse the JSP:

current time is: Mon Feb 19 18:37:23 PST 2001

When you try this, it may take 30 seconds or so to appear because the container has to compile your JSP file the first time you browse it. If the automatic JSP compilation results in compiler error messages, these will be sent back to the client for display in the browser. When you browse the same HTML file a minute later without changing anything, the resulting page will show a different time, demonstrating that the JSP provides dynamic page content.

The piece that is new is the second line in the JSP file. It starts with the tag <%= which means “evaluate the Java expression that follows, convert it to String, and write it to the HTML output.” Other JSP tags have their own meaning, as shown in Table 26-7.

Table 26-7. JSP tags and meanings

Start of JSP tag

Meaning of JSP tag

<%

Everything up to the closing tag “%>” is Java code (blocks, statements, declarations, etc.).

<%=

Evaluates the Java expression that follows, converts it to String, and writes it to the HTML output. Ends with “%>”.

<%!

This is a Java declaration that is inserted into the body of the servlet, where it is available to all methods in the servlet.

<%@

This tag can be followed by one of several different strings, such as “method,” “import,” “implements,” “extends.” These are followed by a string that specifies the name for a Java method, package, interface, etc. This tag affects the generated Java, rather than the HTML it will output.

<jsp: useBean .../>

Has a list of attributes that specify a Java bean to invoke, and parameters to pass to it. Note that it ends with “/>”. This tag uses the XML conventions.

As a further example, the following JSP code echoes back all the headers that the page received. Note that there are some variables predefined within JSP for the coder's convenience. The response PrintWriter is “out,” the HttpServletRequest is “req,” and the HttpServletResponse is “resp.”

<html>
<body bgcolor="white">
<h1>The Echo JSP</h1>
<%   java.util.Enumeration eh = request.getHeaderNames();
     while (eh.hasMoreElements()) {
         String h = (String) eh.nextElement();
         out.print("<br> header: " + h );
         out.println(" value: " + request.getHeader(h));
     }
%>
</body>
</html>

Type this in to a file called echo.jsp and try running it using the pathnames shown in Table 26-8. Make sure Tomcat is running when you try this program, otherwise there is nothing to handle the request!

Table 26-8. Executing your JSP

Purpose

Value

Copy compiler library to Tomcat library. Then stop and restart Tomcat.

copy "c:program filesjavaj2sdk1.5.0lib ools.jar"
      %TOMCAT_HOME%commonlib

JSP source file

%TOMCAT_HOME%webappsjsp-examplesecho.jsp

JSP class file

Generated automatically for you

Browse this URL to run

http://127.0.0.1:8080/jsp-examples/echo.jsp

Since we aren't sending across any parameters, we don't need to invoke the JSP with a form, and we can just directly browse the JSP file itself. If you have connected up everything correctly, there will be a small pause while Tomcat automatically generates a servlet for the JSP and compiles it. Then you should see something like Figure 26-6 appear in your browser.

Figure 26-6. Results of browsing your JSP file

image

A browser doesn't know if there's a servlet, JSP, or static web page at the other end of the URL. These are the kind of headers that the client sends with any request. The headers will vary slightly on different systems and browsers. It is possible to shorten this JSP example by using the JSP tag that automatically does the output, as shown in this next JSP example.

Second example of JSP

Here's another example of JSP.

<html>
<body bgcolor="white">
<h1>The Echo 2 JSP</h1>
<%   java.util.Enumeration eh = request.getHeaderNames();
     while (eh.hasMoreElements()) {
         String h = (String) eh.nextElement();
%>
         <br> header: <%=  h  %>
               value: <%=  request.getHeader(h) %>
<%
     }
%>
</body>
</html>

Put this code in a file called echo2.jsp in directory called %TOMCAT_HOME%webappsjsp-examples. Browse URL http://127.0.0.1:8080/jsp-examples/echo2.jsp to run it. You'll see something like Figure 26-7.

Figure 26-7. echo2.jsp

image

Use Struts to avoid JSP tangles

JSP code can become messy if you are not careful, as this example shows. Tangled messes seem much more common than nicely separated code. People have put effort into additional servlet-based technologies such as WebMacro (sourceforge.net/projects/webmacro/), Enhydra (xmlc.enhydra.org), Velocity (jakarta.apache.org/velocity) and Jakarta Struts, to try to enforce the separation more cleanly.

Struts in particular is gaining great acceptance. Struts is a presentation framework for building servlet and JSP applications. It encourages application architecture that uses the Model-View-Controller separation. To look into Struts, start at http://jakarta.apache.org/struts.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.144.56