Top Banner
JSP Study Material 4 th CSE, 4 th IT Institute of Engineering & Management Prepared by : Sourav Mukherjee Copy Right : 2004-2005 1 Servlets Introduction The rise of server-side Java applications is one of the latest and most exciting trends in Java Programming. The java language was originally intended for use in small, embedded devices. Java’s potential as a server side development platform had been sadly overlooked until recently. Business in particular has been quick to recognize Java’s potential on the server-side. Java is inherently suited for large client/server applications. The cross platform nature of java extremely useful for organizations that have a heterogeneous collection of servers running various flavors of the Unix and Windows operating systems. Java’s modern, object-oriented, memory-protected design allows developers to cut development cycles and increase reliability. In addition, Java’s build – in support for networking and enterprise API’s provides access to legacy data, easing the transition form older client/server systems. Java servlets are a key component of server –side Java development. A servlets is a small pluggable extension to a server that server’s functionality. Servlets allow developers to extend and customize any java – enabled server a web server, a mail server, an application server or any custom server. Java Servlets A servlets is a generic server extension – a java class that can be loaded dynamically to expand the functionality of a server, Servlets are commonly used with web servers, where they can take place of CGI scripts. A servlets is similar to a proprietary server extension, Please purchase PDFcamp Printer on http://www.verypdf.com/ to remove this watermark.
47
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: jsp

JSP Study Material 4th CSE, 4th IT Institute of Engineering & Management

Prepared by : Sourav Mukherjee Copy Right : 2004-2005

1

Servlets Introduction The rise of server-side Java applications is one of the latest and most exciting

trends in Java Programming. The java language was originally intended for use

in small, embedded devices. Java’s potential as a server side development

platform had been sadly overlooked until recently.

Business in particular has been quick to recognize Java’s potential on

the server-side. Java is inherently suited for large client/server

applications. The cross platform nature of java extremely useful for

organizations that have a heterogeneous collection of servers running

various flavors of the Unix and Windows operating systems. Java’s

modern, object-oriented, memory-protected design allows developers

to cut development cycles and increase reliability. In addition, Java’s

build – in support for networking and enterprise API’s provides access

to legacy data, easing the transition form older client/server systems.

Java servlets are a key component of server –side Java development. A servlets

is a small pluggable extension to a server that server’s functionality. Servlets

allow developers to extend and customize any java – enabled server a web

server, a mail server, an application server or any custom server.

Java Servlets

A servlets is a generic server extension – a java class that can be

loaded dynamically to expand the functionality of a server, Servlets

are commonly used with web servers, where they can take place of

CGI scripts. A servlets is similar to a proprietary server extension,

Please purchase PDFcamp Printer on http://www.verypdf.com/ to remove this watermark.

Page 2: jsp

JSP Study Material 4th CSE, 4th IT Institute of Engineering & Management

Prepared by : Sourav Mukherjee Copy Right : 2004-2005

2

except that it runs in side a JVM on the server so it is safe and

portable. Servlets operate solely within the domain of the server:

unlike applets they do not require support for Java in the web browser.

Servlets are supported on all platform that support Java, and servlets work with

all major web servers. Java servlets, as defined by the Java Software division of

Sun Microsystems are the first standard extension to Java. This means that

servlets are officially blessed by Sun and are part of the Java language, but they

are not part of the core Java API.

To make it easy for you to develop servlets support. The javax.servlets and

javax.servlets.http package consistitute this servlets API.

In Addition to servlets class, you need a servlets engine, so that you can test and

deploy your servlets. The choice of the servlets engine depends partly on which

web server you are running. There are three kinds of servlets engines.

§ Standard Servlet Engine

§ Add-on Servlet engine.

§ Embeddable servlet engine

Standard Servlet Engine

A standalone engine is a server that includes build-in support for servlets Such

as engine has the advantage that everything works on Sun’s Java web Server,

Jigsaw Server, Netscapet Enterprise Server

Please purchase PDFcamp Printer on http://www.verypdf.com/ to remove this watermark.

Page 3: jsp

JSP Study Material 4th CSE, 4th IT Institute of Engineering & Management

Prepared by : Sourav Mukherjee Copy Right : 2004-2005

3

Add-on Servlet Engine

An add-on Servlet engine functions as a plug – in to an existing server –it adds

Servlet support for a server that was not originally designed with servlets in

mind. Add – on servlet engines include Java-Apache projects’s Jserv module,

Jrun, WebSphere application

Embeddable Servlet Engine

An embeddable servlet engine is generally a lightweight servlet deployment

platform that can be embedded in another application.

Power of Servlet

Till now we have portrayed servlets as an alternative to other dynamic web

content technology, but we have not really explained why think you should use

them. What makes servlets viable choice for web development ? We believe that

servlets offer a number of advantage over other approaches in the aspects

explained below.

Portability, power, Efficiency and Endurance, Safety, Elegance, Integration,

Extensibility and flexibility, Capable of running in Process, Compiled, Crash

Resistance, Dynamically loadable across the network, Multithreaded.

Please purchase PDFcamp Printer on http://www.verypdf.com/ to remove this watermark.

Page 4: jsp

JSP Study Material 4th CSE, 4th IT Institute of Engineering & Management

Prepared by : Sourav Mukherjee Copy Right : 2004-2005

4

Servlet Structure To start with it is important to notice that servlet are basic Java applications

similar to others you may have written. The only difference is that they extend

new classes and implement some unfamiliar methods. Fortunately, servlets are

as simple to write as any other Java program. You just have to learn the servlet

structure and a new class library.

Particularly all servlets that perform some useful function have two things in

common.

1. First, they all extend one of two servlet classes -> GeneracServlet or

HttpServlet. Extending these classes provides a framework for creating a

servlet as well as significant default functionality.

2. Second all servlets override at least one method wherein custom

functionality is implemented. The method that is automatically called by

the server in response to a client request is called is service(). The method

may be overridden to provide custom functionality. However, if the

servlet developer chooses not to override the service() method, other

methods will be invoked in response to a client request.

In addition to the classes and methods mentioned above, there are tow other

methods that are implemented by most servlets->init() and destroy(). The init()

method is called a single time when the servlet is first loaded. It is similar to c

class constructor in that it provided a method wherein initialization code is

Please purchase PDFcamp Printer on http://www.verypdf.com/ to remove this watermark.

Page 5: jsp

JSP Study Material 4th CSE, 4th IT Institute of Engineering & Management

Prepared by : Sourav Mukherjee Copy Right : 2004-2005

5

guaranteed to be run. The destroy() method is executed when the servlet is

unloaded. It is used to free any resources held by the servlet.

Here is a skeleton structure of any Servlet Public class SkeleServ extends HttpServlet{ Public void init(){ //initialization code goes here } public void service(){ //meaningful work happens here } public void destroy(){ //free resources here } } The SkeleServ given does not look too difficult. Of course, the actual

implementation of different servlets may very widely. For example, servlet may

or may not implement the init() or destroy() methods. Implementation of these

methods is not mandatory. Likewise, a servlet developer may choose not to

override the service() method and opt to implement another method that is

automatically called by the inherited service() method. Similar to service(), this

method would implement the servlet’s unique functionality. The method

automatically called service() depends upon the type of HTTP request received (

e.g. doGet() is called for GET requests and doPost() for POST requests)

Life Cycle for Servlet

The review the process by which a server invokes a servlet. This process can be

broken in to nine steps as following.

Please purchase PDFcamp Printer on http://www.verypdf.com/ to remove this watermark.

Page 6: jsp

JSP Study Material 4th CSE, 4th IT Institute of Engineering & Management

Prepared by : Sourav Mukherjee Copy Right : 2004-2005

6

i. The server loads the servlet when it is first request by the client or it

configured to do so, at server start-up. The servlet may be loaded from

either a local or remote location using the standard Java class loading

facility.

ii. The server creates one or more instances of the servlet class. Depending

on implementation. The server may create a single instances from which

one is chosen to service each new request.

iii. The server constructs a ServletConfig object that provides initialization

information to the servlet.

iv. The server calls the servlets init() method, passing the object constructed

in the step 3 as a parameter. The init() method is guaranteed to finish

execution prior to the servlet processing the first request. If the server has

created multiple servlet instances( step 2), the init() method is called one

time for each instance.

v. The server constructs a ServletRequest or HttpServletRequest object from

the data included in the client’s request. It also constructs a

ServletRespopnse or HttpServletResponse object that provides methods

for customizing the server’s response. The type of object passed in these

two parameters depends on whether the servlet extends the

GenericServelt class or the HttpServlet class, respectively.

vi. The server calls the servlet’s service() method ( or other, more specific

method like doGet() or doPost() for HTTP servlets), passing the objects

constructed in step 5 as parameter. When concurrent request arrive

multiple service() methods can run in separate threads.

vii. The service() method process the client request by evaluating the

ServletRequest or HttpServletRequest object and responds using

ServletResponse or HttpServletResponse object.

viii. If the server receives another request for this servlet, the process begins

again at step 5.

Please purchase PDFcamp Printer on http://www.verypdf.com/ to remove this watermark.

Page 7: jsp

JSP Study Material 4th CSE, 4th IT Institute of Engineering & Management

Prepared by : Sourav Mukherjee Copy Right : 2004-2005

7

ix. When instructed to unload the servlet, perhaps by the server

administrator or programmatically by the servlet itself, the server calls the

servlet itself, the server calls the servlet’s destroy() method. The servlet is

then eligible for garbage collection.

Introduction to JSP JavaServer Pages (JSP) is a technology based on the Java language and enables

the development of dynamic web sites. JSP was developed by Sun Microsystems

to allow server side development. JSP files are HTML files with special Tags

containing Java source code that provide the dynamic content.

The following shows the Typical Web server, different clients connecting via the

Internet to a Web server. In this example, the Web server is running on Unix and

is the very popular Apache Web server.

First static web pages were displayed. Typically these were people’s first

experience with making web pages so consisted of My Home Page sites and

company marketing information. Afterwards Perl and C were languages used on

the web server to provide dynamic content. Soon most languages including

Visualbasic, Delphi, C++ and Java could be used to write applications that

Please purchase PDFcamp Printer on http://www.verypdf.com/ to remove this watermark.

Page 8: jsp

JSP Study Material 4th CSE, 4th IT Institute of Engineering & Management

Prepared by : Sourav Mukherjee Copy Right : 2004-2005

8

provided dynamic content using data from text files or database requests. These

were known as CGI server side applications. ASP was developed by Microsoft to

allow HTML developers to easily provide dynamic content supported as

standard by Microsoft’s free Web Server, Internet Information Server (IIS). JSP is

the equivalent from Sun Microsystems, a comparison of ASP and JSP will be

presented in the following section.

The following diagram shows a web server that supports JSP files. Notice that

the web server also is connected to a database.

JSP source code runs on the web server in the JSP Servlet Engine. The JSP Servlet

engine dynamically generates the HTML and sends the HTML output to the client’s web

browser.

Why use JSP? JSP is easy to learn and allows developers to quickly produce web sites and

applications in an open and standard way. JSP is based on Java, an objectoriented

language. JSP offers a robust platform for web development.

Main reasons to use JSP:

Please purchase PDFcamp Printer on http://www.verypdf.com/ to remove this watermark.

Page 9: jsp

JSP Study Material 4th CSE, 4th IT Institute of Engineering & Management

Prepared by : Sourav Mukherjee Copy Right : 2004-2005

9

1. Multi platform

2. Component reuse by using Javabeans and EJB.

3. Advantages of Java.

You can take one JSP file and move it to another platform, web server or JSP Servlet engine.

HTML and graphics displayed on the web browser are classed as the

presentation layer. The Java code (JSP) on the server is classed as the

implementation. By having a separation of presentation and implementation,

web designers work only on the presentation and Java developers concentrate on

implementing the application.

JSP compared to ASP

JSP and ASP are fairly similar in the functionality that they provide. JSP may

have slightly higher learning curve. Both allow embedded code in an HTML

page, session variables and database access and manipulation. Whereas ASP is

mostly found on Microsoft platforms i.e. NT, JSP can operate on any platform

Please purchase PDFcamp Printer on http://www.verypdf.com/ to remove this watermark.

Page 10: jsp

JSP Study Material 4th CSE, 4th IT Institute of Engineering & Management

Prepared by : Sourav Mukherjee Copy Right : 2004-2005

10

that conforms to the J2EE specification. JSP allow component reuse by using

Javabeans and EJBs. ASP provides the use of COM / ActiveX controls.

JSP compared to Servlets A Servlet is a Java class that provides special server side service. It is hard work to write

HTML code in Servlets. In Servlets you need to have lots of println statements to

generate HTML.

JSP architecture

JSPs are built on top of SUN’s servlet technology. JSPs are essential an HTML

page with special JSP tags embedded. These JSP tags can contain Java code. The

JSP file extension is .jsp rather than .htm or .html. The JSP engine parses the .jsp

and creates a Java servlet source file. It then compiles the source file into a class

file, this is done the first time and this why the JSP is probably slower the first

time it is accessed. Any time after this the special compiled servlet is executed

and is therefore returns faster.

Please purchase PDFcamp Printer on http://www.verypdf.com/ to remove this watermark.

Page 11: jsp

JSP Study Material 4th CSE, 4th IT Institute of Engineering & Management

Prepared by : Sourav Mukherjee Copy Right : 2004-2005

11

Steps required for a JSP request: 1. The user goes to a web site made using JSP. The user goes to a JSP page

(ending with .jsp). The web browser makes the request via the Internet.

2. The JSP request gets sent to the Web server.

3. The Web server recognises that the file required is special (.jsp), therefore

passes the JSP file to the JSP Servlet Engine.

4. If the JSP file has been called the first time, the JSP file is parsed,

otherwise go to step 7.

5. The next step is to generate a special Servlet from the JSP file. All the

Please purchase PDFcamp Printer on http://www.verypdf.com/ to remove this watermark.

Page 12: jsp

JSP Study Material 4th CSE, 4th IT Institute of Engineering & Management

Prepared by : Sourav Mukherjee Copy Right : 2004-2005

12

HTML required is converted to println statements.

6. The Servlet source code is compiled into a class.

7. The Servlet is instantiated, calling the init and service methods.

8. HTML from the Servlet output is sent via the Internet.

9. HTML results are displayed on the user’s web browser.

Generate Implementation class and the JSP life cycle & methods The servlet class generated at the end of the tranlation process must extend a

super class that is either:

§ Specified by the JSP author through the use of the extends attribute in the

page directive as we shall see in a while, or

§ Is a JSP container specific implementation class that implements

javax.servlet.jsp.JspPage interface and provides some basic page specific

behavior. (Since most JSP pages are use HTTP their implementation

classes must actually implement the javax.servlet.jsp.JspPage.)

The javax.servlet.jsp.JspPage interface contains 2 methods: Method Usage Public void jspInit() This is invoked when the JSP is

initialized. This is similier to the init() method is servlets. Page authods are free to provide initialization of the JSP by implementing this method in their JSPs

Public void jspDestroy() This is invoked when the JSP is about to be destroyed by the container. This is similar to the destroy() method in servlets/constructor. Page authors are

Please purchase PDFcamp Printer on http://www.verypdf.com/ to remove this watermark.

Page 13: jsp

JSP Study Material 4th CSE, 4th IT Institute of Engineering & Management

Prepared by : Sourav Mukherjee Copy Right : 2004-2005

13

free to provide cleanup of the JSP by implementing this method is their JSPs.

The javax.servlet.jsp.HttpJspPage interface contains 1 method. Method Usage Public void _jspService( HttpServletRequest Request, HttpServletResponse) throws ServletException, IOException

This method corresponds to the body of the JSP page and is used to threaded request processing, just like the service() method in servlets. This implementing for this method is generated by the JSP container and should never be provided by page authors.

How these 3 methods work together in a JSP can be seen in the figure below, which summarized the 3 mojor life events in a JSP.

§ The page is initialized by invoking the jspInit() method, which may be

user defined. This initializes the JSP much in the same way as servlets

are initialized.

Initialize Public void jspInit()

Handle client requests and generate response Void _jspService(ServletRequest, ServletReaponse) throws

IOException, ServletException

Destroy Public void jspDestroy()

Please purchase PDFcamp Printer on http://www.verypdf.com/ to remove this watermark.

Page 14: jsp

JSP Study Material 4th CSE, 4th IT Institute of Engineering & Management

Prepared by : Sourav Mukherjee Copy Right : 2004-2005

14

§ Every time a request comes to the JSP, the container generated

_jspService() method is invoked, the request is processed and the JSP

generates the appropriate reaponse. This response is taken by the

container and passed back to the client.

§ When the JSP is destroyed by the server( for example at shutdown),

the jsp_destroy() method, which can be user defined, is invoked to

platform and clean up.

Creating your first JSP page <html> <head> <title>My first JSP page </title> </head> <body> <%@ page language=”java” %> <% System.out.println(“Hello World”); %> </body> </html> Type the code above into a text file. Name the file helloworld.jsp. Place this in the correct directory on your JSP web server and call it via your browser. Using JSP tags There are four main tags:

1. Declaration tag

2. Expression tag

3. Directive Tag

4. Scriptlet tag

5. Action tag

Please purchase PDFcamp Printer on http://www.verypdf.com/ to remove this watermark.

Page 15: jsp

JSP Study Material 4th CSE, 4th IT Institute of Engineering & Management

Prepared by : Sourav Mukherjee Copy Right : 2004-2005

15

Declaration tag ( <%! %> )

This tag allows the developer to declare variables or methods.

Before the declaration you must have <%!

At the end of the declaration, the developer must have %>

Code placed in this tag must end in a semicolon ( ; ).

Declarations do not generate output so are used with JSP expressions or

scriptlets.

For Example,

<%!

private int counter = 0 ;

private String get Account ( int accountNo) ;

%>

The JSP you write turns into a class definition. All the scriptlets you write are

placed inside a single method of this class.

You can also add variable and method declarations to this class. You can then

use these variables and methods from your scriptlets and expressions.

To add a declaration, you must use the <%! and %> sequences to enclose your

declarations, as shown below.

<%@ page import="java.util.*" %>

<HTML>

<BODY>

<%!

Please purchase PDFcamp Printer on http://www.verypdf.com/ to remove this watermark.

Page 16: jsp

JSP Study Material 4th CSE, 4th IT Institute of Engineering & Management

Prepared by : Sourav Mukherjee Copy Right : 2004-2005

16

Date theDate = new Date();

Date getDate()

{

System.out.println( "In getDate() method" );

return theDate;

}

%>

Hello! The time is now <%= getDate() %>

</BODY>

</HTML>

The example has been created a little contrived, to show variable and method

declarations.

Here we are declaring a Date variable theDate, and the method getDate. Both of

these are available now in our scriptlets and expressions.

But this example no longer works! The date will be the same, no matter how

often you reload the page. This is because these are declarations, and will only

be evaluated once when the page is loaded! (Just as if you were creating a class

and had variable initialization declared in it.)

Exercise: Modify the above example to add another function computeDate which

re-initializes theDate. Add a scriptlet that calls computeDate each time.

Note: Now that you know how to do this -- it is in general not a good idea to use

variables as shown here. The JSP usually will run as multiple threads of one

single instance. Different threads would interfere with variable access, because it

will be the same variable for all of them. If you do have to use variables in JSP,

you should use synchronized access, but that hurts the performance. In general,

any data you need should go either in the session objet or the request objectc

Please purchase PDFcamp Printer on http://www.verypdf.com/ to remove this watermark.

Page 17: jsp

JSP Study Material 4th CSE, 4th IT Institute of Engineering & Management

Prepared by : Sourav Mukherjee Copy Right : 2004-2005

17

(these are introduced a little later) if passing data between different JSP pages.

Variables you declare inside scriptlets are fine, e.g. <% int i = 45; %> because

these are declared inside the local scope and are not shared.

Expression tag ( <%= %>) This tag allows the developer to embed any Java expression and is short for

out.println().

A semicolon ( ; ) does not appear at the end of the code inside the tag.

For example, to show the current date and time.

Date : <%= new java.util.Date() %>

Directive tag ( <%@ directive … %>)

We have been fully qualifying the java.util.Date in the examples in the previous

sections. Perhaps you wondered why we don't just import java.util.*;

It is possible to use "import" statements in JSPs, but the syntax is a little different

from normal Java. Try the following example:

<%@ page import="java.util.*" %>

<HTML>

<BODY>

<%

System.out.println( "Evaluating date now" );

Date date = new Date();

%>

Hello! The time is now <%= date %>

</BODY>

</HTML>

Please purchase PDFcamp Printer on http://www.verypdf.com/ to remove this watermark.

Page 18: jsp

JSP Study Material 4th CSE, 4th IT Institute of Engineering & Management

Prepared by : Sourav Mukherjee Copy Right : 2004-2005

18

The first line in the above example is called a "directive". A JSP "directive" starts

with <%@ characters.

This one is a "page directive". The page directive can contain the list of all

imported packages. To import more than one item, separate the package names

by commas, e.g.

<%@ page import="java.util.*,java.text.*" %>

There are a number of JSP directives, besides the page directive. Besides the

page directives, the other most useful directives are include and taglib. We will

be covering taglib separately.

The include directive is used to physically include the contents of another file.

The included file can be HTML or JSP or anything else -- the result is as if the

original JSP file actually contained the included text. To see this directive in

action, create a new JSP

<HTML>

<BODY>

Going to include hello.jsp...<BR>

<%@ include file="hello.jsp" %>

</BODY>

</HTML>

View this JSP in your browser, and you will see your original hello.jsp get

included in the new JSP.

Exercise: Modify all your earlier exercises to import the java.util packages.

A JSP directive gives special information about the page to the JSP Engine.

Please purchase PDFcamp Printer on http://www.verypdf.com/ to remove this watermark.

Page 19: jsp

JSP Study Material 4th CSE, 4th IT Institute of Engineering & Management

Prepared by : Sourav Mukherjee Copy Right : 2004-2005

19

There are three main types of directives:

1) page – processing information for this page.

2) Include – files to be included.

3) Tag library – tag library to be used in this page.

Directives do not produce any visible output when the page is requested but

change the way the JSP Engine processes the page.

For example, you can make session data unavailable to a page by setting a page

directive (session) to false.

1. Page directive This directive has 11 optional attributes that provide the JSP Engine with special

processing information. The following table lists the 11 different attributes with a

brief description:

<%@ page attributes %>

Attribute Description Default Value

Language Defines the scripting language to be used.

This attribute exists in case future JSP

containers support multiple language

Java

Extends The value is a fully qualified class name of

the superclass that the generated class, into

which this JSP page is translated, must

Ommited by

default

Please purchase PDFcamp Printer on http://www.verypdf.com/ to remove this watermark.

Page 20: jsp

JSP Study Material 4th CSE, 4th IT Institute of Engineering & Management

Prepared by : Sourav Mukherjee Copy Right : 2004-2005

20

extend.

Import Comma separated list of packages or classes

with the same meaning as import statements

in Java Class

Ommited by

default

Session Specifies whether the page participates in an

HTTP session. When true the implicit object

named session, which refers to the

javax.servlet.http.HttpSession, is available

and can be used to access the current/new

session for the page

If false, the page does not participate in a

session and implicit session object is

unavailable.

Buffer Specifies the buffering model for the output

stream to the client

If the value is none, no buffering occurs and

all output is written directlythrough to the

ServletResponse by a PrinterWriter.

If a buffer size is specified, output is buffered

with a buffer size not less than that value.

Implementation

– dependent; at

least 8kb

Auto Flush If true, the output buffer to the client is

flushed automatically when it is full.

If false, a runtime exception is raised to

indicate a buffer overflow.

true

IsThreadSafe Defines the lavel of thread safely

implemented in the page.

True

Info Defines an informative string that can

subsequently be obtained from the page’s

Ommited by

default

Please purchase PDFcamp Printer on http://www.verypdf.com/ to remove this watermark.

Page 21: jsp

JSP Study Material 4th CSE, 4th IT Institute of Engineering & Management

Prepared by : Sourav Mukherjee Copy Right : 2004-2005

21

implementation of the

Servlet.getServletInfo() method.

Error page Defines a URL to another JSP page within

current web application, which is invoked if

a checked or unchecked exception is thrown.

The page implementation catches the

instance of the Throwable object and passes

it to the error page processing. The error

page mechanism is very useful, and avoids

the need for developers to write code to

catch unrecoverable exception in the JSP

pages.

Ommited by

default

Is Error Apge Indicates if the current JSP page is intended

to be another JSP pages’ error page

False

Content Type Defines the character encoding for the JSP

and the MIME type for the response of the

JSP page.

MIME Type is

text/html

2. Include directive

Allows a JSP developer to include contents of a file inside another. Typically

include files are used for navigation, tables, headers and footers that are common

to multiple pages.

Two examples of using include files:

This includes the html from privacy.html found in the include directory into the

current jsp page.

<%@ include file = “include/privacy.html %>

or to include a naviagation menu (jsp file) found in the current directory.

<%@ include file = “navigation.jsp %>

Please purchase PDFcamp Printer on http://www.verypdf.com/ to remove this watermark.

Page 22: jsp

JSP Study Material 4th CSE, 4th IT Institute of Engineering & Management

Prepared by : Sourav Mukherjee Copy Right : 2004-2005

22

Include files are discussed in more detail in the later sections of this tutorial.

3. Tag Lib directive

A tag lib is a collection of custom tags that can be used by the page.

<%@ taglib uri = “tag library URI” prefix = “tag Prefix” %>

Custom tags were introduced in JSP 1.1 and allow JSP developers to hide

complex

server side code from web designers.

This topic will be covered in the Advanced JSP tutorial at visualbuilder.com

Scriptlet tag ( <% … %> )

Between <% and %> tags, any valid Java code is called a Scriptlet. This code can

access any variable or bean declared.

For example, to print a variable.

<%

String username = “visualbuilder” ;

out.println ( username ) ;

%>

Scriptlets We have already seen how to embed Java expressions in JSP pages by putting

them between the <%= and %> character sequences.

But it is difficult to do much programming just by putting Java expressions

inside HTML.

JSP also allows you to write blocks of Java code inside the JSP. You do this by

placing your Java code between <% and %> characters (just like expressions, but

without the = sign at the start of the sequence.)

Please purchase PDFcamp Printer on http://www.verypdf.com/ to remove this watermark.

Page 23: jsp

JSP Study Material 4th CSE, 4th IT Institute of Engineering & Management

Prepared by : Sourav Mukherjee Copy Right : 2004-2005

23

This block of code is known as a "scriptlet". By itself, a scriptlet doesn't

contribute any HTML (though it can, as we will see down below.) A scriptlet

contains Java code that is executed every time the JSP is invoked.

Here is a modified version of our JSP from previous section, adding in a scriptlet.

<HTML>

<BODY>

<%

// This is a scriptlet. Notice that the "date"

// variable we declare here is available in the

// embedded expression later on.

System.out.println( "Evaluating date now" );

java.util.Date date = new java.util.Date();

%>

Hello! The time is now <%= date %>

</BODY>

</HTML>

If you run the above example, you will notice the output from the

"System.out.println" on the server log. This is a convenient way to do simple

debugging (some servers also have techniques of debugging the JSP in the IDE.

See your server's documentation to see if it offers such a technique.)

By itself a scriptlet does not generate HTML. If a scriptlet wants to generate

HTML, it can use a variable called "out". This variable does not need to be

declared. It is already predefined for scriptlets, along with some other variables.

The following example shows how the scriptlet can generate HTML output.

<HTML>

<BODY>

<%

// This scriptlet declares and initializes "date"

System.out.println( "Evaluating date now" );

Please purchase PDFcamp Printer on http://www.verypdf.com/ to remove this watermark.

Page 24: jsp

JSP Study Material 4th CSE, 4th IT Institute of Engineering & Management

Prepared by : Sourav Mukherjee Copy Right : 2004-2005

24

java.util.Date date = new java.util.Date();

%>

Hello! The time is now

<%

// This scriptlet generates HTML output

out.println( String.valueOf( date ));

%>

</BODY>

</HTML>

Here, instead of using an expression, we are generating the HTML directly by

printing to the "out" variable. The "out" variable is of type

javax.servlet.jsp.JspWriter.

Another very useful pre-defined variable is "request". It is of type

javax.servlet.http.HttpServletRequest

A "request" in server-side processing refers to the transaction between a browser

and the server. When someone clicks or enters a URL, the browser sends a

"request" to the server for that URL, and shows the data returned. As a part of

this "request", various data is available, including the file the browser wants from

the server, and if the request is coming from pressing a SUBMIT button, the

information the user has entered in the form fields.

The JSP "request" variable is used to obtain information from the request as sent

by the browser. For instance, you can find out the name of the client's host (if

available, otherwise the IP address will be returned.) Let us modify the code as

shown:

<HTML>

<BODY>

<%

// This scriptlet declares and initializes "date"

System.out.println( "Evaluating date now" );

Please purchase PDFcamp Printer on http://www.verypdf.com/ to remove this watermark.

Page 25: jsp

JSP Study Material 4th CSE, 4th IT Institute of Engineering & Management

Prepared by : Sourav Mukherjee Copy Right : 2004-2005

25

java.util.Date date = new java.util.Date();

%>

Hello! The time is now

<%

out.println( date );

out.println( "<BR>Your machine's address is " );

out.println( request.getRemoteHost());

%>

</BODY>

</HTML>

A similar variable is "response". This can be used to affect the response being

sent to the browser. For instance, you can call response.sendRedirect(

anotherUrl ); to send a response to the browser that it should load a different

URL. This response will actualy go all the way to the browser. The browser will

then send a different request, to "anotherUrl". This is a little different from some

other JSP mechanisms we will come across, for including another page or

forwarding the browser to another page.

Mixing Scriptlets and HTML We have already seen how to use the "out" variable to generate HTML output

from within a scriptlet. For more complicated HTML, using the out variable all

the time loses some of the advantages of JSP programming. It is simpler to mix

scriptlets and HTML.

Suppose you have to generate a table in HTML. This is a common operation,

and you may want to generate a table from a SQL table, or from the lines of a

file. But to keep our example simple, we will generate a table containing the

numbers from 1 to N. Not very useful, but it will show you the technique.

Here is the JSP fragment to do it:

Please purchase PDFcamp Printer on http://www.verypdf.com/ to remove this watermark.

Page 26: jsp

JSP Study Material 4th CSE, 4th IT Institute of Engineering & Management

Prepared by : Sourav Mukherjee Copy Right : 2004-2005

26

<TABLE BORDER=2>

<%

for ( int i = 0; i < n; i++ ) {

%>

<TR>

<TD>Number</TD>

<TD><%= i+1 %></TD>

</TR>

<%

}

%>

</TABLE>

You would have to supply an int variable "n" before it will work, and then it will

output a simple table with "n" rows.

The important things to notice are how the %> and <% characters appear in the

middle of the "for" loop, to let you drop back into HTML and then to come back

to the scriptlet.

The concepts are simple here -- as you can see, you can drop out of the scriptlets,

write normal HTML, and get back into the scriptlet. Any control expressions

such as a "while" or a "for" loop or an "if" expression will control the HTML also.

If the HTML is inside a loop, it will be emitted once for each iteration of the loop.

Another example of mixing scriptlets and HTML is shown below -- here it is

assumed that there is a boolean variable named "hello" available. If you set it to

true, you will see one output, if you set it to false, you will see another output.

<%

Please purchase PDFcamp Printer on http://www.verypdf.com/ to remove this watermark.

Page 27: jsp

JSP Study Material 4th CSE, 4th IT Institute of Engineering & Management

Prepared by : Sourav Mukherjee Copy Right : 2004-2005

27

if ( hello ) {

%>

<P>Hello, world

<%

} else {

%>

<P>Goodbye, world

<%

}

%>

It is a little difficult to keep track of all open braces and scriptlet start and ends,

but with a little practice and some good formatting discipline, you will acquire

competence in doing it.

Action tag

There are three main roles of action tags :

1) enable the use of server side Javabeans

2) transfer control between pages

3) browser independent support for applets.

Javabeans A Javabean is a special type of class that has a number of methods. The JSP page

can call these methods so can leave most of the code in these Javabeans. For

example, if you wanted to make a feedback form that automatically sent out an

email. By having a JSP page with a form, when the visitor presses the submit

button this sends the details to a Javabean that sends out the email. This way

there would be no code in the JSP page dealing with sending emails (JavaMail

API) and your Javabean could be used in another page (promoting reuse).

Please purchase PDFcamp Printer on http://www.verypdf.com/ to remove this watermark.

Page 28: jsp

JSP Study Material 4th CSE, 4th IT Institute of Engineering & Management

Prepared by : Sourav Mukherjee Copy Right : 2004-2005

28

To use a Javabean in a JSP page use the following syntax:

<jsp : usebean id = “ …. “ scope = “application” class = “com…” />

The following is a list of Javabean scopes:

page – valid until page completes.

request – bean instance lasts for the client request

session – bean lasts for the client session.

application – bean instance created and lasts until application ends.

Beans and Form processing

Forms are a very common method of interactions in web sites. JSP makes forms

processing specially easy.

The standard way of handling forms in JSP is to define a "bean". This is not a full

Java bean. You just need to define a class that has a field corresponding to each

field in the form. The class fields must have "setters" that match the names of the

form fields. For instance, let us modify our GetName.html to also collect email

address and age.

The new version of GetName.html is

<HTML>

<BODY>

<FORM METHOD=POST ACTION="SaveName.jsp">

What's your name? <INPUT TYPE=TEXT NAME=username SIZE=20><BR>

What's your e-mail address? <INPUT TYPE=TEXT NAME=email SIZE=20><BR>

What's your age? <INPUT TYPE=TEXT NAME=age SIZE=4>

<P><INPUT TYPE=SUBMIT>

Please purchase PDFcamp Printer on http://www.verypdf.com/ to remove this watermark.

Page 29: jsp

JSP Study Material 4th CSE, 4th IT Institute of Engineering & Management

Prepared by : Sourav Mukherjee Copy Right : 2004-2005

29

</FORM>

</BODY>

</HTML>

To collect this data, we define a Java class with fields "username", "email" and "age"

and we provide setter methods "setUsername", "setEmail" and "setAge", as shown. A

"setter" method is just a method that starts with "set" followed by the name of the field.

The first character of the field name is upper-cased. So if the field is "email", its "setter"

method will be "setEmail". Getter methods are defined similarly, with "get" instead of

"set". Note that the setters (and getters) must be public.

public class UserData {

String username;

String email;

int age;

public void setUsername( String value ) { username = value; } public void setEmail( String value ) { email = value; } public void setAge( int value ) { age = value; } public String getUsername() { return username; } public String getEmail() { return email; } public int getAge() { return age; } }

Please purchase PDFcamp Printer on http://www.verypdf.com/ to remove this watermark.

Page 30: jsp

JSP Study Material 4th CSE, 4th IT Institute of Engineering & Management

Prepared by : Sourav Mukherjee Copy Right : 2004-2005

30

The method names must be exactly as shown. Once you have defined the class,

compile it and make sure it is available in the web-server's classpath. The server

may also define special folders where you can place bean classes, e.g. with Blazix

you can place them in the "classes" folder. If you have to change the classpath,

the web-server would need to be stopped and restarted if it is already running.

(If you are not familiar with setting/changing classpath,.)

Now let us change "SaveName.jsp" to use a bean to collect the data.

<jsp:useBean id="user" class="UserData" scope="session"/>

<jsp:setProperty name="user" property="*"/>

<HTML>

<BODY>

<A HREF="NextPage.jsp">Continue</A>

</BODY>

</HTML>

All we need to do now is to add the jsp:useBean tag and the jsp:setProperty tag!

The useBean tag will look for an instance of the "UserData" in the session. If the

instance is already there, it will update the old instance. Otherwise, it will create

a new instance of UserData (the instance of the UserData is called a bean), and

put it in the session.

The setProperty tag will automatically collect the input data, match names

against the bean method names, and place the data in the bean!

Let us modify NextPage.jsp to retrieve the data from bean..

<jsp:useBean id="user" class="UserData" scope="session"/>

<HTML>

<BODY>

You entered<BR>

Name: <%= user.getUsername() %><BR>

Email: <%= user.getEmail() %><BR>

Age: <%= user.getAge() %><BR>

Please purchase PDFcamp Printer on http://www.verypdf.com/ to remove this watermark.

Page 31: jsp

JSP Study Material 4th CSE, 4th IT Institute of Engineering & Management

Prepared by : Sourav Mukherjee Copy Right : 2004-2005

31

</BODY>

</HTML>

Notice that the same useBean tag is repeated. The bean is available as the

variable named "user" of class "UserData". The data entered by the user is all

collected in the bean.

We do not actually need the "SaveName.jsp", the target of GetName.html could

have been NextPage.jsp, and the data would still be available the same way as

long as we added a jsp:setProperty tag. But in the next tutorial, we will actually

use SaveName.jsp as an error handler that automatically forwards the request to

NextPage.jsp, or asks the user to correct the erroneous data.

Creating your second JSP page For the second example, we will make use of the different tags we have learnt.

This example will declare two variables; one string used to stored the name of a

website and an integer called counter that displays the number of times the page

has been accessed. There is also a private method declared to increment the

counter. The website name and counter value are displayed.

<HTML>

<HEAD>

<TITLE> JSP Example 2</TITLE>

</HEAD>

<BODY> JSP Example 2

<BR>

<%!

String sitename = “iemcal.com”;

int counter = 0;

private void increment Counter()

Please purchase PDFcamp Printer on http://www.verypdf.com/ to remove this watermark.

Page 32: jsp

JSP Study Material 4th CSE, 4th IT Institute of Engineering & Management

Prepared by : Sourav Mukherjee Copy Right : 2004-2005

32

{

counter ++;

}

%>

Website of the day is

<%= sitename %>

<BR>

page accessed

<%= counter %>

</BODY>

</HTML> Tag libraries JSP 1.1 introduces a method of extending JSP tags, called "tag libraries". These libraries

allow addition of tags similar to jsp:include or jsp:forward, but with different prefixes

other than jsp: and with additional features.

To introduce you to tag libraries, in this tutorial we use the Blazix tag library as an

example. This tag library comes bundled with the Blazix server, which you can

download free for learning and evaluation. (The material you learn about using tag

libraries will work with any other tag libraries also.)

Each tag-library will have its own tag-library specific documentation. In order to use the

tag library, you use the "taglib" directive to specify where your tag library's "description"

resides. For the Blazix tag library, the (recommended) directive is as follows

<%@ taglib prefix="blx" uri="/blx.tld" %>

The "uri" specifies where to find the tag library description. The "prefix" is unique for

the tag library. This directive is saying that we will be using the tags in this library by

starting them with blx:

Please purchase PDFcamp Printer on http://www.verypdf.com/ to remove this watermark.

Page 33: jsp

JSP Study Material 4th CSE, 4th IT Institute of Engineering & Management

Prepared by : Sourav Mukherjee Copy Right : 2004-2005

33

The Blazix tag library provides a blx:getProperty tag. This tag can be used to allow the

user to edit form data. In our GetName.jsp file, we will now add a jsp:useBean and place

the form inside blx:getProperty.

The new GetName.jsp is

<%@ taglib prefix="blx" uri="/blx.tld" %>

<jsp:useBean id="user" class="UserData" scope="session"/>

<HTML>

<BODY>

<blx:getProperty name="user" property="*">

<FORM METHOD=POST ACTION="SaveName.jsp">

What's your name? <INPUT TYPE=TEXT NAME=username SIZE=20><BR>

What's your e-mail address? <INPUT TYPE=TEXT NAME=email SIZE=20><BR>

What's your age? <INPUT TYPE=TEXT NAME=age SIZE=4>

<P><INPUT TYPE=SUBMIT>

</FORM>

</blx:getProperty>

</BODY>

</HTML>

Note that the blx:getProperty doesn't end with /> but is instead terminated by a separate

</blx:getProperty> line. This puts all the form input fields inside the blx:getProperty so

they can be appropriately modified by the tag library.

Try putting a link to GetName.jsp from the NextPage.jsp, and you will see that the bean's

data shows up automatically in the input fields.

The user can now edit the data.

We still have a couple of problems. The user cannot clear out the name field. Moreover,

if the user enters a bad item in the "age" field, something which is not a valid integer, a

Java exception occurs.

Please purchase PDFcamp Printer on http://www.verypdf.com/ to remove this watermark.

Page 34: jsp

JSP Study Material 4th CSE, 4th IT Institute of Engineering & Management

Prepared by : Sourav Mukherjee Copy Right : 2004-2005

34

We will use another tag from the Blazix tag library to take care of this. Blazix offers a

blx:setProperty tag that can be used to take care of these problems. blx:setProperty

allows us to define an exception handler method. If an exception occurs, we can collect

an error message for the user and continue processing.

Following is a version of SaveName.jsp that processes any errors, and either shows the

user GetName.jsp again to user can enter the data correctly, or automatically forwards to

NextPage.jsp.

<%@ taglib prefix="blx" uri="/blx.tld" %>

<%!

boolean haveError;

StringBuffer errors;

public void errorHandler( String field,

String value,

Exception ex )

{

haveError = true;

if ( errors == null )

errors = new StringBuffer();

else

errors.append( "<P>" );

errors.append( "<P>Value for field \"" +

field + "\" is invalid." );

if ( ex instanceof java.lang.NumberFormatException )

errors.append( " The value must be a number." );

}

%>

<%

Please purchase PDFcamp Printer on http://www.verypdf.com/ to remove this watermark.

Page 35: jsp

JSP Study Material 4th CSE, 4th IT Institute of Engineering & Management

Prepared by : Sourav Mukherjee Copy Right : 2004-2005

35

// Variables must be initialized outside declaration!

haveError = false;

errors = null;

%>

<HTML>

<BODY>

<jsp:useBean id="user" class="UserData" scope="session"/>

<blx:setProperty name="user"

property="*"

onError="errorHandler"/>

<%

if ( haveError ) {

out.println( errors.toString());

pageContext.include( "GetName.jsp" );

} else

pageContext.forward( "NextPage.jsp" );

%>

</BODY>

</HTML>

Note that haveError and errors must be re-initialized each time, therefore they are being

initialized outside of the declaration.

[Also notice the use of pageContext.include and pageContext.forward. These are

like jsp:include and jsp:forward, but are more convenient to use from within Java

blocks. pageContext is another pre-defined variable that makes it easy to do certain

operations from within Java blocks.]

Here, if an error occurs during the processing of blx:setProperty, we display the error

and then include the GetName.jsp again so user can correct the error. If no errors occur,

we automatically forward the user to NextPage.jsp.

Please purchase PDFcamp Printer on http://www.verypdf.com/ to remove this watermark.

Page 36: jsp

JSP Study Material 4th CSE, 4th IT Institute of Engineering & Management

Prepared by : Sourav Mukherjee Copy Right : 2004-2005

36

There is still a problem with the forms, the "age" shows up as zero initially rather than

being empty. This can be fixed by adding "emptyInt=0" to both the blx:getProperty

and blx:setProperty tags (bean fields should be initialized to 0.) It happens that "0" is

not a valid value for age, so we can use "0" to mark empty strings. If "0" were a valid

value for age, we could have added "emptyInt=-1" (and made sure to initialize the bean

fields to -1.)

Another small problem is that the "<HTML>" tag gets doubled if there is an error and we

end up including "GetName.jsp". A more elegant solution is to remove the out.println,

and pass back the error as shown

<%

if ( haveError ) {

request.setAttribute( "errors",

errors.toString());

pageContext.forward( "GetName.jsp" );

} else

pageContext.forward( "NextPage.jsp" );

%>

We can then do a "request.getAttribute" in the GetName.jsp, and if the returned value

is non-null, display the error.

Techniques for form editing

A tag library such as the one that comes with the Blazix server, may not be available in

your environment. How can you allow similar features without using a tag library?

It is a little tedious, but it can be done. Basically, you must edit each HTML tag yourself,

and put in a default value. The following examples shows how we modify GetName.jsp

to provide features similar to blx:getProperty but with manual HTML tag editing:

Please purchase PDFcamp Printer on http://www.verypdf.com/ to remove this watermark.

Page 37: jsp

JSP Study Material 4th CSE, 4th IT Institute of Engineering & Management

Prepared by : Sourav Mukherjee Copy Right : 2004-2005

37

<jsp:useBean id="user" class="UserData" scope="session"/>

<HTML>

<BODY>

<FORM METHOD=POST ACTION="SaveName.jsp">

What's your name? <INPUT TYPE=TEXT NAME=username

SIZE=20 VALUE="<%= user.getUsername() %>"><BR>

What's your e-mail address? <INPUT TYPE=TEXT

NAME=email SIZE=20

VALUE="<%= user.getEmail() %>"><BR>

What's your age? <INPUT TYPE=TEXT NAME=age

SIZE=4 VALUE=<%= user.getAge() %>>

<P><INPUT TYPE=SUBMIT>

</FORM>

</BODY>

</HTML>

As you can see, this simply involves adding a "VALUE" field in the INPUT tags, and

initializing the field with an expression!

To handle exceptions during input processing, a simple approach is to use "String" fields

in the bean, and do the conversion to the target datatype yourself. This will allow you to

handle exceptions.

COOKIS

Why we use Cookies

Cookies are necessary because the HTTP protocol that is used to transfer

webpages around the web is state-less. This means that web servers cannot

remember information about users throughout their travels, and so everyone

Please purchase PDFcamp Printer on http://www.verypdf.com/ to remove this watermark.

Page 38: jsp

JSP Study Material 4th CSE, 4th IT Institute of Engineering & Management

Prepared by : Sourav Mukherjee Copy Right : 2004-2005

38

becomes anonymous. If you ever return to a site you have visited previously,

you are treated as if it was your first visit.

This is especially unsatisfactory for sites which ask their users to log in — if you

leave and return just a few minutes later, you'll have to log in again. The server

doesn't remember anything about your visit or your preferred settings. So,

cookies were invented to give memory, of a sort, to web servers.

Structure of a Cookie

Cookies are no more than simple text files — usually found in your browser

cache, or ‘Temporary Internet files’ — which contain one or more entries. Each

entry is made up of

1. A name-value pair which stores whatever data you want to save.

2. An expiry date, after which time the entry will be deleted.

3. The web domain and path that the entry should be associated with.

You can use JavaScript to read or write a new entry to the cookie file. The process

of creating an entry is often referred to as ‘writing a cookie’, but this is

misleading. The cookie is the text file which contains all of your entries, while the

individual entries themselves hold the data. Each domain name on the web can

have a cookie file associated with it, and each cookie can hold multiple entries.

When you request a file from a server that you have used previously, the data in

the relevant cookie is sent to the server along with your request. This way,

server-side scripts, such as those written in Perl or » PHP, can read your cookie

and figure out whether you have permission to view a certain page, for instance.

Cookies can also be used for somewhat more malicious purposes, usually by

advertising companies to track your behaviour online. Most modern browsers

Please purchase PDFcamp Printer on http://www.verypdf.com/ to remove this watermark.

Page 39: jsp

JSP Study Material 4th CSE, 4th IT Institute of Engineering & Management

Prepared by : Sourav Mukherjee Copy Right : 2004-2005

39

include good measures that allow you to block cookies from certain sites, so

which sites you disclose information to is now at your discretion.

The name-value pair part of the entry is very similar to declaring a variable —

when you want to retrieve information you ask for the value that is associated

with a name that you provide. The expiry date is expressed in an unfriendly UTC

format; though fortunately there are methods for generating a suitable date. If a

date is not set, the entry is deleted when you close your browser.

The domain and path that you associate your cookie with have to be part of

the same domain that your site belongs to. For instance, I can set my cookie to be

active for www.yourhtmlsource.com, the default; or to yourhtmlsource.com,

which will cover any and all subdomains I set up for the site. I cannot, however,

set it to yahoo.com, for obvious security reasons. Using the path you can restrict

a cookie to be valid for only a certain directory. Usually you'll want it to be

available to any page in the domain, so this is set to /, the root directory.

Setting, Reading and Erasing Cookies

The document has an object in JavaScript called document.cookie, which is used

to read and retrieve cookie data. It is a repository of Strings (though not an

array). You can create new entries, read out an existing name-value pair, or

erase an entry through JavaScript. To create a cookie for my site, I write

document.cookie =

"testvalue1=Yes; expires=Fri, 13 Jul 2004 05:28:21 UTC; path=/";

The whole entry is supplied as one quoted String with segments set apart with

semicolons — first the name-value pair, then the expiry date in the correct

format, and finally the path. This syntax is fixed, and you shouldn't go

rearranging the elements. Write this entry now. To test out the cookie's contents,

we can use a simple script like

Please purchase PDFcamp Printer on http://www.verypdf.com/ to remove this watermark.

Page 40: jsp

JSP Study Material 4th CSE, 4th IT Institute of Engineering & Management

Prepared by : Sourav Mukherjee Copy Right : 2004-2005

40

alert(document.cookie);

Which will yield this result. You may see another value in there too, which is

used by our Stylesheet-switcher. Now we can write another entry to the cookie,

using a different name, as so:

document.cookie =

"testvalue2=Nah; expires=Fri, 13 Jul 2004 05:28:21 UTC; path=/";

Checking on the cookie's contents now, we can see that our first value is still in

there. Had we used the same name, the first value would've been overwritten;

but since we used a different name, the new entry has been added in with the

first.

Erasing cookie entries is easy — just set a new value and give an expiry date

before today, as in

document.cookie =

"testvalue2=Whatever; expires=Fri, 13 Jul 2001 05:28:21 UTC; path=/";

You can also give the entry an expiry date of -1, and it will be erased

