513-0 ch01.qxd 9/30/05 4:08 PM Page 7 CHAPTER

513-0 ch01.qxd 9/30/05 4:08 PM Page 9 CHAPTER 1 THE ANATOMY OF A JAVASERVER PAGE and technologies. Although architecture and design can seem a little daunting at first (especially when you re new to the technology and all you really want to do is cut code), with a little effort you ll soon start to understand the benefits that are to be gained by using tried and tested patterns. As you re no doubt aware, the Java EE 5 presentation tier consists of several components for example, servlets, JSP pages, tag libraries, and JavaBeans which may be used to create a presentation layer for a web application. All these components have their relative strengths and weaknesses, particularly when used in different combinations. Good design, therefore, is concerned not only with selecting the correct component for a task but also with ensuring that the component is used in the correct manner. In recent times, two popular web-application architectures have been repeatedly used for web-application design, and there are strengths and weaknesses to consider with both. Let s discuss the simpler of these two architectures first. Model 1 Architecture The simplicity of the Model 1 architecture is that each JSP page is entrusted to deal with its request entirely by itself, thereby generating a response and sending it back to the client, and for this reason it s often known as page-centric. Usually such JSP pages will use some form of model to represent the business logic of the application. JavaBeans components are often used to model business logic. The JavaBean neatly encapsulates the business logic for reusability and at the same time keeps the amount of processing logic in the page to a minimum. Figure 1-3 shows a JSP page entrusted with handling a client request and building an appropriate response all by itself. It is also using a JavaBean to encapsulate business logic. Browser JSP/Servlet Container JSP Page JavaBean Data Tier Data Data Request Response Figure 1-3. In a Model 1 architecture, all the application processing occurs in a single tier of the application. Each JSP page has the potential to contain a lot of processing logic. However, as long as the application is relatively small with few pages, the Model 1 architecture is a good choice because it s quick and simple to put together. However, such a page-centric architecture can begin to introduce problems when used with larger, more complex applications. Some of the more common problems are outlined here.
Note: If you are looking for good and high quality web space to host and run your jsp application check Lunarwebhost jsp web hosting services

513-0 ch01.qxd 9/30/05 4:08 PM Page 7 CHAPTER

513-0 ch01.qxd 9/30/05 4:08 PM Page 8 CHAPTER 1 THE ANATOMY OF A JAVASERVER PAGE (commonly known as a taglib) is simply a collection of one or more custom tags that are generally related in some way. For example, as we said earlier, the JSP 2.0 specification introduced a standard tag library known as the JSTL. The JSP 2.1 specification refines the JSTL. The JSTL s core library contains tags that solve many of the common and recurring problems encountered when building JSP-based web applications. After the tags are bundled into a tag library, that tag library can be reused across the following: A single page The pages of a web application Different web applications The ability to easily reuse custom tags across more than a single page illustrates the true potential of tag libraries when building web applications. This is something that you ll be seeing when you examine the best practices for designing and building custom tags in later chapters. Readability Another important best practice is that of readability. Embedding too much Java code in the page can easily lead to pages that are unreadable as content (typically HTML) is mixed with JSP tags and Java code wrapped up as scriptlets. In addition to the confusion caused by the various syntaxes that each of these languages uses, one clear problem with embedding Java code inside JSP pages is that it s hard to correctly indent your source code. Writing and indenting code is trivial when dealing with regular class files, but trying to correctly indent Java code that is mixed with HTML and JSP elements is a different story. Wrapping up reusable functionality as custom tags or JavaBeans components removes this code from the page, therefore making it cleaner, shorter, and more readable. Also, choosing appropriate names for your custom tags can make a page more readable by page designers those who are responsible for the look and feel of a page rather than the mechanics of how it works. This, as you ll see when we talk about some of the best practices associated with custom tags, is very important and often overlooked. Maintainability Having a system that promotes reusability and readability is great, but what does that mean in the real world? The maintainability of an application is how well the system can be modified and fixed during its lifetime, which for a given application is typically hard to measure. However, in looking at any system, several signs help us to identify whether that system will be easy or difficult to maintain. In reality, this is dictated by reuse and the need to ensure that the code is as readable as possible the two goals that custom tags can help you achieve. JavaServer Pages Application Architecture All the factors mentioned in this chapter reusability, readability, maintainability are improved by a good design or architecture; therefore, it s worth ensuring that sufficient time is taken early in your project life cycle to select the architecture that best suits your environment
Note: If you are looking for good and high quality web space to host and run your jsp application check Lunarwebhost jsp web hosting services

