You are on page 1of 23

1.

Introduction to Web

The web is a complex, international, cross platform, cross language, cross cultural mesh of servers, clients, users, databases and quite a few artificial intelligence all connected to each other and capable to talk to each other. The web is owned by no single entity because it cannot be considered as a thing but as a process, action and communication medium. Initially web was originated to fulfill the need for a collaborative knowledge sharing tool" (to support scientific work) in an international context. Now it is providing access to information, news, email, shopping and entertainment. For different people web has different meaning, to some people it is like a newspaper, magazine or a library of any kind of books. To some people it is a radio or TV where they can access any latest information around all over the world. To some people it serves like a communication medium. To some people it is an open market where they can get anything of their interest without going out of their house. So it can be concluded that its domain is not restricted to the boundations.

1.2.1 Common Gateway Interface:


The program, which generates dynamic content using CGI technology are known as CGI Program. The CGIs are written in C, perl and Fortran language. Earlier the programs were written in C language. Being a compiled language the C programs run very fast but the problems with this approach were: First, it was relatively difficult to change the programs. Instead of just editing a file containing the program, the programmer must recompile the program each time there are some changes. But that was only the problem of one time when the program is changed after it gets compiled, the compiled program is fast to run. The second problem is that C is low-level language. It is difficult to manipulate large blocks of the code. This is especially a problem in CGIs where the goal is to transfer the user requests into the HTML representing server response. Then came the Perl for the scripting purpose. Perl programs do not need to recompile every time they are changed because Perl is an interpreted language. Every time a Perl program runs, another program called the Perl interpreter is also loaded which reads the program, translates it into instructions that computer can understand. This translation also takes time and hence Perl program sacrifice the speed at run time in favor of fast development and changes. Hence, the main disadvantage of the CGI program is that each time when a request comes to the server from the client the CGI script written in any of the language either Perl or C is run from the server to create the requested page which involves creation of new process into which the script is loaded and Perl interpreter is loaded (if the CGI is written in Perl) and then unloaded after response is finished. The same process is repeated if the same page is requested again. For example if there are N requests for a web page, the script and the Perl interpreter will be loaded

N times into the memory, due to which a lot of system memory will be wasted and also the speed of the server will suffer. Thus the CGI script creates the problem of System Resources and hence make the speed of the server very slow.

Comentario [SSG1]: Provide more explanation as to how exactly the system resources are wasted.

1.2.2 Java Servlets:


Java Servlets is the technology introduced by the Sun Microsystems to overcome the problems of CGI Scripts. Since it is a Java technology it is benefited with all the advantages of Java like once compile run anywhere, platform independent and speed. In Servlets there is no need of a new process each time as in traditional CGIs. The Java Virtual Machine takes care of each request by using a lightweight Java thread. In CGIs the program will be loaded N times in the memory for N requests wasting a lot of Operating System resources while In Servlets if there are N request for the same class there will be N threads for the process and the class will be loaded only once in the memory which makes an efficient utilization of Operating System resources. The Servlets are more powerful then CGIs as they can directly talk to the server while a CGI program can not, it has to use a server specific API to talk to the server.

1.2.3 Active Server Pages:


Active Server Pages is a Microsoft Technologies for the Server Side Programming. The programming language used in ASP is Visual Basic and Jscript the programmer can use Active X objects also. ASP is easy to learn language. The main problem with the ASP is that it works only on Microsofts IIS and Personal Web Server. And so the user has a limited domain of the server.

1.2.4 Java Server Pages:


Now come the Java Server Pages, which is a Java Technology. So the question arises when already Java Servlets exist then why there is need for another language based on Java technology. The answer to the question lies in the following lines. The main advantage of JSP over Servlets is that it separates presentation logic from the business logic. So a non-programming person can also use JSP to develop the dynamic web site. For their convenience JSPs are simple text files, which consists of simple HTML and new scripting JSP tags which looks like HTML tags but complied into Java Servlets at the time of first invocation.

