Friday, August 19, 2016

JSP Application Design with MVC

JSP Application Design with MVC

MVC was first described by Xerox in a number of papers published in the late 1980s. The key point of using MVC is to separate logic into three distinct units: the Model, the View, and the Controller. In a server application, we commonly classify the parts of the application as business logic, presentation, and request processing. Business logic is the term used for the manipulation of an application's data, such as customer, product, and order information. Presentation refers to how the application data is displayed to the user, for example, position, font, and size. And finally, request processing is what ties the business logic and presentation parts together. In MVC terms, the Model corresponds to business logic and data, the View to the presentation, and the Controller to the request processing.

An application data structure and logic (the Model) is typically the most stable part of an application, while the presentation of that data (the View) changes fairly often. Just look at all the face-lifts many web sites go through to keep up with the latest fashion in web design. Yet, the data they present remains the same. Another common example of why presentation should be separated from the business logic is that you may want to present the data in different languages or present different subsets of the data to internal and external users. Access to the data through new types of devices, such as cell phones and personal digital assistants (PDAs), is the latest trend. Each client type requires its own presentation format. It should come as no surprise, then, that separating business logic from the presentation makes it easier to evolve an application as the requirements change; new presentation interfaces can be developed without touching the business logic.

Labels:

JSP Elements

JSP Elements

There are three types of JSP elements you can use: directive, action, and scripting. A new construct added in JSP 2.0 is an Expression Language (EL) expression; let's call this a forth element type, even though it's a bit different than the other three.

Directive elements

The directive elements, shown in Table 3-1, specify information about the page itself that remains the same between requests—for example, if session tracking is required or not, buffering requirements, and the name of a page that should be used to report errors, if any.


Standard action elements

Action elements typically perform some action based on information that is required at the exact time the JSP page is requested by a browser. An action can, for instance, access parameters sent with the request to do a database lookup. It can also dynamically generate HTML, such as a table filled with information retrieved from an external system.


 Custom action elements and the JSP Standard Tag Library

In addition to the standard actions, the JSP specification defines how to develop custom actions to extend the JSP language, either as Java classes or as text files with JSP elements. The JSP Standard Tag Library (JSTL) is such an extension, with the special status of being defined by a formal specification from Sun and typically bundled with the JSP container. JSTL contains action elements for the type of processing needed in most JSP applications, such as conditional processing, database access, internationalization, and more.

Scripting elements

Scripting elements, allow you to add small pieces of code (typically Java code) in a JSP page, such as an if statement to generate different HTML depending on a certain condition. Like actions, they are also executed when the page is requested. You should use scripting elements with extreme care: if you embed too much code in your JSP pages, you will end up with the same kind of maintenance problems as with servlets embedding HTML.


Expression Language expressions

A new feature in JSP 2.0 is the Expression Language (EL), originally developed as part of the JSTL specification. The EL is a simple language for accessing request data and data made available through application classes. EL expressions can be used directly in template text or to assign values to action element attributes. Its syntax is similar to JavaScript, but much more forgiving; it's constrained in terms of functionality, since it's not intended to be a full-fledged programming language.
Rather, it is a glue for tying together action elements and other application components.

JavaBeans components

JSP elements, such as action and scripting elements, are often used to work with JavaBeans components. Put succinctly, a JavaBeans component is a Java class that complies with certain coding conventions. JavaBeans components are typically used as containers for information that describes application entities, such as a customer or an order.



Labels:

JSP Processing

JSP Processing


Just as a web server needs a servlet container to provide an interface to servlets, the server needs a JSP container to process JSP pages. The JSP container is responsible for intercepting requests for JSP pages. To process all JSP elements in the page, the  container first turns the JSP page into a servlet (known as the JSP page implementation class). The conversion is pretty straightforward; all template text is converted to println( ) statements and all JSP elements are converted to Java code that implements the corresponding dynamic behavior. The container then compiles the servlet class.


Converting the JSP page to a servlet and compiling the servlet form the translation phase. The JSP container initiates the translation phase for a page automatically when it receives the first request for the page. Since the translation phase takes a bit of time, the first user to request a JSP page notices a slight delay. The translation phase can also be initiated explicitly; this is referred to as precompilation of a JSP page. Precompiling a JSP page is a way to avoid hitting the first user with this delay.

The JSP container is also responsible for invoking the JSP page implementation class (the generated servlet) to process each request and generate the response. This is called the request processing phase.




As long as the JSP page remains unchanged, any subsequent request goes straight to the request processing phase (i.e., the container simply executes the class file).
When the JSP page is modified, it goes through the translation phase again before entering the request processing phase.

The JSP container is often implemented as a servlet configured to handle all requests for JSP pages. In fact, these two containers—a servlet container and a JSP container—are often combined in one package under the name web container.

So in a way, a JSP page is really just another way to write a servlet without having to be a Java programming wiz. Except for the translation phase, a JSP page is handled exactly like a regular servlet; it's loaded once and called repeatedly, until the server is shut down.

By virtue of being an automatically generated servlet, a JSP page inherits all the advantages of a servlet like  platform and vendor independence, integration, efficiency, scalability, robustness, and security.

Labels:

The Anatomy of a JSP Page

The Anatomy of a JSP Page


A JSP page is simply a regular web page with JSP elements for generating the parts that differ for each request.



Everything in the page that isn't a JSP element is called template text. Template text can be any text: HTML, WML, XML, or even plain text. Since HTML is by far the most common web page language in use today.
Note that JSP has no dependency on HTML; it can be used with any markup language. 
Template text is always passed straight through to the browser. When a JSP page request is processed, the template text and dynamic content generated by the JSP elements are merged, and the result is sent as the response to the browser.



Labels:

The Problem with Servlets over JSP