513-0 ch01.qxd 9/30/05 4:08 PM Page 7 CHAPTER

513-0 ch01.qxd 9/30/05 4:08 PM Page 7 CHAPTER 1 THE ANATOMY OF A JAVASERVER PAGE After this method has been called, the servlet can no longer serve any requests. Like the destroy() method, jspDestroy()is an excellent place to release or close application-level resources when the servlet is shutting down. To do this, simply provide an implementation of this method via a JSP method declaration. For example, to release the application resource you opened inside the jspInit() method, you would use the following: <%! public void jspDestroy() { try { appVar.release(); } catch (Exception e){} appVar = null; } %> JavaServer Pages Best Practices One of the design goals of this book, apart from the obvious introduction to the concepts and mechanics of JSP technology, is to teach right from the start the best practices learned from experience. Of all the best practices that have been established around JSP, one of the most important suggests that there should be as little Java code as possible embedded inside a JSP page. Experience has shown us that three key factors benefit from this practice: Reusability Readability Maintainability Let s look at each of these and see how their use can benefit your JSP applications. Reusability A common goal associated with using any programming language is that of reuse, whether it involves structuring code inside modules, classes, or some other language-specific construct. Reusing code leads to increased maintainability and productivity, and higher quality because changes to such common functionality need to be made in only a single place. Although the concept of building web-based applications is relatively new, this goal applies equally to building Java-based web applications with JSP. Web-based applications are typically built up around the pages or screens from which the application is comprised. For example, in an online bookstore, you might build a welcome page first, followed by a page that shows a list of books, and then a page that displays the information about a single book. With the ability to embed Java code inside JSP pages, there can be a tendency to simply reuse code on a source-code level by copying and pasting it between JSP pages. Although this does achieve some reuse, it brings with it a dramatic decrease in the maintainability of such code as changes and bugs slowly creep in and around the system. Ideally, you re looking for reusability at the class or component level. Throughout this book, you ll see many techniques for aiding reusability provided by the JSP specification such as JavaBeans components, custom tags, and tag libraries. A tag library
Note: If you are looking for good and high quality web space to host and run your jsp application check Lunarwebhost jsp web hosting services

513-0 ch01.qxd 9/30/05 4:08 PM Page 4 CHAPTER

