Webs



JSP

Introduction

A web application consists of number of web pages. These web pages are generally developed using HTML. But pages developed using HTML produce static output or they have passive behavior. But at times you want to give different output to users by changing only a small part of the page. For example, if you want to display date and time or hit-count require a very small change in web page. To provide dynamic behavior to it, small programs can be included in HTML. This makes web pages to give different output for different users. Thus the behavior of the page becomes active.

Java Server Pages (JSP) is a Java-based technology that simplifies the process of developing dynamic web-sites using JSP, web designers & developer can quickly incorporate dynamic elements into web pages using embedded Java & markup tags. The tags allow the user to present data & java object (Applet/JDBC/Java bean/servlet etc) allow storing business logic.

JSP specification is a standard extension defined on top of the servlet API. JSP‘s are text files with .jsp extension, which includes HTML/XML tags along with embedded java code.

Advantage Of JSP Technology

1. Portability

Since it is based on Java, JSP technology is platform independent. To run .jsp files, we need a JSP engine (programs used to run .jsp files). This engine can be built for different type of web-servers to make them execute jsp files.

2. Reuse of Components & Tag Libraries

JSP technology emphasizes the use of reusable component such as Java Bean Components, Enterprise Java Bean Components etc. Data is the main reason of dynamic contents. The components may contain the code to obtain the data from databases or text files thus offering different contents to JSP files.

It supports different type of markup languages such as HTML/DHTML/XML. JSP also supports user-defined tags. For user-defined tags, the control is transferred to classes that contain the code, which should be executed. Any type of code such as JDBC, File Handling etc can be included in these classes. Thus a JSP page developer need not have considerable knowledge of Java.

3. Separation of static & Dynamic Content

Using HTML pages, we can send only static contents to web clients. If we use servlets, then the entire HTML code is required to be written in println statement, which is tedious. It also makes the entire page to be dynamic. JSP allows you to include dynamic content into the static contents separating the two from each other. The static contents are provided using HTML tags and dynamic contents are generated using scriptlets, user-defined tags etc. It also follows popular MVC (Model-View-Control) Design Pattern.

Fig.

4. Suitable for N-Tier Architecture

Because of features such as, platform-independence, support for different types of servers(web servers, database servers etc), markup languages, reuse of objects in the form of components etc. it is best suited for N-Tier architecture.

5. Performance

JSP pages are automatically compiled before execution. So it frees the job of programmer to explicitly compile the program. After compilation, the page is kept in memory for certain duration to serve for next requests. Thus the compilation activity is not done for every request(unless there are modifications in the page).

ASP VS JSP

|Category |ASP |JSP |

|Platform Support |Windows only |All java enabled platforms |

|Type |Interpreted for every request |Compiled once executed again and again |

|Memory requirements |Loaded for each request |Loaded only once in memory |

|Web Server Support |IIS, PWS |Any web server – Apache, Netscape, IIS etc |

|Reusable objects |COM / DCOM |Java Beans, Servlets, EJB |

|Scripting Languages |VBScript, Java script |Java / Java script |

|Customizable tags |Cannot use custom tag libraries and is not |Extensible with custom tag libraries. |

| |extensible. | |

|Memory leak protection |No |Yes |

Servlets VS JSP

|Servlets |JSP |

|1. Servlets are less efficient in generating dynamic contents. |1. JSP offers a clear separation of static and dynamic contents. |

|2. Servlets files must be compiled by user. |2. JSP files are automatically compiled. |

|3. Developers need to have significant knowledge of Java. |3. Developers need not have significant knowledge of Java. |

|4. Management of beans is done using java code |4. Management of beans is done using tags. |

One.jsp

Hello.

Hello, !