The Problem with Servlets


In many Java servlet-based applications, processing the request and generating the response are both handled by a single servlet class.

A typical servlet class

public class OrderServlet extends HttpServlet 
{
public void doGet((HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException 
{

response.setContentType("text/html");
PrintWriter out = response.getWriter( );

if (isOrderInfoValid(request)
{

saveOrderInfo(request);
out.println("<html>");
out.println(" <head>");
out.println(" <title>Order Confirmation</title>");
out.println(" </head>");
out.println(" <body>");
out.println(" <h1>Order Confirmation</h1>");
renderOrderInfo(request);
out.println(" </body>");
out.println("</html>");

}
...

If you're not a programmer, don't worry about all the details in this code. The point is that the servlet contains request processing and business logic (implemented by methods such as isOrderInfoValid() and saveOrderInfo( )), and also generates the response HTML code, embedded directly in the servlet code using println( ) calls. A more structured servlet application isolates different pieces of the processing in various reusable utility classes and may also use a separate class library for generating the actual HTML elements in the response. Even so, the pure servletbased approach still has a few problems:

  • Thorough Java programming knowledge is needed to develop and maintain all aspects of the application, since the processing code and the HTML elements are lumped together.

  • Changing the look and feel of the application, or adding support for a new type of client (such as a WML client), requires the servlet code to be updated and recompiled.

  • It's hard to take advantage of web page development tools when designing the application interface. If such tools are used to develop the web page layout, the generated HTML must then be manually embedded into the servlet code, a process which is time consuming, error prone, and extremely boring.
Adding JSP to the puzzle lets you solve these problems by separating the request processing and business logic code from the presentation.  Instead of embedding HTML in the code, place all static HTML in a JSP page, just as in a regular web page, and add a few JSP elements to generate the dynamic parts of the page. The request processing can remain the domain of the servlet, and the
business logic can be handled by JavaBeans and EJB components.





As I mentioned before, separating the request processing and business logic from presentation makes it possible to divide the development tasks among people with different skills. Java programmers implement the request processing and business logic pieces, web page authors implement the user interface, and both groups can use best-of-breed development tools for the task at hand. The result is a much more productive development process. It also makes it possible to change different aspects of the application independently, such as changing the business rules without touching the user interface.

Labels:

Introduction to Java Server Pages

Introduction to Java Server Pages

In late 1999, Sun Micro systems added a new element to the collection of Enterprise Java tools: Java Server Pages (JSP). Java Server Pages are built on top of Java servlets and designed to increase the efficiency in which programmers, and even non programmers, can create web content.

Java Server Pages is a technology for developing web pages that include dynamic content. Unlike a plain HTML page, which contains static content that always remains the same, a JSP page can change its content based on any number of variable items, including the identity of the user, the user's browser type, information provided by the user, and selections made by the user.

What Is JavaServer Pages?

A JSP page contains standard markup language elements, such as HTML tags, just like a regular web page. However, a JSP page also contains special JSP elements that allow the server to insert dynamic content in the page. JSP elements can be used for a variety of purposes, such as retrieving information from a database or registering user preferences. When a user asks for a JSP page, the server executes the JSP elements, merges the results with the static parts of the page, and sends the
dynamically composed page back to the browser.

JSP defines a number of standard elements that are useful for any web application, such as accessing JavaBeans components, passing control between pages and sharing information between requests, pages, and users. Developers can also extend the JSP syntax by implementing application-specific elements that perform tasks such as accessing databases and Enterprise JavaBeans, sending email, and generating HTML to present application-specific data. One such set of commonly needed custom elements is defined by a specification related to the JSP specification: the JSP Standard Tag Library (JSTL) specification. The combination of standard elements and custom elements allows for the creation of powerful web applications.

Why Use JSP?

In the early days of the Web, the Common Gateway Interface (CGI) was the only tool for developing dynamic web content. However, CGI is not an efficient solution. For every request that comes in, the web server has to create a new operatingsystem process, load an interpreter and a script, execute the script, and then tear it all down again. This is very taxing for the server and doesn't scale well when the amount of traffic increases.
Numerous CGI alternatives and enhancements, such as FastCGI, mod_perl from Apache, NSAPI from Netscape, ISAPI from Microsoft, and Java servlets from Sun Microsystems, have been created over the years. While these solutions offer better performance and scalability, all these technologies suffer from a common problem: they generate web pages by embedding HTML directly in programming language code. This pushes the creation of dynamic web pages exclusively into the realm of programmers. JavaServer Pages, however, changes all that.

The JSP Advantage


JSP combines the most important features found in the alternatives:

• JSP supports both scripting- and element-based dynamic content, and allows developers to create custom tag libraries to satisfy application-specific needs.
• JSP pages are compiled for efficient server processing.
• JSP pages can be used in combination with servlets that handle the business logic, the model favored by Java servlet template engines.
In addition, JSP has a couple of unique advantages that make it stand out from the crowd:
• JSP is a specification, not a product. This means vendors can compete with different implementations, leading to better performance and quality. It also leads to a less obvious advantage, namely that when so many companies have invested time and money in the technology, chances are it will be around for a long time, with reasonable assurances that new versions will be backward compatible; with a proprietary technology, this is not always a given.
• JSP is an integral part of J2EE, a complete platform for enterprise class applications. This means that JSP can play a part in the simplest applications to the most complex and demanding.


What You Need to Get Started

Before we begin, let's quickly run through what you need to run the examples and develop your own applications. You really only need three things:

• A PC or workstation, with a connection to the Internet so you can download the software you need

• A Java 2 compatible-Java Software Development Kit (Java 2 SDK)

• A JSP 2.0-enabled web server, such as Apache Tomcat from the Jakarta Project


Labels: