2013-09-24

Java Server Pages - Evolution of Web Application, Introduction to Java Server Pages


Evolution of Web Application

Introduction

Core Issue

Characteristics of web Application

Role of JAVA for Server Applications

JavaServer Pages - An Overview

The Components of JSPs

How JSP and JSP Container function?

JSP Planning

Advantages of using JSP

Introduction to Java Server Pages

Introduction to Java Server Pages

How a JSP Page Looks Like?

Why we employ JSP?

JSP Advantages

Convenience of JSP Coding Versus Servlet Coding

Calling JavaBeans

JSP Pages and Alternative Markup Languages

What we need to get started

Sample Example

Evolution of Web Application

 

Introduction

 

Web server purpose has evolved from static to dynamic applications. These developments became important due to some deficiencies in previously web site design

 

For example, to put more of commerce processes on the web, whether in business-to-consumer or business-to-business markets, usual web site design technologies are not enough

 

 

Core Issue

 

The major issues, that every developer faces when developing web applications, are:

 

Scalability:

A successful site will have more users and as the number of users is increasing fast, the web applications have to scale correspondingly

 

 

Integration of data and business logic:

The web is a new way to conduct business, and so it should be able to use the same middle-tier and data-access code

 

 

Manageability:

sites keep getting bigger and we need some practical mechanism to deal with the ever-increasing content and its interaction with business systems.

 

 

Personalization:

Adding a personal touch to the web page becomes an essential factor to keep our customer coming back again. Knowing their preferences, allowing them to configure the information they view, recall their past transactions or frequent search keywords are all significant in providing feedback and interaction from what is otherwise a fairly one-sided conversation

 

 

 

Characteristics of web Application

 

Apart from common needs for a business-oriented web site, the necessity for new technologies to create robust, dynamic and compact server-side web applications has been realized.

 

 

The major characteristics of dynamic web server applications are:

. Serve HTML and XML, and stream data to the web client

. Separate presentation, logic and data

. Interface to databases, other Java applications, directory and mail services.

. Make use of application server middleware to provide transactional support.

. Track client sessions.

 

 

 

 

Role of JAVA for Server Applications

 

The J2EE specification provides a platform for enterprise applications, with complete API support for enterprise code and guarantees of portability between server implementations. Also it brings a clear division between code which deals with presentation, business logic and data

 

The J2EE specification meets the requirements of web applications because it provides:

. Affluent via servlets and built-in support for and EJBs. interaction with a sessions available in both servlets web server

. The use of EJBs to mirror the user interaction with data by providing automatic session and transaction support to EJBs operating in the EJB server.

. Entity EJBs to represent data as an object and seamless integration with the Java data access APIs

. Flexible template-based output using JSP and XML

 

APIs mean that the final web page can be generated from a user input request, which was processed by a servlet or JSP and a session EJB, which represents the user's session with the server, using data extracted from a database and put into an entity EJB.

 

Thus, the Java revolution of portable code and open APIs is conjugal with an evolution in existing products such as database, application, mail and web servers. The wide availability of products to run Java applications on the server has made this a fast-moving and very competitive market, but the essential compatibility through specifications, standard APIs and class libraries has held. It makes server-side Java a very exciting area.

 

 

 

JavaServer Pages - An Overview

 

The JavaServer Pages specification provides web developers with a structure to build applications containing dynamic web content such as HTML, DHTML, XHTML and XML.

 

A JSP page is a text based document containing static HTML and dynamic actions which describe us how to process a response to the client in a more powerful and flexible manner.

Most of a JSP file is plain HTML but it also has, interspersed with it, special JSP tags.

 

There are many JSP tags such as:

. JSP directive denoted by tags and

. Directive includes the contents of the file sample.php in the response at that point.

 

To process a JSP file, we need a JSP engine that can be connected with a web server or can be accommodated inside a web server.

 

Firstly when a web browser seeks a JSP file through an URL from the web server, the web server recognizes the .jsp file extension in the URL requested by the browser and understands that the requested resource is a JavaServer Page. Then the web server passes the request to the JSP engine. The JSP page is then translated into a Java class, which is then compiled into a servlet.

 

 

The translation and compilation phase occurs when the JSP file is requested for the first time, or if it undergoes any changes to the extent of getting retranslated and recompiled. For each additional request of the JSP page thereafter, the request directly goes to the servlet byte code, which is already in memory.

 

Thus when a request comes for a servlet, an init () method is called when the Servlet is first loaded into the virtual machine, to perform any global initialization that every request of the servlet will need. Then the individual requests are sent to a service () method, where the response is put together.

 

The servlet creates a new thread to run service () method for each request. The request from the browser is converted into a Java object of type HttpServletRequest, which is passed to the Servlet along with an HttpServletResponse object that is used to send the response back to the browser. The servlet code performs the operations specified by the JSP elements in the .jsp file.

 

 

 

The Components of JSPs

 

The universal system are applicable to all JSP tags:

1. Tags have either a start tag with elective attributes, an optional body, or a matching end tag or they have an empty tag with attributes.

 

2. Attribute values in the tag always appear quoted. The special strings ' and " can be used if quotes are a part of the attribute value itself.

 

 

The whitespace within the body text of a document is not important, but is preserved, it means whitespace in the JSP being translated is read and preserved during translation into a servlet.

 

The character \ can be used as an escape character in a tag, for instance, to use the % character, \% can be used.

 

 

JavaServer Pages are text files that combine standard HTML and new scripting tags.

 

JSPs look like HTML, but they get compiled into Java servlets the first time they are invoked. The resulting servlet is a combination of HTML from the JSP file and embedded dynamic content specified by the new tags.

 

 

JSP page can be divided into two categories:

. Elements that are processed on the server

. Template data or everything other than elements, that the engine processing the JSP engines.

 

 

Element data or that part of the JSP which is processed on the server, can be classified into the following categories:

. Directives
. Scripting elements
. Standard actions

 

 

Directives

JSP directives serve as messages to the JSP container from the JSP.

These are used to set global values such as class declaration, methods to be implemented, output content type, etc. All directives have scope of the entire JSP file.

 

Directives are characterized by the @ character within the tag.

 

The three directives are page, include and taglib.

 

 

Scripting elements

Scripting elements are used to include scripting code (Java code) within the JSP. It allows declaring variables and methods include arbitrary scripting code and evaluate an expression.

 

The three types of scripting element are: Declaration, Scriptlets and Expressions:

A declaration is a building block of Java code in a JSP which is used to define class-wide variables and methods in the generated class file. Declarations are initialized when the JSP page is initialized and have class scope. Anything defined in a declaration is available throughout the JSP, to other declarations, expressions or code.

 

A scriptlet is a block of Java code that is executed at request-processing time. A scriptlet is enclosed between. What the scriptlet really does depends on the code, and it can produce output into the output stream to the client. Multiple scriptlets are combined in the compiled class in the order in which they appear in the JSP. Scriptlets like any other Java code block or method can modify objects inside them as a result of method invocations.

 

An expression is a shorthand document for a scriptlet that outputs a value in the response stream back to the client. When the expression is evaluated, the outcome is converted to a string and displayed, an expression is enclosed within. If any part of expression is an object, the conversion is done using the toString () method of the object.

 

 

Standard actions

Standard actions are exact tags that influence the runtime behavior of the JSP and affect the answer sent back to the client. The JSP specification lists some standard action types to be provided by all containers, irrespective of the implementation. Standard actions provide page authors with some basic functionality to exploit; the vendor is free to provide other actions to enhance behavior.

 

 

 

How JSP and JSP Container function?

 

A JSP page is executed in a JSP container or a JSP engine, which is installed in a web server or in an application server.

 

When a client asks for a JSP page the engine wraps up the request and delivers it to the JSP page along with a response object. The JSP page processes the request and modifies the answer object to integrate the communication with the client. The container or the engine, on getting the response, wraps up the responses from the JSP page and delivers it to the client. The abstractions of the request and response are the same as the ServletRequest and ServletResponse respectively. If the protocol used is HTTP, then the corresponding objects are HttpServletRequest and HttpServletResponse.

 

The first time the engine intercepts a request for a JSP, it compiles the JSP page and other files into a class file that implements the servlet protocol. If the dependent files are other JSPs they are compiled into their own classes.

 

The servlet class generated at the end of the translation process must extend a superclass that is either :

1. It is specified by the JSP author through the use of the extends attribute in the page directive or
2. It is a JSP container specific implementation class that implements javax.servlet.jsp.JspPage interface and provides some basic page specific behavior.

 

As JSP pages use HTTP, their implementation classes actually implement the javax.servlet.jsp.HttpJspPage interface, which is a sub interface of javax.servlet.jsp.JspPage.

 

 

The javax.servlet.jsp.JspPage interface contains two methods:

1. public void jspInit() - It is invoked when the JSP is initialized and the page are free to provide initialization of the JSP by implementing this method in their JSPs.
2. public void jspDestroy() - This method is invoked when the JSP is about to be destroyed by the container.

 

 