( includes JSP/Java codes(Scriplet)

( includes variables

request ( Http request object

JSP Execution

When a server receives a request for JSP file, the request is sent to the JSP engine. The JSP engine checks whether it already exists in memory or not. If it doesn’t, then the engine compiles the JSP file into a special servlet file. The servlet is executed and the response object generated by it is sent to the client through the web server. Thus, when a JSP file is accessed for the first time, it requires some time to get the response. If the file is already present in the memory, then the engine checks whether the original JSP file is modified or not. If it is modified, then the JSP file is recompiled and executed. Otherwise it is just executed again. Thus JSP files are automatically recompiled, but pure servlet files should be explicitly recompiled.

Fig.

The JSP page class file extends HttpJspBase which in turn implements the Servlet interface. It contains 3 methods.

i. jspInit : performs the initialization of a servlet. This method can be overridden.

ii. _jspService: executed for every request.

iii. jspDestroy: gets executed when servlet is removed by the server. This method can be overridden.

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 similar to the ones in the handcoded servlet, 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. The two phases are illustrated in the following figure -

[pic]

[pic]

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.

JSP Access Model / JSP Architecture

These are based on the location at which the bulk of the request process is preformed.

1. Model 1 (Page – Centric Design)

Fig.

In this type, the incoming request from a web browser is sent directly to the JSP page, which is responsible for processing it & replaying back to the client. There is still separation of using beans. Although, Model 1 architecture is suitable for simple application, it may not be desirable for complex implementation. This architecture usually leads to significant amount of script-lets embedded within a JSP Page. This may cause problems for web developers who don’t know much about Java, but required to develop large websites. The other disadvantage of this architecture is that each JSP page is individually responsible for managing application state & verifying authentication & security.

2. Model 2 (Servlet-Centic Design)

[pic]

The Model-2 architecture is a server-side implementation of the popular MVC design pattern. Here the processing is divided between the presentation and front component. Presentation component are JSP pages that generate the HTML/XML response that determines the user interface when viewed by the browser. Front component controller do not handle any presentation issues, but process all the HTTP requests. Here, they are responsible for creating any beans or objects used by the presentation components, as well as deciding, depending on the users act which presentation components to forward the request to. Front components can be implemented as either a servlet or JSP page. The advantage of this architecture is that, there is no processing logic within the presentation component itself, it is simply responsible for retrieving any objects or beans that may have been previously created by the controller and extracting the dynamic content within for insertion within its static templates. This separation of roles and responsibilities of developers and page designers.

Another advantage of this approach is that the front component present a single point of entry into the application thus making the management of application state, security and presentation uniform and easier to maintain.

JSP Syntax Basics

1. Declarations

JSP Declarations let’s you define page level variables or methods. These are like variables or methods declared as class-level member. You can declare static or instance variables or methods. It is declared using .

For eg or

numsq.html

Enter Num :

numsq.jsp

Sq:

2. Expression

They are included . The results of evaluating the expression are converted to a string & directly included within the output page. These are used to display simple variables or return values of methods. For example or

3. Scriplets

JSP code fragments or scriplets are included in. The code declared within these tags goes into service method. It includes java code which is to be executed by the server. For example:-

You accessed this page for times

Click

Handling Exceptions

When you are creating an application using JSP, you need to make sure that your application handles the errors properly. There are 2 types of errors or exceptions that can generally occur –

1. Translation Time Errors

Since JSP pages are compiled automatically by Web server, translation errors can occur during the page compilation. This results in an internal server error ( Error Code 500). The specific error messages displayed as a translation time error which are sent and displayed on the browser.

2. RunTime Exceptions

These errors occur during the execution of a JSP page. Most of the times, it occurs because of invalid client input. Most of the rime, it results in a stack dump on the client side. In JSP, this can be avoided using error pages as shown below –

cal.jsp

arith.jsp

error.jsp

Forwards

This is similar to forwarding using RequestDispatcher.

Syntax

You can also specified parameters using tags

user.html

Name :

user.jsp

info.jsp

Hello,

Your pass is :

Including Beans

JSP allows programmers to make use of beans in them. It is a part of jsp action category. Actions allow programmers to specify how to forward pages, specify java applets, include beans etc. Actions support XML-based syntax. The syntax for including beans is as follows –

The main attributes are as follows –

i) id – specified name using which the bean can be accessed,

ii) class- specified java class name

iii) scope – specified scope (application /request/session/page)

To access the properties of bean, the syntax is as follows –

To set the properties of bean, the syntax is as follows –

Object Scope

JSP pages include java objects. These objects are either implicit or can be created by the user. These objects can be associated with a scope attribute defining the visibility of that object in different parts of JSP pages or through out the application. We have already studied that there are objects like ServletConext, request, session etc which can hold objects using setAttribute method. In this case, we first declare the objects and then specify where they should be added using scope.