immediately. Erase test values 1 and 2 now, if you have the heart.

Convenient Scripts

To easily tinker with cookies ourselves, we'll be using some great scripts which I

found through » PPK, and which were originally coded by » Scott Andrew.

They'll take much of the pain out of the process; especially reading the values out

of a cookie, which is a bit complicated. Here are the functions:

function createCookie(name, value, days)

{

if (days) {

Please purchase PDFcamp Printer on http://www.verypdf.com/ to remove this watermark.

Page 41: jsp

JSP Study Material 4th CSE, 4th IT Institute of Engineering & Management

Prepared by : Sourav Mukherjee Copy Right : 2004-2005

41

var date = new Date();

date.setTime(date.getTime()+(days*24*60*60*1000));

var expires = "; expires="+date.toGMTString();

}

else var expires = "";

document.cookie = name+"="+value+expires+"; path=/";

}

function readCookie(name)

{

var ca = document.cookie.split(';');

var nameEQ = name + "=";

for(var i=0; i < ca.length; i++) {

var c = ca[i];

while (c.charAt(0)==' ') c = c.substring(1, c.length); //delete spaces

if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);

}

return null;

}

function eraseCookie(name)

{

createCookie(name, "", -1);

}

These are some nicely coded scripts, and don't require too much explanation.

The function we use to create cookies takes three arguments, which make up the

name-value pair and the amount of days to retain the cookie. The last argument

Please purchase PDFcamp Printer on http://www.verypdf.com/ to remove this watermark.

Page 42: jsp

JSP Study Material 4th CSE, 4th IT Institute of Engineering & Management

Prepared by : Sourav Mukherjee Copy Right : 2004-2005

42

is converted into a valid date by adding its value in hours to the current time

before being annexed into the line which creates the cookie.

The cookie reading function is the most difficult one here. First it splits the

available cookie String (what we've been reading out in the alert earlier on this

page) at every occurrence of the separating semicolon. This creates a new array,

with each index holding an entry pair. We loop through these looking for the

String 'name='. When we find this, we read out whatever else makes up this

index, which will be the value associated with the name we passed to the

function at the beginning.

Erasing an entry is easy — simply recreate a cookie with its expiration date set to

-1.

JSP Easy Cookies Script Here's a simple script to set a cookie in JSP.

<%@ page import="java.util.Date"%> <%@ page import="java.net.*"%> <% Date now = new Date(); String timestamp = now.toString(); Cookie cookie = new Cookie ("Username", "David"); cookie.setMaxAge(365 * 24 * 60 * 60); response.addCookie(cookie); %> <HTML> <HEAD> </HEAD> <BODY>

Please purchase PDFcamp Printer on http://www.verypdf.com/ to remove this watermark.

Page 43: jsp

JSP Study Material 4th CSE, 4th IT Institute of Engineering & Management

Prepared by : Sourav Mukherjee Copy Right : 2004-2005

43

<%=cookie.getValue()%> </BODY> </HTML>

Now here's how you check whether it exists or not.

<%@ page import="java.net.*"%> <% String cookieName = "Username"; Cookie cookies [] = request.getCookies (); Cookie myCookie = null; if (cookies != null) { for (int i = 0; i < cookies.length; i++) { if (cookies [i].getName().equals (cookieName)) { myCookie = cookies[i]; break; } } } %> <HTML> <HEAD> </HEAD> <BODY> <%if (myCookie == null) {%> Hello first timer! <%} else {%> Hi again <%=redCookie.getValue()%>, welcome back! <%}%> </BODY> </HTML>

Please purchase PDFcamp Printer on http://www.verypdf.com/ to remove this watermark.

Page 44: jsp

JSP Study Material 4th CSE, 4th IT Institute of Engineering & Management

Prepared by : Sourav Mukherjee Copy Right : 2004-2005

44

JDBC

One of the major problems with databases has been the feature war between the

database companies. There is a standard database language. Structure Query

Language(SQL-92), but usually you must know which database vendor you’ar

programming. However, it’s still possible to make vendor-specific calls form

JDBC so you aren’t restricted form doing what you must.

JDBC, like many of the APIs in Java, is designed for simplicity. The method calls

you make correspond to the logical operations you’d think of doing when

gathering data form a database: connect to the database, create a statement and

execute the query and look at the result set.

To allow this platform independence, JDBC provides a driver manager that

dynamically maintains all the driver objects that your databases to connect to,

you’ll need three different driver objects. The driver objects register themselves

with the driver manager at the time of loading, and can force the loading using

the method Class.forName().

Java

Database Client

JDBC Driver Database Server

Vendor Specific Protocol

Please purchase PDFcamp Printer on http://www.verypdf.com/ to remove this watermark.

Page 45: jsp

JSP Study Material 4th CSE, 4th IT Institute of Engineering & Management

Prepared by : Sourav Mukherjee Copy Right : 2004-2005

45

Another way for the java program to communicate with different database

engines is through the jdbc-odbc bridge. Microsoft established a common

standard for communicating with databases, called Open Database

Connectively(ODBC). Until ODBC, most database client were server specific.

ODBC drivers abstract away vendor – specific protocols, providing a common

application programming interface to database clients. By writing your database

clients to the ODBC API, you enable your programs to access more databse

servers. So your program interaction with different databases through jdbc-

odbc bridge might look something like this

Example :

Part I

To create a html page include a form name form1 action test.jsp and two textbox

one is username and other is password.

Java Database Client

Jdbc-Odbc Bridge

Database Server Vendor A )

Database Server Vendor B )

Database Server Vendor C )

Please purchase PDFcamp Printer on http://www.verypdf.com/ to remove this watermark.

Page 46: jsp

JSP Study Material 4th CSE, 4th IT Institute of Engineering & Management

Prepared by : Sourav Mukherjee Copy Right : 2004-2005

46

Part II

Create a system dsn name test through administrative privilege. DSN will create

through system->administrative tools.

Part III

Coding of test.jsp

<%

String regno=request.getParameter(“text1”);

String pass1=request.getParameter(“text2”);

%>

<html>

<head>

<title>

Test

</title>

</head>

<body bgcolor=lightskyblue>

<h1>

</h1>

<%@ page import = “java.sql.*” %>

<%

try{

Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);

String dbUrl=”jdbc:odbc:test”;

Connection connl=DriverManager.getConnection(dbUrl);

Statement stml=connl.createStatement();

Resultset rs=stml.executeQuery(“select reg_no,pass from stud where reg_no=’

“+regno.toString()+” ‘ “);

Please purchase PDFcamp Printer on http://www.verypdf.com/ to remove this watermark.

Page 47: jsp

JSP Study Material 4th CSE, 4th IT Institute of Engineering & Management

Prepared by : Sourav Mukherjee Copy Right : 2004-2005

47

%>

<%

int cou=0;

while (rs.next())

{

cou++;

if (rs.getString(“pass”).compareTo(pass1)!=0){%>

<p aline=center><string</strong><a href=

”http://iem_program/login.htm>Error-Pass</a></p>

<%{

else

{

%>

<p aline=center><string</strong><a href=

”http://iem_program/next.htm>Continue</a></p>

<%

} catch (Exception ex)

ex.getMessage();

}%>

</body>

</html>

Please purchase PDFcamp Printer on http://www.verypdf.com/ to remove this watermark.