The javax.servlet.jsp.HttpJspPage interface contains one method:

public void _jspService(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException

This method generated by the JSP container is invoked, every time a request comes to the JSP. The request is processed and the JSP generates appropriate response. This response is taken by the container and passed back to the client.

 

 

 

 

JSP Planning

 

The two fundamental customs of using the JSP skill are :

. The client/server (page-centric) 2-tier approach and

. The N-tier approach (dispatcher).

 

 

The client/server (page-centric) 2-tier approach

Applications built using a client-server (2-tier) approach consist of one or more application programs running on client machines and connecting to a server-based application to work.

 

This model allows JSPs or Servlets direct access to some resource such as database or legacy application to service a client's request. The JSP page is where the incoming request is intercepted, processed and the response sent back to the client. JSPs differ from Servlets in this scenario by providing clean code, separating code from the content by placing data access in EJBs. Even though this model makes application development easier, it does not scale up well for a large number of simultaneous clients as it entails a significant amount of request processing to be performed and each request must establish or share a potentially scarce/expensive connection to the resource in question

 

Page view:

This basic architecture involves direct request invocations to a server page with embedded Java code, and markup tags which dynamically generate output for substitution within the HTML All the Java code may be embedded within the HTML, so changes are confined to a very limited area, reducing complexity drastically.

 

 

The big trade:

As the scale of the system grows, some limitations begin to surface, such as bloating of business logic code in the page instead of factoring forward to a mediating Servlet or factoring back to a worker bean. It is a fact that utilizing a Servlet and helper beans helps to separate developer roles more cleanly and improves the potential for code reuse.

 

Page-view with bean

This pattern is used when the above architecture becomes too cluttered with business-related code and data access code. The Java code representing the business logic and simple data storage implementation in the previous model moves from the JSP to the JavaBean worker.

 

 

 

Advantages of using JSP

 

One of the major reasons why the JavaServer Pages technology has evolved is the overwhelming technical need to simplify application design by separating dynamic content from static template display data.

Another benefit of utilizing JSP is that it allows to more cleanly separate the roles of web application/HTML designer from a software developer

 

The JSP technology has a number of benefits, which are :

 

1. The JSP technology is platform independent

in its dynamic web pages, its web servers, and its underlying server components. JSP pages perform completely without any aggravate on any platform, run on any web server, and web-enabled application server. The JSP pages can be accessed from any web server

 

2. The JSP technology emphasizes the use of reusable components

JSP's components can be shared or manipulated towards developing more purposeful components and page design. This definitely reduces development time .JSPs are very different from Servlets, but precompiled into Servlets at run time and executed by a JSP engine which is installed on a Web-enabled application server such as BEA WebLogic and IBM WebSphere.

 

 

 

Introduction to Java Server Pages

 

Introduction to Java Server Pages

 

What is Java Server Page?

 

JSP stands for 'Java Server Pages'. These are pages which are used to run dynamic content to the user using logic and data (XML, Database etc) on the server side

 

JSP is a part of J2SE (Java 2 Standard Edition) and along with Java Servlets and Java Beans is used to develop efficient, scalable and secure web applications in quick time.

 

Java Server Pages is a technology specified by Sun Microsystems as a trouble-free way of generating dynamic content in pages that are output by a Web application (an application running on a Web server).

 

This technology, which is openly coupled with Java servlet technology, helps us to incorporate Java code snippets and calls to external Java components within the HTML code (or other markup code, such as XML) of our Web pages

 

Java Server Pages (JSP) technology works satisfactorily as a front-end for business logic and dynamic functionality in JavaBeans and Enterprise JavaBeans (EJBs).

 

JSP code is distinct from other Web scripting code, such as JavaScript, in a Web page. Anything that we can include in a ordinary HTML page can be incorporated in a JSP page as well. In a usual development for a database application, a JSP page will call a component such as a JavaBean or Enterprise JavaBean, and the bean will directly or indirectly access the database through JDBC.

 

A JSP page is translated into a Java servlet before being executed, and processes HTTP requests and generates responses similarly to any other servlet. JSP technology offers a more suitable way to code the servlet. The translation typically occurs on demand, but sometimes in advance

 

JSP pages are fully interoperable with servlets--JSP pages can comprise output from a servlet or forward to a servlet, and servlets can include output from a JSP page or forward to a JSP page.

 

 

 

How a JSP Page Looks Like?

 

Here is an example of a easy JSP page:

 

<HTML>
<HEAD>
<TITLE>
The Welcome User JSP in MKDTutorials
</TITLE>
</HEAD>
<BODY><center>

<% String user=request.getParameter("user"); %>
<H1>WELCOME TO MKDTutorials</H1>
<H3>Welcome <%= (user==null) ? "" : user %>!</H3>
<P><B> Today is <%= new java.util.Date() %>. Have a nice day! :-)</B></P><p><b>MKDTutorials is fulfilling your dream of Learning the JSP</b></p>
<B>Enter name:</B><FORM METHOD=get>
<INPUT TYPE="text" NAME="user" SIZE=15>
<INPUT TYPE="submit" VALUE="Submit name">
</FORM>
</BODY>
</HTML>

 

Output:



 

 

Why we employ JSP?

 

First of all ASP is not the only answer out there which supports rapid web application development, there are others like PHP, Perl, ColdFusion etc. JSP is different from all of them because

 

1. JSP uses Java. Java is by far one of the most popular programming languages on the web. It's simpler syntax and 'write once run anywhere' capability makes it the server side programming language of preference. So JSP pages and Java applications that we create will run on almost all major operating systems. e.g. Windows, UNIX, etc.

 

2. JSP is part of J2EE. J2EE is the most popular model used to develop Enterprise level applications. J2EE is supported by software giants like Sun Microsystems, BEA, Oracle, IBM etc. So once we learn programming JSP, we can extend our skills to learn other Java technologies to become what is called, an Enterprise Developer

 

3. Networking is built into Java. Java's inherent support for Networking makes it an ideal language for the internet

 

 

 

JSP Advantages

 

1. Separation of static from dynamic content

With servlets, the logic for creation of the dynamic content is an intrinsic part of the servlet and is closely tied to the static appearance templates responsible for the user interface. Thus, even minor changes made to the UI typically result in the recompilation of the servlet. This tight coupling of presentation and content results in brittle, inflexible applications. However, with JSP, the logic to generate the dynamic content is kept separate from the static presentation templates by encapsulating it within external JavaBeans components. These are then created and used by the JSP page using special tags and scriptlets. When a page designer makes any changes to the presentation template, the JSP page is automatically recompiled and reloaded into the web server by the JSP engine

 

2. Write Once Run Anywhere

JSP technology brings the "Write Once, Run Anywhere" paradigm to interactive Web pages. JSP pages can be moved easily across platforms, and across web servers, without any changes

 

3. Dynamic content can be served in a range of formats:

There is nothing that mandates the static template data within a JSP page to be of a certain format. Therefore, JSP can service a diverse clientele ranging from conventional browsers using HTML/DHTML, to handheld wireless devices like mobile phones and PDAs using WML, to other B2B applications using XML

 

4. Recommended Web access layer for n-tier architecture:

Sun's J2EE Blueprints, which offers guidelines for developing large-scale applications using the enterprise Java APIs, categorically recommends JSP over servlets for serving dynamic content.

 

5. Completely leverages the Servlet API:

If we are a servlet developer, there is very little that we have to "unlearn" to move over to JSP. In fact, servlet developers are at a distinct advantage because JSP is nothing but a high-level abstraction of servlets. We can do almost anything that can be done with servlets using JSP--but more easily

 

 

 

Convenience of JSP Coding Versus Servlet Coding

 

Combining Java code and Java calls into an HTML page is more convenient than using straight Java code in a servlet. JSP syntax gives us a shortcut for coding dynamic Web pages, typically requiring much less code than Java servlet syntax

 

