Deploying and Running JSP

   

Java™ 2 Primer Plus
By Steven Haines, Steve Potts

Table of Contents
Chapter 22.  JavaServer Pages (JSP)


The cheapest way to deploy and run JSPs on your computer is to download the Apache Tomcat Web server.

Jakarta Tomcat is available at no cost from the Apache Web site at http://www.apache.org/.

The link for Tomcat 4.0.4 is http://jakarta.apache.org/builds/jakarta-tomcat-4.0/release/v4.0.4/bin/.

Choose a release that is right for your needs. If you are running Java 1.4, the following self-extracting .exe file will be correct for you.

 jakarta-tomcat-4.0.4-LE-jdk14.exe 

Caution

graphics/01icon17.gif

As new versions of Tomcat are released, the links that lead to them will differ from those shown previously. In these cases, you will need to go to the http://jakarta.apache.org/ Web site and navigate to the newest release.


Chapter 21, "Servlets," provides detailed instructions on how to install and verify Tomcat on your computer.

It is easy to deploy JSP on Tomcat. All you have to do is create a folder of your own under the …\webapps\examples\jsp\ directory. For this chapter, we have created a directory called jpp. Whenever we write a servlet, we can place it in this directory and call it by using the following URI:

 http://localhost:1776/examples/jsp/jpp/xyz.jsp 

In this case, xyz.jsp is the name of the file that contains the JSP code. Listing 22.1 shows a simple JSP page that we can use to prove to ourselves that JSPs placed in this new directory will run on the server.

Listing 22.1 The requestExamination.jsp Page
 <html>  <!--   The requestExamination.jsp File.  This JSP uses expressions to do    all of the Java work. This is an HTML comment  -->  <%--   The requestExamination.jsp File.  This JSP uses expressions to do    all of the Java work. This is a JSP comment  --@>  <body bgcolor="white">  <h1> Request Examination </h1>  <font size="4">  JSP Request Method: <%= request.getMethod() %>  <br>  Server: <%= request.getServerName() %>  <br>  port: <%= request.getServerPort() %>  <br>  address: <%= request.getRemoteAddr() %>  <br>  host: <%= request.getRemoteHost() %>  <br>  Locale: <%= request.getLocale() %>  <hr>  Request URI: <%= request.getRequestURI() %>  <br>  Request Protocol: <%= request.getProtocol() %>  <br>  Servlet path: <%= request.getServletPath() %>  <br>  Browser version <%= request.getHeader("User-Agent") %>  <hr>  </font>  </body>  </html> 

We see the usual HTML tags in this code along with some of the new JSP syntax that you have been introduced to in this chapter. The first things we notice are the JSP comment and the HTML comment. The first comment will show up in the result, but the second one is only for the JSP programmer's eyes.

 <!--   The requestExamination.jsp File.  This JSP uses expressions to do    all of the Java work. This is an HTML comment  -->  <%--   The requestExamination.jsp File.  This JSP uses expressions to do    all of the Java work. This is a JSP comment  --> 

The next nugget of JSP that we see is an expression. This expression is using the request object that we mentioned previously as always being available in JSP. The getMethod() method returns whether the request was a Get or a Post.

 JSP Request Method: <%= request.getMethod() %> 

The server name for our example is localhost. The localhost machine name always means this machine, regardless of the machine's real ServerName.

 Server: <%= request.getServerName() %> 

The port is 1776 because the test machine for this chapter chooses to run Tomcat on that port to avoid conflicts with other products that were using the default port 8080.

 port: <%= request.getServerPort() %> 

The getRemoteAddr() method returns the IP address of the server running the JSP. 127.0.0.1 is a magic IP address that always means "this machine," regardless of the true IP address of the machine.

 address: <%= request.getRemoteAddr() %> 

The getRemoteHost() method returns the name of the machine running the browser that called the JSP page. In this example's case, the same machine is running both the browser and the server.

 host: <%= request.getRemoteHost() %> 

The getLocale() is used to internationalize the JSP. This value is set when you install Java on your computer. It is initially based on settings in your operating system that the installation program reads. It has two parts; the first is the language, and the second is the locality. This machine returns en_US, indicating English as spoken in the United States instead of English as spoken in England.

 Locale: <%= request.getLocale() %> 

The getRequestURI() returns the relative path entered into the address line on the browser. It is the directory location in relation to the Web server's root.

 Request URI: <%= request.getRequestURI() %> 

The getProtocol() method will return the version of HTTP that was submitted with the request.

 Request Protocol: <%= request.getProtocol() %> 

The servlet path is the path relative to the name of the application, which in our case is a directory called <install-dir>\webapps\examples.

 Servlet path: <%= request.getServletPath() %> 

The getHeader("User-Agent") method returns the precise name and version number of the browser that was used.

 Browser version <%= request.getHeader("User-Agent") %> 

To run this example, type the following in the address line of your browser:

 http://localhost:1776/examples/jsp/jpp/requestExamination.jsp 

This will result in the display of the Web page shown in Figure 22.2.

Figure 22.2. The result of running this JSP program is a formatted HTML page.

graphics/22fig02.gif

We can view the HTML source that was generated by selecting Page Source from the View menu when running Netscape Navigator, or by selecting Source from the View menu when running Microsoft Internet Explorer. The generated HTML for requestExamination.jsp is shown in Listing 22.2.

Listing 22.2 The requestExamination.jsp-Generated HTML
 <html>  <!--   The requestExamination.jsp File.  This JSP uses expressions to do    all of the Java work. This is an HTML comment  -->   <body bgcolor="white">  <h1> Request Examination </h1>  <font size="4">  JSP Request Method: GET  <br>  Server: localhost  <br>  port: 1776  <br>  address: 127.0.0.1  <br>  host: localhost  <br>  Locale: en_US  <hr>  Request URI: /examples/jsp/jpp/requestExamination.jsp  <br>  Request Protocol: HTTP/1.1  <br>  Servlet path: /jsp/jpp/requestExamination.jsp  <br>  Browser version Mozilla/5.0 (Windows; U;   Windows NT 5.1; en-US; rv:0.9.4.1) Gecko/20020508 Netscape6/6.2.3  <hr>  </font>  </body>  </html> 

Notice that no <% characters are left in the code by the time that it arrives in the server. You can think of the <% as the remove me command. Every bit of JSP that falls inside of this delimiter is to be resolved and removed. This includes the Java comment delimiters /**, */, and //.

The JSP is translated into an ordinary servlet before being run. You might notice an unusual delay, caused by the translation step, the first time you run a large servlet. Each JSP is translated only once and will be run without retranslation until it is modified. Fortunately, in Tomcat 4.x, this retranslation is automatic, saving the programmer much time and aggravation. Listing 22.3 shows the servlet that was created for the requestExamination.jsp file.

