Servlets and JSP


As discussed in Chapter 4, "HTTP Protocol: Web Application Communications and Control," the HTTP protocol consists of a request being passed to a Web server, processed , and data returned in a stateless transaction. By using techniques such as session cookies, state can be maintained even though the HTTP protocol itself is stateless.

Servlets are the basic computational unit that a Java-based Web server uses to handle requests. Whereas a non-Java Web server such as Apache might use an external CGI program written in Perl or C, a Java-based Web server such as Tomcat uses Java classes that have been made available somewhere in the classpath to service incoming requests .

In a pure servlet implementation, the Web server has been told via a configuration file to associate certain URLs with servlets rather than with physical Web pages. When a request comes in that matches one of these URLs, the request is handed off to the appropriate method of the class (depending on whether the operation is a GET , POST , and so on), which is responsible for returning the content of the page.

Listing 5.1 shows a sample servlet. All HTTP-based servlets extend the HttpServlet class and should provide class-specific methods for the types of operations they're prepared to handle.

Listing 5.1 BaseBallStatServlet.java
 import javax.servlet.*; import javax.servlet.http.*; public class BaseBallStatServlet extends HttpServlet {     protected void doGet(HttpServletRequest req, HttpServletResponse resp)        throws java.io.IOException {        resp.setContentType("text/html");        java.io.PrintWriter html = resp.getWriter();        String player = (String) req.getParameter("player");        html.println("<HTML><HEAD><TITLE>MLB Player Stats</TITLE></HEAD>");        html.println("<BODY>");        if ((player == null)  (player.length() == 0)) {            html.println("<H1>No Player Requested</H1>");        } else {            if (player.equals("Derek Lowe")) {               html.println("<H1>Derek Lowe has an ERA of 1.76</H1>");            } else {               html.println("<H1>" + player + " has an ERA of 5.23</H1>");            }         }         html.println("</BODY></HTML>");     } } 

The main weakness of pure servlet programming is readily apparent from this example. Because all the content, even basic HTML formatting, must come from the servlet, you end up with a lot of simple print statements in the servlet whose only purpose is to get this content back to the client. In addition, even simple HTML formatting changes must be made in the Java source itself, meaning that non-Java staff can't work on the Web site design.

The Power of JSP

As an answer to these weaknesses, JavaServer Pages was developed. JSP lets the developer leverage all the power of Java that was present in servlets, but also create pages that look something like HTML.

A common mistake when first approaching JSP is to think of it as HTML with Java embedded inside of it. Although a JSP might seem to behave this way on the surface, it's really a Java servlet with HTML inside. To understand why this is the case, you need to look at how JSP services a request. For example, Listing 5.2 shows a very simple JSP page.

Listing 5.2 printloop.jsp
 <% for (int i = 1; i < 10; i++) { %> This is loop #<%= i %><BR> <% } %> 

When a browser requests printloop.jsp from the JSP server, the source page is passed through a converter (in Tomcat, this converter is called Jasper ), which turns the JSP into a Java source file that defines a single class, whose name is based on the name of the source file.

For example, Tomcat turns printloop.jsp into a file called printloop$jsp.java , whose contents are shown in Listing 5.3.

Listing 5.3 printloop$jsp.java
 package org.apache.jsp; import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.jsp.*; import org.apache.jasper.runtime.*; public class printloop$jsp extends HttpJspBase {     static {     }     public printloop$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;charset=ISO-8859-1");             pageContext = _jspxFactory.getPageContext(this, request, response,                     "", true, 8192, true);             application = pageContext.getServletContext();             config = pageContext.getServletConfig();             session = pageContext.getSession();             out = pageContext.getOut();             // begin [file="/printloop.jsp";from=(0,2);to=(2,0)]                 for (int i = 1; i < 10; i++) {             // end             // HTML // begin [file="/printloop.jsp";from=(2,2);to=(3,14)]                 out.write("\r\nThis is loop #");             // end             // begin [file="/printloop.jsp";from=(3,17);to=(3,20)]                 out.print( i );             // end             // HTML // begin [file="/printloop.jsp";from=(3,22);to=(4,0)]                 out.write("<BR>\r\n");             // end             // begin [file="/printloop.jsp";from=(4,2);to=(6,0)]                 }             // end             // HTML // begin [file="/printloop.jsp";from=(6,2);to=(7,0)]                 out.write("\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);        }    } } 

As you can see, all the HTML has been embedded inside calls to out.write , whereas the Java code is inserted untouched in the method. The method itself has access to the HttpServletRequest and HttpServletResponse objects, which are passed in to the method as the arguments request and response . This means that the Java code on the JSP page can gain access to these values by using the variables .

After the JSP file has been converted into Java, it's compiled and the jspService method of the class is called with the request and response objects. The class services the request exactly as a servlet would, and the resulting content is sent back to the client. The results from requesting this JSP page are shown in Listing 5.4.

Listing 5.4 Results from Requesting printloop.jsp
 This is loop #1 This is loop #2 This is loop #3 This is loop #4 This is loop #5 This is loop #6 This is loop #7 This is loop #8 This is loop #9 

In addition to placing raw Java on the JSP page, there are also a number of tags that JSP makes available to make developing applications easier. You've already seen two of those tags: the <% %> tag, which escapes out to Java, and the <%= %> tag, which inserts a Java value into HTML.



Struts Kick Start
Struts Kick Start
ISBN: 0672324725
EAN: 2147483647
Year: 2002
Pages: 177

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