1.2.5 A Comparison between ASP & JSP:


Functionally speaking ASP and JSP both deliver the same functionality. Both of them are using mark up tags and embedded tag in the program. The main difference is of Technology. As ASP uses Microsoft Technology so ASP pages are written in VB script while being a Java technology JSP pages are written in Java language and hence JSP pages are platform independent while ASP pages are not. JSP pages use Java Beans for the Business logic while ASP pages uses COM objects.

JSP pages are accessed fast then ASP pages because after first compilation JSP pages are not compiled again if there is no modification in the JSP source file, while ASP are interpreted by the .dll file residing at the server each time new request comes from the user. JSP 1.2 specification adds a new functionality to JSP pages called the Extensible Tags. The developer can create his own tags and can use them in any number of JSP pages. ASP does not favor this feature. In brief the ASP and JSP technologies can be compared as the following table: Criteria of comparison Scripting languages Web server ASP VB script, Jscript IIS PWS JSP Java Any web server including Apache, IIS, Netscape server Solaris Operating environment Microsoft windows, Unix, Linux Beans, EJBs, extensible tag library Yes(JDBC API) Yes (using JDBC API) Yes

Platforms

Microsoft windows

Components Compatibility with the legacy database Data source compatibility Custom tag extension

Com Yes(*Com API) Any ODBC, DAO, ADO data source No

* Com Connecter can be developed using any Component supporting language like VB, VC to connect to the legacy database.

1.3

JSP Architecture:

JSP is a part of the Java platform Enterprise Edition (J2EE), which is the Java architecture for developing multi-tier enterprise applications. A JSP page is executed by a JSP engine, which is installed in a web server or a JSP enabled application server. The JSP request response involves a four step architecture which can be described as follows: When JSP engine first time receives the request for some JSP page it parses the JSP file and create the Java source code file. The second step is the compilation of this source code into the class file. This is the Servlet files and is handled by the Servlet engine. The third step involved is the execution of the Servlet. In final step the servlet executes and response is send back to the client.

The first and second steps occur only once since the jsp is loaded or updated and third step is performed once since the server was last started. Once the Servlet is executed it becomes available there for the life cycle of the Java Virtual Machine, hence there is no need for its execution again and again. Response Client JSP Engine
Request Response

Respon Component Request

&Web server Request

JSP file

Fig 1.1: The Figure shows the flow of request and response when a jsp page is called.

1.4.

JSP Implementation Environment

1.4.1. Explain, What is Web Server?


On the Internet, Http is used for communication, which works on port 80. A web server is a Server-side application that listens to port 80. Any Http request submitted would travel over port 80, and will be intercepted by assigned web server. The Web server receiving the request would process it or may transmit it to enterprise application like EJBs for the next level of processing. After the request has been completely processed, the web server would send appropriate response to the client Browser and hence complete this web-based communication. Apache web server is a JSP enabled web server, which can be freely downloaded from apache.org & configured to have maximum share of the web server net. JSP pages can be used in combination with Servlets, HTML, XML, Applets, JavaBeans components and Enterprise JavaBeans components to implement a broad Varity of application architecture. The main Architectures in which JSP fits can be described as follows:

1.4.2. Two Tier Architecture:


Two Tier Architecture is also known as Client Server Architecture. In simple 2-tier architecture only two layers are involved in the processing, one is client and the other is server. All the business logic (JSP files) resides at the client and the server is devoted for the database. The client makes a request that is sent to the JSP file. The architecture can be better understand with the help of following diagram:

Request GUI Response JSP

Request for data Selected data Data base

Client Fig 1.2 Simple Two -Tier Architecture This approach has the following advantages:

Server

1. It is Simple and faster to program. 2. The developer can easily generate dynamic content based on request and state of response. The main problem with the approach were: 1. It is difficult to maintain changes. 2. It is very difficult to reuse the presentation and business logic. 3. No manageable for internet applications

1.4.3. 3 - Tier Architecture:


In Three-Tier Architecture the application involves three logical layers each of which is responsible for well-defined tasks. The first layer of 3-Tier Architecture is the Presentation Layer, which consists of a GUI from which user can send his requests and see the responses. The second or middle Tier is the Business Layer, which consists of all the business logic. The third and the last layer is the Data Layer, which stores all the data required for the Application. The business layer typically consists of Java code, which can be either Java Beans, Java Servlets or simple Java classes or combination of these. This layer is independent of presentation layer and the data layer, it just receives request from the Presentation layer, processes the request and interacts with data layer if required, and passes the response back to the Presentation layer. The main benefit of this architecture is that being independent layers multiple use interfaces can be built and deployed without effecting the application which can serve different type of users like internet user (using HTML in presentation layer), mobile user (using WAP technology in presentation layer) and much more. The presentation layer can either be some HTML page or some WAP application.

The third layer, the data layer consists of the data required for the application. This data can be any standard database such as Oracle, Sybase, a set of XML documents or a directory service like LDAP. The 3-Tier Architecture can be better understood by the following diagram:

Data base

User Interface

Application Layer

XML Document

LDAP

Fig 1.3 Simple Three -Tier Architecture

1.4.4. N- Tier Architecture:


In N-Tier Architecture there is no hard and fast rule to define the application layers. An n-tier architecture can support a number of different configurations. The basic difference between 2tier and N-tier architecture is that unlike 2-tier in N-tier architecture the application logic is divided functionally rather than physically. N-tier architecture is very supportive to the concept of reusing the components. An N-Tier Architecture can provide different layers which supports the following functionality individually:

User Interface: Handles the user interaction with the application. For example a Web browser. Presentation logic: defines what the user interface displays and how a user's requests are handled. Business Logic: handles the application's business rules through the interaction with the application's data. Infrastructure Services: provides additional functionality required by the application components, such as messaging, transaction support etc. Data layer: the data regarding the application resides in this layer.

Browser

Presentation Logic Services Business Logic

Data base

XML Documents

LDAP

Fig 1.3 Concept of Simple N-Tier Architecture

1.5. JSP engine:

When the browser sends a request to the server for the JSP page, the server forwards the request to the jsp engine. Jsp engine translates the jsp page into java Source code that is converted into a Servlet class by the servlet engine. This conversion of the jsp file and compilation occurs only when the file is first called after uploading or it is updated. After the first request other requests for the page directly goes to the Servlet Byte Code. The JSP engine is installed on a web server (Apache-Tomcat) or on the application server (Weblogic). JSP engine must support HTTP as a protocol for requests and responses, but an engine may also support additional request / response protocols. The default request and response objects are of type HttpServletRequest and HttpServletResponse respectively.

Summary:
Server side programming is needed to process the request coming from the client and to generate the response. CGI scripts, Servlets, ASP and JSP are used for the purpose of server side programming. CGI scripts are slow and a lot of system resources are wasted due to creation of new process for each request. Servlets are the Java solution to the problem of CGI scripts. In servlets no new process is started for every request so they save system resources like memory and processor speed. ASP is the Microsoft solution for the Server side programming. In ASP the scripting language is VB script. Servlets involves business logic and presentation logic together, so they are difficult to code. JSP is the solution to the problem of Servlets and separates the business logic and presentation logic. A JSP page is executed by a JSP engine, which is installed in a web server or a JSP enabled application server. JSP can be fitted into two tier, three tier or N-tier architecture. In two-tier architecture the layers are separated physically while in N-tier architecture the layers are separated functionally.

2.1

JSP Basic Syntax

JSP technology provides with the facility to mix static HTML elements with dynamic content that was not an easy thing with the Servlets. In simple HTML pages dynamic contents is added

by using <% %> tags. All dynamic contents come in between <%%> tags. These tags are called special tags in JSP. This change from HTML to JSP to include dynamic content is simple and quite subtle at first glance.

2.2

JSP Templates