Listing 22.3 The requestExamination$jsp.java Servlet
 package org.apache.jsp;   import javax.servlet.*;  import javax.servlet.http.*;  import javax.servlet.jsp.*;  import org.apache.jasper.runtime.*;   public class requestExamination$jsp extends HttpJspBase  {     static     {     }     public requestExamination$jsp( )     {     }     private static boolean _jspx_inited = false;     public final void _jspx_init()     throws org.apache.jasper.runtime.JspException     {     }     public void _jspService(HttpServletRequest request,                           HttpServletResponse  response)             throws java.io.IOException, ServletException     {        JspFactory _jspxFactory = null;        PageContext pageContext = null;        HttpSession session = null;        ServletContext application = null;        ServletConfig config = null;        JspWriter out = null;        Object page = this;        String  _value = null;        try        {           if (_jspx_inited == false)           {              synchronized (this)              {                 if (_jspx_inited == false)                  {                    _jspx_init();                    _jspx_inited = true;                 }              }           }           _jspxFactory = JspFactory.getDefaultFactory();           response.setContentType("text/html;ISO-8859-1");           pageContext = _jspxFactory.getPageContext(this,           request, response,        "", true, 8192, true);           application = pageContext.getServletContext();           config = pageContext.getServletConfig();           session = pageContext.getSession();           out = pageContext.getOut();            // HTML // begin [file="/jsp/jpp/requestExamination.jsp";           //from=(0,0);to=(6,0)]           out.write("<html>\r\n\r\n<! \r\n  The requestExamination.jsp              File.  This JSP uses expressions to do\r\n  all of the              Java work. This is an HTML comment\r\n >\r\n");           // end           // HTML // begin [file="/jsp/jpp/requestExamination.jsp";                  //from=(9,4);to=(14,20)]           out.write("\r\n\r\n<body bgcolor=\"white\">\r\n<h1>                     Request Examination </h1>\r\n<font size=\"4\">\r\nJSP                     Request Method: ");           // end           // begin [file="/jsp/jpp/requestExamination.jsp";                     //from=(14,23);to=(14,44)]           out.print( request.getMethod() );           // end           // HTML // begin [file="/jsp/jpp/requestExamination.jsp";                     //from=(14,46);to=(16,8)]           out.write("\r\n<br>\r\nServer: ");           // end           // begin [file="/jsp/jpp/requestExamination.jsp";           //from=(16,11);to=(16,36)]           out.print( request.getServerName() );           // end           // HTML // begin [file="/jsp/jpp/requestExamination.jsp";           //from=(16,38);to=(18,6)]           out.write("\r\n<br>\r\nport: ");           // end           // begin [file="/jsp/jpp/requestExamination.jsp";           //from=(18,9);to=(18,34)]           out.print( request.getServerPort() );           // end           // HTML // begin [file="/jsp/jpp/requestExamination.jsp";           //from=(18,36);to=(20,9)]           out.write("\r\n<br>\r\naddress: ");           // end           // begin [file="/jsp/jpp/requestExamination.jsp";           //from=(20,12);to=(20,37)]           out.print( request.getRemoteAddr() );           // end           // HTML // begin [file="/jsp/jpp/requestExamination.jsp";           //from=(20,39);to=(22,6)]           out.write("\r\n<br>\r\nhost: ");           // end           // begin [file="/jsp/jpp/requestExamination.jsp";           //from=(22,9);to=(22,34)]            out.print( request.getRemoteHost() );            // end           // HTML // begin [file="/jsp/jpp/requestExamination.jsp";           //from=(22,36);to=(24,8)]           out.write("\r\n<br>\r\nLocale: ");           // end           // begin [file="/jsp/jpp/requestExamination.jsp";           //from=(24,11);to=(24,32)]           out.print( request.getLocale() );           // end           // HTML // begin [file="/jsp/jpp/requestExamination.jsp";           //from=(24,34);to=(26,13)]           out.write("\r\n<hr>\r\nRequest URI: ");           // end           // begin [file="/jsp/jpp/requestExamination.jsp";           //from=(26,16);to=(26,41)]           out.print( request.getRequestURI() );           // end           // HTML // begin [file="/jsp/jpp/requestExamination.jsp";           //from=(26,43);to=(28,18)]           out.write("\r\n<br>\r\nRequest Protocol: ");           // end           // begin [file="/jsp/jpp/requestExamination.jsp";           //from=(28,21);to=(28,44)]           out.print( request.getProtocol() );           // end           // HTML // begin [file="/jsp/jpp/requestExamination.jsp";           //from=(28,46);to=(30,14)]           out.write("\r\n<br>\r\nServlet path: ");           // end           // begin [file="/jsp/jpp/requestExamination.jsp";           //from=(30,17);to=(30,43)]           out.print( request.getServletPath() );           // end           // HTML // begin [file="/jsp/jpp/requestExamination.jsp";           //from=(30,45);to=(32,16)]           out.write("\r\n<br>\r\nBrowser version ");           // end           // begin [file="/jsp/jpp/requestExamination.jsp";           //from=(32,19);to=(32,52)]           out.print( request.getHeader("User-Agent") );           // end           // HTML // begin [file="/jsp/jpp/requestExamination.jsp";           //from=(32,54);to=(37,0)]           out.write("\r\n<hr>\r\n</font>\r\n</body>\r\n</html>\r\n");           // end         } catch (Throwable t)        {           if (out != null && out.getBufferSize() != 0)              out.clearBuffer();           if (pageContext != null) pageContext.handlePageException(t);        } finally        {           if (_jspxFactory != null)              _jspxFactory.releasePageContext(pageContext);        }     }  } 

This listing is a bit long, but understanding it is critical if you are going to be a JSP programmer instead of a JSP page developer. This servlet is placed in a package and in a special directory that differs from Web server to Web server. On Tomcat 4.x, it was found in the directory …\ work\Standalone\localhost\examples\jsp\jpp. The package the class file is moved to be run is package org.apache.jsp;.

This servlet imports the usual group of servlet packages along with the org.apache.jasper.runtime package. Jasper is the name of the Apache JSP engine.

 import javax.servlet.*;  import javax.servlet.http.*;  import javax.servlet.jsp.*;  import org.apache.jasper.runtime.*; 

Notice that the JSP file has been renamed during the translation process.

 public class requestExamination$jsp extends HttpJspBase 

The work of the servlet is done in the _jspService() method, which looks a lot like the service method from the GenericServlet class.

 public void _jspService(HttpServletRequest request,                         HttpServletResponse  response)          throws java.io.IOException, ServletException  { 

Apache uses its own JspFactory object to obtain contexts and such. These objects are the intrinsic objects from earlier in the chapter.

 JspFactory _jspxFactory = null;  PageContext pageContext = null;  HttpSession session = null;  ServletContext application = null;  ServletConfig config = null;  JspWriter out = null;  Object page = this; 

Here the servlet obtains the values to all the intrinsic objects that you can access in the JSP page.

_jspxFactory = JspFactory.getDefaultFactory();

response.setContentType("text/html;ISO-8859-1");

pageContext = _jspxFactory.getPageContext(this,

request, response, "", true, 8192, true);

application = pageContext.getServletContext();

config = pageContext.getServletConfig();

session = pageContext.getSession();

out = pageContext.getOut();

Finally, the generated HTML is written to out. Notice that the origin of each statement is listed in the comments. This is to aid debugging, especially when JSP gets large and complex. The coordinates are in units of characters that are counted with 0,0 at the origin, with the x-coordinate increasing downward and the y-coordinate increasing from left to right.

 // HTML // begin [file="/jsp/jpp/requestExamination.jsp";  //from=(0,0);to=(6,0)]  out.write("<html>\r\n\r\n<! \r\n  The requestExamination.jsp      File. This JSP uses expressions to do\r\n  all of      the Java work. This is an HTML comment\r\n >\r\n");  // end 

Static HTML is just written out in a formatted fashion.

 // HTML // begin [file="/jsp/jpp/requestExamination.jsp";         //from=(9,4);to=(14,20)]  out.write("\r\n\r\n<body bgcolor=\"white\">\r\n<h1>            Request Examination </h1>\r\n<font size=\"4\">\r\nJSP            Request Method: "); 

The dynamic values are extracted or calculated using normal servlet logic. Here a call to an HttpServletRequest object's getMethod() method is employed.

 // begin [file="/jsp/jpp/requestExamination.jsp";            //from=(14,23);to=(14,44)]  out.print( request.getMethod() );  // end 

In the end, the servlet is run and gets the illusion that the JSP is really a program that can be run directly. This mindset is productive as long as everything works. When bugs arise, peel back the cover and look at the intermediate servlet to find the problem.


       
    Top
     



    Java 2 Primer Plus
    Java 2 Primer Plus
    ISBN: 0672324156
    EAN: 2147483647
    Year: 2001
    Pages: 332

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