You can define objects with following scope---

1) application :-( identifies objects accessible from pages that belong to the same application (Client independent). The objects with “application” scope are added into ServletContext.

2) session:-( identifies objects accessible from pages that belonging to the same session as the one in which they were created.(life of user session, multiple requests from same browser window). The objects with “session” scope are added intoHttpSession.

3) request:-( objects accessible from pages processing the request where they were created(before response is sent, accessible also in any included or forwarded pages). The objects with “request” scope are added into HttpServletRequest.

4) page :-(objects accessible only within pages where they were created.(current page until it is displayed or control is forwarded to new page). The objects with “page” scope are added into PageContext. PageContext object is used to store contextual information to be accessed in Tag-Handler classes which are written for custom tags written in JSP.

The scope of implicit objects is as follows----

Scope Implicit objects

1) application ----------( application

2) request ----------( request

3) page ----------( response, pageContext,

out, config, page, exception

4) session --------( session

Note :---(

1) All implicit objects are only visible within the system generated _jspService method. They are not visible within methods that you define yourself in declarations.

2) 4 JSP implicit objects(request, session, application, pageContext) have the ability to store and retrieve attribute names and values .These are used to share information among jsp and servlets.

i) setAttribute(String key,Object val)

ii) String [] getAttributeNames( )

iii) Object getAttribute(String key)

iv) removeAttribute(String key)

Bean Demo

It shows creation of bean and how values can be assigned to the properties of bean and then how they can be used. The program contains a data-entry form accepting roll, name and marks whose input is taken from two files.

Step 1 : Create a class called student, compile it and store the class file in classes folder.

student.java

public class student

{

private int roll;

private String name;

private float marks;

public student()

{

roll = 0;

name = "XYZ";

marks = 0;

}

public int getRoll()

{

return roll;

}

public void setRoll(int r)

{

if(r>0)

roll = r;

}

public String getName()

{

return name;

}

public void setName(String r)

{

name = r;

}

public float getMarks()

{

return marks;

}

public void setMarks(float f)

{

if(f>0)

marks = f;

}

}

Step 2 : Now you create HTML/JSP files.

s1.html

enter roll :

enter name :

s1.jsp

s2.jsp

Marks :

s3.jsp

Roll :

Name :

Marks :

Creating Custom Tags

Step 1 : Define Tag Library Descriptor(tld) file

This file contains the definition of new tags and their attributes. It also contains the names of tag handler classes which should be called on occurrence of these tags in JSP file.

web-inf \ mytags.tld

1.0

1.1

mytag

showtab

showtable

dsn

table

Step 2. Define JSP file

Then write the jsp file. To use the customs tags, it should include the tag library descriptor file which contains the definition of the tags which are written in JSP.

tables.jsp

Step 3. Write tag handler class

Now write the code of tag handler class. The tag handler class should implement Tag interface or should extends TagSupport class located in javax.servlet.jsp.tagext package. It contains setter methods for every attribute that is defined in the tag. The above example is of a tag that does not have body.

showtable.java

import java.io.*;

import java.sql.*;

import javax.servlet.jsp.*;

import javax.servlet.jsp.tagext.*;

public class showtable extends TagSupport

{

private String dsn,table;

public showtable()

{ super( ); }

public void setDsn(String d)

{ dsn = d; }

public void setTable(String d)

{ table = d; }

public int doEndTag()

{

try

{

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

Connection con = DriverManager.getConnection("jdbc:odbc:" + dsn);

Statement st = con.createStatement();

ResultSet rs = st.executeQuery("select * from " + table);

if(rs!=null)

{

JspWriter jspout = pageContext.getOut();

jspout.println(" Showing 1st column of " + table + "");

while(rs.next())

{

jspout.println(" " +rs.getString(1));

}

}

con.close();

}

catch(Exception e)

{

System.out.println(e);

}

return EVAL_PAGE;

}

}

Step 5. Compile tag handler class and execute the JSP file

................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download

To fulfill the demand for quickly locating and searching documents.

It is intelligent file search solution for home and business.

Literature Lottery