A large percentage of JSP page just consists of static HTML, known as template text. In almost all respects, this HTML looks just like normal HTML, follows all the same syntax rules, and is simply passed through to the client by the servlet created to handle the page by the JSP engine. There are two minor exceptions to the template text is passed straight through rule. First, if <% is needed in the output, it will be given by putting <\% in the template text. Second JSP provides separate rule for commenting also. In HTML comments are given by <!--text --> JSPs solution to replace the above HTML comment with JSP comment is <%-- Start header --%> When JSP engine sees this tag, it recognizes it as a comment and does not put it into servlet while converting the JSP to servlet.

2.3

JSP Scripting Elements

A JSP page contains scripting language and some special JSP tags that can encapsulate tasks that are difficult or time consuming to program through servlets. The scripting language used for JSP is Java. For that, JSP has provided with some scripting elements to insert code into the resulting servlet, which is generated by the JSP engine. JSP has three type of scripting elements. Declarations Expressions Scriptlets In details these elements can be understood as further:

2.3.1 JSP Declarations

These are the tags, which, are used to create new objects and variable of any data type as well as providing initial value to them. The syntax for Declaration is given as follows: <%! define parameters %> Declaration contains one or more variables or object declarations that end or are separated by semicolons: <%! int I=0; %> //declaring and initializing single variable <%! int a, b; double c; %> //declaring many variables <%! Circle a = new Circle (2.0); %> //instantiating object

2.3.2 JSP Expressions


Expressions can contain any valid expression which is valid in the scripting language, if the scripting language is Java then expressions will follow all the Java conventions. The syntax for the JSP expression is given as follows

<%= Expression comes here %>

The example of Expression can be given as follows:

<%= out.println(hello) %> <%= Integer.parseInt(str) %> <%= new java.util.Date ( ) %> <%= a+b+c %>

Notice in the examples that statements are not ending with the semicolon. In JSP Expressions, expressions are not terminated by the semicolon.

Following is the example to illustrate the use of JSP Expression:

<html> <head><title></title> <%! int i =5, j =2; %> </head>

//declaration

<body> <h1>The test example for JSP expressions</h1> <b>the sum is <%= i + j %> //this is JSP expression <b> </body> </html>

Listing 2.1 expression.jsp

The output screen for the above example is as follows:

Figure 2.1 Output for expression

2.3.3 JSP Scriptlets

JSP Scriptlets are executed at request-processing time. They allow writing any number of valid scripting language statements. Following tasks can be done within a scriptlet:

Declare variables or methods to use later in the file. Write expressions valid in the page scripting language. Write any other statement valid in the scripting language used in the JSP page

Any text, HTML tags, or JSP elements must be outside the scriptlet.

The syntax for using JSP Scriptlets can be given as follows: <% any statement ;%> Scriptlets end with a semicolon (;) if the language require it. Example of valid scriptlet can be:

<% String name = null; If (request.getParameter (name) = = null) { %> Following example makes clear use of scriptlets in a conditional statement:

<html> <head><title></title></head> <body> <%! int item = 12 ;%> <% if(item < 12) {%> <br>less then dozen <% } else if(item >12){%> <br> more then dozen <% } else {%> <br> a dozen <%}%> </body> </html>

Listing 2.2 scriptlets.jsp

It is must to close <% tag while ending the statement and before starting the HTML code, For example in scriptlets.jsp

<% if(item < 12) {%> //notice that tag is closed here <br> less then dozen //this is HTML

In general, scriptlets can perform those tasks that can not be accomplished by the expressions alone. For example setting response header and status codes, writing the server console, server log or updating a database, executing a code that contains loop, conditional statement and other complex constructs. For example:

<% response.setContentType(text/plain); %> <% System.out.println(hello I m in JSP Scriptlet) ;%>

2.3.4 A Complete Example using Declaration, Expression and Scriptlet

Consider the following code:

<html> <head><title> </title></head> <body> <h2>use of declarations, expression and scriptlet </h2> <%! java.util.Date now = new java.util.Date(); %> <% //declaration %> today's date is <%= now.getMonth() + 1 %>/<%= now.getDate() %> <% //expression %> </body> </html> <% System.out.println("Today's date is "+ now.getMonth() +1 + "/" + now.getDate() ) ;%> <% //scriptlet %>

Listing 2.3 date.jsp

The above example is using: JSP Declaration to instantiate the object of Date class, expression to print today date at the client end and scriptlet to print today date at server console at the server end.

System.out.println is used to display any data or message at the server end, which helps in debugging the code.

2.3.5 When is the Scripting Elements executed


A JSP source file is processed in two stages Http translation time and request processing time. At HTTP translation time, which occurs when a user first loads a JSP page, the JSP source file is compiled to a Java class, usually a Java servlet. The HTML tags as many JSP tags as possible are processed at this stage, before the user makes a request. Request processing time occurs when user submit some request from the JSP page. The request is sent from the client to the server by way of the request object. The JSP container then executes the compiled JSP file, or servlet, using the request values the user submitted. In JSP, declarations are processed at request processing time and are available to other declarations, expression, and scriptlets in the compiled JSP file. Expressions are evaluated at request processing time. The value of each expression is converted to a String and inserted in place in the compiled JSP file. Scriptlets also are evaluated at request processing time, using the values of any declaration that are made available to them.

2.4

JSP Implicit Objects

To simplify the code JSP is provided with some predefined variables sometimes called the implicit objects. These objects need not to be declared or instantiated anywhere but these are already provided by the container in the implementation class.

These can be used only in the scriptlets and expressions and not in declaration. Because the declaration part is converted into declaration of variables used in the methods but these are already declared with the container in the implementation class so no need for the redeclaration. In details these objects can be defined as follows:

2.4.1 Request Object


This is the object associated with HttpServletRequest class. It is responsible to take the form elements and pass to the JSP by the JSP container as a parameter to the _jspService () method. The scope of request object is request only. There are some important methods of Request object which are commonly used in JSP pages, these methods and their usage are listed in the following Table: Method getCharacterEncoding () getProtocol () getScheme () getServerName () getServerPort () getRemoteAddr () getRemoteHost () getAuthType () Purpose The character set in which this page is encoded (e.g, ISO) The protocol used for the request (HTTP/1.0) The scheme portion of the URL such as HTTP The name of the computer on which the server is running The port the server is listening The address of the computer the request came from The name of the computer the request came from The type of authorization used for the request (if the page is not protected it will be null) Any header sent by the browser The method used for the request (post, get) The path info The path to the requested file on the servers local filesystem

getHeader () getMethod () getPathInfo () getPathTranslated ()

getQueryString () getRemoteUser ()

The query string portion of the URL. (The portion after the question mark) The name of the user logged in as (if the page is not protected, its value will be null) The full request URL of the JSP. Table 2.1 Methods of Request Object

getRemoteURI ()

2.4.2 Response Object


This is the object associated with HttpServletResponse class. It is responsible to deliver the requested data, which is produced by the JSP to the client. It is passed to the JSP by the JSP container as a parameter to the _jspService () method. The scope of response object is response.

2.4.3 Processing Form Data Using Request and Response Object


When user submits some data to the server from the form, it is processed there and response is send back to the user. The task of sending the data to the server and from the server to the user is accomplished by the request and response objects. Consider the following Form in which user will submit his name and age to the server which will be displayed to him from the sever in response. The sendreq.html will contain the User From The showResp.jsp will process the request and send the response back to the user.

The code for sendreq.html can be given as follows:

<html> <head> <title>Use of Request and Response Objects</title> </head> <body> <form action = "showResp.jsp" method = "post"> Enter Your name here <input type = "text" name = "nam"><br> Listing 2.3 Enter your age here <input type = "text" name = "age"><br> <input type = "submit" value = "Submit"> </form> </body> </html>

Listing 2.4 sendreq.html

The code for showResp.jsp can be given as follows:

<html> <head> <title> This is the response of uor request </title> <% String name = request.getParameter("nam"); %> <% String age = request.getParameter("age"); %> <body> The name of the user is <%= name %><br> the age of the user is <%= age %> </body> </html> Listing 2.5 showResp.jsp

The output of the sendreq.html is

Figure 2.2 User Form to send the request The responses send back to the client will be

Figure 2.3 Response send back to the user Above is the Response send back to the user if he enters name as Deepti agrawal and age as 23.

2.4.4 Page Object


This object is associated with Object class and is accessed using this reference like in Java programming language. The scope of the object is page.

2.4.5 PageContext Object

This object is associated with PageContext object. This is used to access different attributes of a page at single point. The PageContext object holds the value of the different attributes of the current page. The scope of the variable is Page.

2.4.6 Session Object


This object is associated with HttpSession class. This variable is used to maintain the session information. Sessions are created automatically so it is always created even if there is no session reference in incoming request. The session can be turn off by assigning false value to the session attribute in of the page directive. The values in the session can be placed and retrieved by using setAttribute () and getAttribute () methods. The scope of the object is session.

2.4.7 Application Object

This object is associated with the ServletContext and obtained as getServletContext.getContext (). JSP pages can store and retrieve the information in ServletContext object using setContext () and getContext () methods rather then storing in any variable. The ServletContext is shared by all the servlets in the servlet engine and so the data can be retrieved anywhere in the application. The scope of the object is Application

2.4.8 Out Object


This is the object associated with the JspWriter class. In order to make the response object useful, this is the buffered version of PrintWriter class of JspWriter. The buffer size can be controlled by the buffer attribute of page directive. The scope of the object is page.

2.4.9 Config Object


This object is associated with the ServletConfig object. It represents the Servlet configuration. The scope of this variable is page.

2.4.10 Exception Object


This object is associated with java.lang.Throwable class. It refers to the runtime exception that resulted in the error page being invoked. And is available only in an error page. The concept of error page will be discussed later in the book The throwable object describing the exception may be accessed within the error page by the exception object.

2.5

JSP Standard Actions

JSP Actions are the special tags that affect the behaviour of the JSP at the run time and affects the response, which is, send back to the client. There are some standard JSP actions. These

Standard actions are provided with some basic functionality, which benefits to the author while designing the web page. All JSP containers implement these actions. The standard action types are: <jsp: useBean> <jsp: setProperty> <jsp: getProperty> <jsp: include> <jsp: forward> <jsp: param> <jsp: plugin> Out of which <jsp: useBean>, <jsp: setProperty> and <jsp: getProperty> are used with the Java Beans which will be discussed in the coming chapters.

Summary:
The chapter introduces to you with the basic building blocks of the JSP. These can be summarized as follows: Scripting language is a mechanism for embedding code directly into a HTML page. There are three classes of the Scripting elements: o Declarations: <! %%> o Expressions: <%=%> o Scriptlets: <%..%>. To simplify the code JSP is provided with some predefined variables sometimes called the implicit objects. JSP has provided with the following implicit objects: Request Object, Response Object, Page Object, PageContext Object, Session Object, Application Object, Out Object, Config Object, Exception Object JSP Actions are the special tags that affect the behaviour of the JSP at the run time and to the response. Following actions are supported by the JSP: <jsp:useBean>, <jsp:setProperty>, <jsp:param>, and <jsp: plugin> <jsp:getProperty>, <jsp:include>, jsp:forward>,

Directive provides global information that is conceptually valid independent of any specific request received by the JSP page, the syntax of Directive <%@ Directive %>. There are three possible directive currently defined by the JSP specification: o Page:- Defines information will be available globally for that JSP

o Include:-The include directives is used to insert text and code at JSP translation time. o Taglib: - The taglib directive declares that the page uses custom tags, uniquely names the tag library defining.

You might also like