Following is an example contrasting servlet code and JSP code

 

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class Hello extends HttpServlet
{
public void doGet(HttpServletRequest rq, HttpServletResponse rsp)
{
rsp.setContentType("text/html");
try {
PrintWriter out = rsp.getWriter();
out.println("("<HTML>"); out.println("<HEAD><TITLE>Welcome</TITLE></HEAD>"); out.println("("<BODY>"); out.println("("<H3>Welcome!</H3>"); out.println("("<P>Today is "+new java.util.Date()+".</P>"); out.println("("</BODY>"); out.println("("</HTML>"); } catch (IOException ioe)
{
// (error processing)
}
}
}

 

JSP Code

<HTML>
<HEAD><TITLE>Welcome</TITLE></HEAD>
<BODY>
<H3>Welcome!</H3>
<P>Today is <%= new java.util.Date() %>.</P>
</BODY>
</HTML>

 

Note how much simpler JSP syntax is. Among other things, it saves Java overhead such as package imports and try...catch blocks.
Additionally, the JSP translator automatically handles a significant amount of servlet coding overhead for us in the .java file that it outputs, such as directly or indirectly implementing the standard javax.servlet.jsp.HttpJspPage interface and adding code to acquire an HTTP session.
Also note that because the HTML of a JSP page is not embedded within Java print statements, as it is in servlet code, we can use HTML authoring tools to create JSP pages.

 

 

 

Calling JavaBeans

 

JSP technology allows separating the development efforts between the HTML code that determines static page presentation, and the Java code that processes business logic and presents dynamic content. It therefore becomes much easier to split maintenance responsibilities between presentation and layout specialists who may be proficient in HTML but not Java, and code specialists who may be proficient in Java but not HTML.In a typical JSP page, most Java code and business logic will not be within snippets embedded in the JSP page--instead, it will be in JavaBeans or Enterprise JavaBeans that are invoked from the JSP page. JSP technology offers the following syntax for defining and creating an instance of a JavaBeans class

<jsp:useBean id="pageBean" class="mybeans.NameBean" scope="page" />

 

This example creates an instance, pageBean, of the mybeans.NameBean class. Later in the page, we can use this bean instance, as in the following example

Hello <%= pageBean.getNewName() %> !

 

 

This prints "Hello Aman !", for example, if the name "Aman" is in the newName attribute of pageBean, which might occur through user input. The separation of business logic from page presentation allows convenient division of responsibilities between the Java expert who is responsible for the business logic and dynamic content (the person who owns and maintains the code for the NameBean class) and the HTML expert who is responsible for the static presentation and layout of the Web page that the application users see (the person who owns and maintains the code in the .jsp file for this JSP page)

 

 

 

 

JSP Pages and Alternative Markup Languages

 

JavaServer Pages technology is typically used for dynamic HTML output, but the Sun Microsystems JavaServer Pages Specification, also supports additional types of structured, text-based document output.

 

A JSP translator does not process text outside of JSP elements, so any text that is appropriate for Web pages in general is typically appropriate for a JSP page as well.

 

A JSP page takes information from an HTTP request and accesses information from a data server (such as through a SQL database query). It combines and processes this information and incorporates it, as appropriate, into an HTTP response with dynamic content. The content can be formatted as HTML, DHTML, XHTML, or XML.

 

 

 

What we need to get started

 

We'll need to have JDK 1.3 installed on our system in order for Tomcat 4.0 to work. If we don't already have it, we can get it from java.sun.com

 

Obtaining Tomcat 4.0

Tomcat 4.0 is an open source and free Servlet Container and JSP Engine. It is developed by Apache Software Foundation's Jakarta Project and is available for download at http://jakarta.apache.org/tomcat, or more specifically at http://jakarta.apache.org/site/binindex.php

 

Choose the latest Tomcat 4.0 version. Currently Tomcat 4.0 beta 5 is the latest version. Once we have downloaded Tomcat 4.0, proceed to the next step

 

Installing Tomcat 4.0

Unzip the file to a suitable directory. In Windows, you can unzip to C:\ which will create a directory like C:\jakarta-tomcat-4.0-b5 containing Tomcat files

Now we'll have to create two environment variables, CATALINA_HOME and JAVA_HOME. Most probably we'll have JAVA_HOME already created if we have installed Java Development Kit on our system.

 

To create these environment variables in Windows 2000, go to Start -&git Settings -&git Control Panel -&git System -&git Advanced -&git Environment Variables -&git System variables -&git New. Enter the name and value for CATALINA_HOME

 

Running Tomcat 4.0

Start Tomcat by running the C:\jakarta-tomcat-4.0-b5\bin\startup.bat batch file. Tomcat server will start and print some status message

Now point your browser to http://localhost:8080 and you should see the default Tomcat home page. To shutdown the server run C:\jakarta-tomcat-4.0-b5\bin\shutdown.bat batch file.

 

 

 

Sample Example

 

Print the following text into 'index.jsp' file and save it:

<html>
<head>
<style>p { font-family:tahoma; font-size:14pt; }</style>
</head>
<body>
<%
String name = "Aman Kumar";
%>
<p>Hello <%= name %>!</p>

</body>
</html>

 

Explanation

Above page appears to be a simple HTML page except one line of Java code between the <% and %> tags. These work the same way as <% %> tags in ASP. We can add server side Java code between these tags. In this case we simple declared a variable 'name' of type String ( simple text ) and initialized it with a value of "Aman Kumar", we can substitute our own name if we want.

 

<%
String name = "Aman Kumar";
%>
Next we output the value of 'name' variable to the user.
<p>Hello <%= name %>!</p>

 

Start Tomcat server and point your browser to http://localhost:8080/star/index.jsp to see JSP page running

 

Output:



 

 

Next Chapter »

Show more