513-0 ch01.qxd 9/30/05 4:08 PM Page 6 CHAPTER 1 THE ANATOMY OF A JAVASERVER PAGE Caution A JSP page that sets the page attribute isThreadSafe to false may contain deprecated code in the implementation class. In addition, it does not guarantee thread safety in all cases. Do not rely on isThreadSafe=”false” to protect your JSP page from concurrency problems. After the servlet class is loaded, the container initializes the servlet instance with a call to an initialization method. For a JSP implementation servlet, that method is the jspInit() method. As the name suggests, this method is used for initializing the implementation servlet in an identical manner to the standard servlet init() method, which is used to initialize a servlet. The behavior of both methods can be regarded as identical, and each is called exactly once. Although jspInit() is automatically generated during the translation phase, it s possible to override this method in the JSP page by using a declaration. The method can be used for initializing application-level variables or resources, for example: <%! AppVar appvar = null; %> <%! public void jspInit() { try { appvar = initAppVar(...); } catch (Exception e){ //handle exception } } %> Execution After the web container has loaded and initialized the implementation servlet, the initial request can be serviced. To service the request, the web container calls the _jspService() method of the implementation servlet. As we mentioned, each request to the JSP page results in a separately threaded call to the _jspService() method. The _jspService() method provides all the functionality for handling a request and returning a response to the client. All the scriptlets and expressions end up inside this method, in the order in which they were declared inside the JSP page. Notice that JSP declarations and directives aren t included inside this method because they apply to the entire page, not just to a single request, and therefore exist outside the method. The _jspService()method may not be overridden in the JSP page. Finalization The last phase in the life cycle is the finalization phase. As with the previous two phases, there is a corresponding method in the implementation servlet for this phase. The method is named jspDestroy(). Like the destroy() method found in a standard servlet, this method is called by the servlet container when the page implementation servlet is about to be destroyed. This destruction could be for various reasons, such as the server being low on memory and wanting to free up some resources, but the most common reason is that the servlet container is shutting down or being restarted.
Note: If you are looking for good and high quality web space to host and run your jsp application check Lunarwebhost jsp web hosting services

513-0 ch01.qxd 9/30/05 4:08 PM Page 4 CHAPTER

513-0 ch01.qxd 9/30/05 4:08 PM Page 5 CHAPTER 1 THE ANATOMY OF A JAVASERVER PAGE As you can see in Figure 1-2, the JSP servlet container decides whether the JSP page has been translated before. If not, the JSP container starts the translation phase to generate the JSP page implementation servlet, which is then compiled, loaded and initialized, and used to service the request. If the JSP container detects that a JSP page has already been translated and hasn t subsequently changed, the request is simply serviced by the implementation servlet that already exists inside the container. The life cycle of a JSP page can be split into four phases: translation, initialization, execution, and finalization. Translation The first stage in the life cycle of a JSP page is known as the translation phase. When a request is first made for a JSP page (assuming it hasn t been precompiled), the JSP engine will examine the JSP file to check that it s correctly formed and that the JSP syntax is correct. If the syntax check is successful, the JSP engine will translate the JSP page into its page implementation class, which takes the form of a standard Java servlet. After the page s implementation servlet has been created, it will be compiled into a class file by the JSP engine and will be ready for use. Each time a container receives a request, it first checks whether the JSP file has changed since it was last translated. If it has, it s retranslated so that the response is always generated by the most up-to-date implementation of the JSP file. Initialization After the translation phase has been completed, the JSP engine will need to load the generated class file and create an instance of the servlet in order to continue processing the initial request. Therefore, the JSP engine works very closely with the servlet container and the JSP page implementation servlet and will typically load a single instance of the servlet into memory. This single instance will be used to service all requests for the JSP page. In a real-world web application, those requests will most likely happen concurrently, so your JSP page must be multithreaded. Prior to the Servlet 2.5 specification, the Java Servlet specification provided two separate threading models that could be used for a servlet. The models determine whether single or multiple instances of a servlet can exist. The default threading model for any servlet is the multithreaded one that requires no additional work for the developer. In this model, the container creates only a single instance of the servlet class and sends multiple requests to the instance concurrently. To select the single-threaded model for your JSP, you must set an attribute of the page directive called isThreadSafe to falseto serialize all requests to the implementation servlet behind the JSP: <%@ page isThreadSafe="false" %> In the past, containers would support this feature by creating an implementation page that implements the SingleThreadModel interface. When the implementation page implements this interface, the JSP container creates multiple instances of the implementation class; each instance handles a single request at any given time. However, note that the JSP 2.1 specification advises developers against using isThreadSafe=”false” because the Servlet 2.5 specification has deprecated SingleThreadModel.
Note: If you are looking for good and high quality web space to host and run your jsp application check Lunarwebhost jsp web hosting services

513-0 ch01.qxd 9/30/05 4:08 PM Page 4 CHAPTER

513-0 ch01.qxd 9/30/05 4:08 PM Page 4 CHAPTER 1 THE ANATOMY OF A JAVASERVER PAGE A request for a JSP page is handled initially by the web server, which then delegates the request to the JSP container. The JSP engine will translate the contents of the JSP into its implementation servlet, which the container then uses to service the request. Usually a JSP container will check whether the contents of a JSP page have changed before deciding if it needs to retranslate the page in response to a request. This feature can make on-the-spot changes to JSP pages easy because the next request will automatically cause a retranslation and the most up-to-date content will be returned. Compare this with a purely servlet-based approach, which would require the servlet container to be shut down in order to have the necessary changes made, such as recompilation, testing, and finally, a restart! Let s take a closer look at the process of taking a plain JSP text file and turning it into a dynamic web component; this process is also known as the JSP life cycle. The JSP Life Cycle As you ve just seen, JSP pages don t directly return content to the client browser themselves. Instead, they rely on some initial server-side processing that converts the JSP page into the JSP page implementation class (see Figure 1-2), which handles all requests made of the JSP. New or Changed HTTP Request JSP Servlet (Source) Servlet (Class)Servlet Instance HTTP Response No Yes locate JSP JSP translation JSP compilation Servlet loaded and initialized Web Container Figure 1-2. Before processing a request, the container determines whether the JSP source is new or has changed. If so, the container translates and compiles the JSP page into a servlet class, or page implementation class, before passing the request to the servlet for processing.
Note: If you are looking for good and high quality web space to host and run your jsp application check Lunarwebhost jsp web hosting services

The Anatomy of a JavaServer Page CHAPTER 1

513-0 ch01.qxd 9/30/05 4:08 PM Page 3 CHAPTER 1 THE ANATOMY OF A JAVASERVER PAGE Servlets are typically used for returning text-based content such as HTML, XML, WML, and so on. However, they are equally at home returning binary data such as images or serialized Java objects, which are often used by further servlets to generate some appropriate dynamic response. JSP Under the Hood A JSP page is simply a regular text file that contains markup (usually HTML) suitable for display inside a browser. Within this markup are special JSP elements that you ll learn more about later. These are used to provide processing logic that enables dynamic content to be produced on a request-by-request basis. In JSP terms, any markup that isn t a JSP element is known as template text, and this really can be any form of text-based content such as HTML, WML, XML, or even plain text! Of course the mixture of JSP elements and template text cannot simply be sent to the browser without any form of processing by the server. We mentioned earlier how JSP technology is an extension of servlet technology, and so you probably won t be surprised to learn that each JSP page is, in fact, converted into a servlet in order to provide this processing logic. Figure 1-1 shows a JSP page being translated and compiled into a servlet in response to a request. This servlet is known as the JSP implementation servlet. JSP Page Request <%@ taglib uri= http://java.sun.com/jstl/core prefix= C %> A Very Simple Page! Welcome: JSP Transformation and Compilation JSP Implementation Servlet Servlet/JSP Container JSP Page Response Figure 1-1. The JSP container translates and compiles the JSP source into an implementation class, which is used to process all requests.
Note: If you are looking for good and high quality web space to host and run your jsp application check Lunarwebhost jsp web hosting services

The Anatomy of a JavaServer Page CHAPTER 1

513-0 ch01.qxd 9/30/05 4:08 PM Page 2 CHAPTER 1 THE ANATOMY OF A JAVASERVER PAGE In this chapter, you ll take a look at some of the fundamental concepts based around JSP technology, such as the following: The mechanics of a JSP page Typical JSP architectures Core JSP syntax Tag libraries The aim of this chapter is to help you gain a grounding in the basics of JSP technology so you can make full use of the rest of the chapters in this book that build on these basic principles. Before You Begin To begin examining the basics of JSP technology, it s essential that you have a cursory familiarity with the alternative and complementary presentation-tier web component, Java servlets. The next chapter will discuss servlets in more detail. Java Servlets As mentioned earlier, servlets can most simply be described as custom web-server extensions, whose jobs are to process requests and dynamically construct appropriate responses. In practice, such responses are usually returned in the form of HTML or XML and are the result of a user making an HTTP request via a web browser. Servlet technology has been an extremely popular choice for building dynamic web applications such as e-commerce sites, online banking, and news portals, for reasons of simplicity, extensibility, efficiency, and performance over alternative technologies such as Common Gateway Interface (CGI) scripts. Some of the most basic advantages of servlet technology are as follows: Simplicity: Servlets are easy to write, and all the complicated threading and request delegating is managed by the servlet container. Extensibility: The Servlet API is completely protocol independent. Efficiency: Unlike CGI scripts, the execution of a servlet doesn t require a separate process to be spawned by the web server each time. Performance: Servlets are persistent, and their life cycle extends beyond that of each HTTP request. Servlets are simply Java classes that inherit from the javax.servlet.Servlet interface. These servlets are compiled and deployed inside a servlet container, which is a Java environment that manages the life cycle of the servlet and deals with the lower-level socket-based communication. The servlet container may be part of an existing Java-enabled web server itself or may be used as a stand-alone product that is integrated with a third-party web server. The servlet Reference Implementation container, Apache Jakarta Tomcat for example, may be used as a stand-alone web server or as a separate servlet container inside a larger commercial web server such as the Apache web server.
Note: If you are looking for good and high quality web space to host and run your jsp application check Lunarwebhost jsp web hosting services

The Anatomy of a JavaServer Page CHAPTER 1

The Anatomy of a JavaServer Page CHAPTER 1 The Java Platform, Enterprise Edition 5 (Java EE 5) has two different but complementary technologies for producing dynamic web content in the presentation tier namely Java Servlet and JavaServer Pages (JSP). Java Servlet, the first of these technologies to appear, was initially described as extensions to a web server for producing dynamic web content. JSP, on the other hand, is a newer technology but is equally capable of generating the same dynamic content. However, the way in which a servlet and a JSP page produce their content is fundamentally different; servlets embed content into logic, whereas JSP pages embed logic into content. JSP pages contain markup interlaced with special JSP elements that provide logic for controlling the dynamic content. Servlets are built using Java classes that contain statements to output markup code. Of these two paradigms, JSP pages are preferred for presenting dynamic content in the presentation tier due to their greater readability, maintainability, and simplicity. Further increasing the simplicity and ease of use of JSP pages was one of the main objectives of the JSP 2.0 specification, which included several new features to make it easier than ever to embrace JSP technology, especially for developers who aren t fluent in the Java syntax. The inclusion of a new expression language (EL) enables JavaScript-style JSP code to be embedded within pages, which makes it much easier for web developers not familiar with the Java syntax to understand the JSP logic. A library of standard actions known as the JavaServer Pages Standard Tag Library (JSTL) is also included to provide a host of useful, reusable actions such as conditional statements, iteration, and XML integration to name a few. These actions are applicable in some shape or form to most JSP web applications, and their use will greatly improve the reliability and ease of development for JSP page authors. Custom actions (also known as custom tags) also benefit from changes in the JSP specification, and it s now possible to write a custom action entirely in JSP syntax instead of Java syntax! JSP 2.1 further eases the development of JSP pages by unifying the JSP expression language with the JavaServer Faces (JSF) expression language. These new features will help make JSP pages easier to write and maintain and are discussed in detail in the following chapters: The JSP 2.1 expression language (EL) (see Chapter 3) The JavaServer Pages Standard Tag Library (JSTL) (see Chapter 4) The JavaServer Faces custom tags (see Chapter 5) JSP custom tags (see Chapters 6, 7, and 8)
Note: If you are looking for good and high quality web space to host and run your jsp application check Lunarwebhost jsp web hosting services