148
Article Home> Articles > JSP > Fundamentals JSP Tutorial This is a JSP tutorial to help a developer understand what is meant by Java Server Pages. The reader will learn the main concepts, setup a JSP environment on their computer and write a few JSP programs. Why not learn JSP development using our JSP source code examples? Your First JSP Page 04/28/09 03:44:52 1/148

Jsp Tutorials

  • Upload
    gapvc

  • View
    436

  • Download
    7

Embed Size (px)

Citation preview

Page 1: Jsp Tutorials

ArticleHome> Articles > JSP > Fundamentals

JSP Tutorial

This is a JSP tutorial to help a developer understand what is meant by Java Server Pages. The reader will learn the mainconcepts, setup a JSP environment on their computer and write a few JSP programs. Why not learn JSP developmentusing our JSP source code examples?

Your First JSP Page 04/28/09 03:44:52

1/148

Page 2: Jsp Tutorials

Introduction to JSP

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 Tagscontaining 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 thisexample,the Web server is running on Unix and is the very popular Apache Web server

Your First JSP Page 04/28/09 03:44:52

2/148

Page 3: Jsp Tutorials

First static web pages were displayed. Typically these were people?s first experience with making web pages so consistedof My Home Page sites and company marketing information. Afterwards Perl and C were languages used on the webserver to provide dynamic content. Soon most languages including Visualbasic,Delphi,C and Java could be used to writeapplications that provided dynamic content using data from text files or database requests. These were known as CGIserver side applications. ASP was developed by Microsoft to allow HTML developers to easily provide dynamic contentsupported as standard by Microsoft?s free Web Server,Internet Information Server (IIS). JSP is the equivalent from SunMicrosystems,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 adatabase.

JSP source code runs on the web server in the JSP Servlet Engine. The JSP Servlet engine dynamically generates theHTML and sends the HTML output to the client?s web browser.

Your First JSP Page 04/28/09 03:44:52

3/148

Page 4: Jsp Tutorials

Your First JSP Page 04/28/09 03:44:52

4/148

Page 5: Jsp Tutorials

Why use JSP?

Why use JSP?

JSP is easy to learn and allows developers to quickly produce web sites and applications in an open and standard way. JSPis based on Java,an object-oriented language. JSP offers a robust platform for web development.

Main reasons to use JSP:

Multi platformComponent reuse by using Javabeans and EJB.Advantages of Java.You can take one JSP file and move it to another platform,web server or JSP Servlet engine.

This means you are never locked into one vendor or platform.

HTML and graphics displayed on the web browser are classed as the presentation layer. The Java code (JSP) on the serveris classed as the implementation.

By having a separation of presentation and implementation,web designers work only on the presentation and Javadevelopers concentrate on implementing the application.

Your First JSP Page 04/28/09 03:44:52

5/148

Page 6: Jsp Tutorials

JSP compared to ASP,ASP.NET and Servlets

JSP compared to ASP

JSP and ASP are fairly similar in the functionality that they provide. JSP may have slightly higher learning curve. Bothallow embedded code in an HTML page,session variables and database access and manipulation. Whereas ASP is mostlyfound on Microsoft platforms i.e. NT,JSP can operate on any platform that conforms to the J2EE specification. JSP allowcomponent reuse by using Javabeans and EJBs. ASP provides the use of COM / ActiveX controls.

JSP compared to ASP.NET

ASP.NET is based on the Microsoft .NET framework. The .NET framework allows applications to be developed usingdifferent programming languages such as Visual Basic,C# and JavaScript. JSP and Java still has the advantage that it issupported on many different platforms and the Java community has many years of experience in designing and developingEnterprise quality scalable applications. This is not to say that ASP.NET is bad,actually it is quite an improvement overthe old ASP code.

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. InServlets you need to have lots of println statements to generate HTML. JSP pages are converted to Servlets so actually cando the same thing as old Java Servlets.

Your First JSP Page 04/28/09 03:44:52

6/148

Page 7: Jsp Tutorials

JSP architecture

JSP architecture

JSPs are built on top of SUN Microsystems' servlet technology. JSPs are essential an HTML page with special JSP tagsembedded. These JSP tags can contain Java code. The JSP file extension is .jsp rather than .htm or .html. The JSP engineparses the .jsp and creates a Java servlet source file. It then compiles the source file into a class file,this is done the firsttime and this why the JSP is probably slower the first time it is accessed. Any time after this the special compiled servletis executed and is therefore returns faster.

Steps required for a JSP request:

The user goes to a web site made using JSP. The user goes to a JSP page (ending with .jsp). The web browsermakes the request via the Internet.

1.

The JSP request gets sent to the Web server.2. The Web server recognises that the file required is special (.jsp),therefore passes the JSP file to the JSP ServletEngine.

3.

If the JSP file has been called the first time,the JSP file is parsed,otherwise go to step 7.4. The next step is to generate a special Servlet from the JSP file. All the HTML required is converted to printlnstatements.

5.

The Servlet source code is compiled into a class.6. The Servlet is instantiated,calling the init and service methods.7. HTML from the Servlet output is sent via the Internet.8. HTML results are displayed on the user's web browser.9.

Your First JSP Page 04/28/09 03:44:52

7/148

Page 8: Jsp Tutorials

Your First JSP Page 04/28/09 03:44:52

8/148

Page 9: Jsp Tutorials

Setting up the JSP environment

Before setting up the JSP environment,you must make sure you have the JDK.

Download the latest JDK (with or without IDE) from the following URL:

http://java.sun.com/javase/downloads/index.jsp

For Windows,the complete download is about 50 MB.

Run through the setup.

One of the main problems new Java developers have is setting the PATH and CLASSPATH.

For Windows 95/98/ME you edit the AUTOEXEC.BAT file with the new PATH and CLASSPATH

settings and reboot your machine.

For Windows 2000/XP you edit the environment variables.

(Control Panel -> System -> Environment Variables).

See below. Read the installation instructions properly as it may change with future releases. What you do is add thelocation of java's bin folder to the Path variable and the classes you want in the CLASSPATH variable.

Your First JSP Page 04/28/09 03:44:52

9/148

Page 10: Jsp Tutorials

Both of these changes are described in the Java installation instructions.

Download the JSP environment

You can download JSP environments from the web.http://java.sun.com/products/jsp/index.jsp

The preferred option is to download the Tomcat (approximately 7 to 10MB depending on the extras chosen). Tomcat is afree open source JSP and Servlet engine,developed by Apache. Instructions to download Tomcat are given below.

http://tomcat.apache.org/

For Tomcat setup

To download Tomcat (current version 5.),go to the following URL:http://tomcat.apache.org/download-55.cgi

Your First JSP Page 04/28/09 03:44:52

10/148

Page 11: Jsp Tutorials

Unzip the file into a directory and set an environment variable TOMCAT_HOME to your main Tomcat directory:

For example, set TOMCAT_HOME=c:tomcat

To start the server change to the tomcatbin directory and type:startup

Open a web browser and in the address box type:http://localhost:8080/ - this displays the example page.

Place any new JSP files in the webapps directory under your installed Tomcat directory.

For example,to run myfirst.jsp file,copy the file into the webapps/ROOT directory and then open a browser to the address:http://localhost:8080/myfirst.jsp

This will show you the executed JSP file.

CONGRATULATIONS - YOUR JSP and SERVLET ENVIRONMENT IS NOW SETUP!

Your First JSP Page 04/28/09 03:44:52

11/148

Page 12: Jsp Tutorials

Creating your first JSP pageCreating your first JSP page

<html><head><title>My first JSP page</title></head><body><%@ page language=java %><% 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.

Your First JSP Page 04/28/09 03:44:52

12/148

Page 13: Jsp Tutorials

Using JSP tags

Using JSP tags

There are five main tags:

Declaration tag1. Expression tag2. Directive tag3. Scriptlet tag4. Action tag5.

Your First JSP Page 04/28/09 03:44:52

13/148

Page 14: Jsp Tutorials

Declaration tagDeclaration 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) ;%>

Your First JSP Page 04/28/09 03:44:52

14/148

Page 15: Jsp Tutorials

Expression tag

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() %>

Your First JSP Page 04/28/09 03:44:52

15/148

Page 16: Jsp Tutorials

Directive tag

Directive tag ( <%@ directive ... %> )A JSP directive gives special information about the page to the JSP Engine. 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 withspecial processing information. The following table lists the 11 differentattributes with a brief description:

language Which language the file uses. <%@ page language =java %>

extends Superclass used by the JSPengine for the translatedServlet.

<%@ page extends =com.taglib... %>

import Import all the classes in a javapackage into the current JSPpage. This allows the JSPpage to use other java classes.

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

session Does the page make use ofsessions. By default all JSPpages have session dataavailable. There areperformance benefits toswitching session to false.

Default is set to true.

buffer Controls the use of bufferedoutput for a JSP page. Defaultis 8kb

<%@ page buffer =none %>

autoFlush Flush output buffer when full. <%@ page autoFlush =true %>

isThreadSafe Can the generated Servlet dealwith multiple requests? If truea new thread is started so

Your First JSP Page 04/28/09 03:44:52

16/148

Page 17: Jsp Tutorials

requests are handledsimultaneously.

info Developer uses info attributeto add information/documentfor a page. Typically used toadd author,version,copyrightand date info.

<%@ page info =visualbuilder.com testpage,copyright 2001. %>

errorPage Different page to deal witherrors. Must be URL to errorpage.

<%@ page errorPage =/error/error.jsp %>

IsErrorPage This flag is set to true to makea JSP page a special ErrorPage. This page has access tothe implicit object exception(see later).

contentType Set the mime type andcharacter set of the JSP.

2. Include directive

Allows a JSP developer to include contents of a file inside another. Typicallyinclude files are used for navigation,tables,headers and footers that arecommon to multiple pages.Two examples of using include files: This includes the htmlfrom privacy.html found in the include directoryinto the current jsp page. <%@ include file =include/privacy.html %> or to include a naviagation menu (jsp file) found inthe current directory. <%@ include file = navigation.jsp %> Include filesare discussed in more detail in the later sections of this tutorial. 3. TagLib directive A tag lib is a collection of custom tags that can be used by thepage. <%@ taglib uri = tag library URI prefix = tag Prefix %> Custom tagswere introduced in JSP 1.1 and allow JSP developers to hide complex serverside code from web designers.

Your First JSP Page 04/28/09 03:44:52

17/148

Page 18: Jsp Tutorials

Scriptlet tag

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 ) ; %>

Your First JSP Page 04/28/09 03:44:52

18/148

Page 19: Jsp Tutorials

Action tagAction tag

There are three main roles of action tags :

1) enable the use of server side Javabeans2) transfer control between pages3) 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 leavemost of the code in these Javabeans. For example,if you wanted to make a feedback form that automatically sent out anemail. By having a JSP page with a form,when the visitor presses the submit button this sends the details to a Javabeanthat 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).

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

There are three main roles of action tags :

1) enable the use of server side Javabeans2) transfer control between pages3) 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 leavemost of the code in these Javabeans. For example,if you wanted to make a feedback form that automatically sent out anemail. By having a JSP page with a form,when the visitor presses the submit button this sends the details to a Javabeanthat 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).

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 requestsession - bean lasts for the client session.application - bean instance created and lasts until application ends.

Your First JSP Page 04/28/09 03:44:52

19/148

Page 20: Jsp Tutorials

Your First JSP Page 04/28/09 03:44:52

20/148

Page 21: Jsp Tutorials

Creating your second JSP page

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 pagehas been accessed. There is also a private method declared to increment the counter. The website name and counter valueare displayed.

<HTML><HEAD><!-- Example2 --><TITLE> JSP loop</TITLE></HEAD><BODY><font face=verdana color=darkblue>JSP loop<BR> <BR><%!public String writeThis(int x){ String myText=; for (int i = 1; i < x; i++ ) myText = myText + <font size= i color=darkred face=verdana>VisualBuilder JSP Tutorial</font><br> ; return myText;}%>

This is a loop example from the

<br><%= writeThis(8) %></font></BODY></HTML>

Your First JSP Page 04/28/09 03:44:52

21/148

Page 22: Jsp Tutorials

Implicit Objects

Implicit Objects

So far we know that the developer can create Javabeans and interact with Java objects. There are several objects that areautomatically available in JSP called implicit objects.

The implicit objects are

Variable Of typeRequest Javax.servlet.http.httpservletrequestResponse Javax.servlet.http. httpservletresponseOut Javax.servlet.jsp.JspWriterSession Javax.servlet.http.httpsessionPageContent Javax.servlet.jsp.pagecontextApplication Javax.servlet.http.ServletContextConfig Javax.servlet.http.ServletConfigPage Java.lang.Object

Page object

Represents the JSP page and is used to call any methods defined by the servlet class.

Config object

Stores the Servlet configuration data.

Request object

Access to information associated with a request. This object is normally used in looking up parameter values and cookies.

<% String devStr = request.getParameter(dev); %>Development language = <%= devStr %>This code snippet is storing the parameter dev in the string devStr. The result is displayed underneath.

Your First JSP Page 04/28/09 03:44:52

22/148

Page 23: Jsp Tutorials

Creating a Form

Creating a Form

Here we show how to create and process an html form.Copy the code below and place in a file named: myform.jspGo to myform.jsp in your browserYou will see the form you just created.It won't do anything yet.

<html><head><!-- Example4 --><title>VisualBuilder.com</title></head><body><form action=myformconfirm.jsp method=post>Enter in a website name:<br><input type=text name=website><br><input type=submit name=submit></form></body></html>

Your First JSP Page 04/28/09 03:44:52

23/148

Page 24: Jsp Tutorials

Processing a Form

Processing a FormHere we show how to process the html form your just created.Copy the code below and place in a file named: myformconfirm.jspGo to myform.jspFill in some details and submit the formYou should see the results of your submission<html><head><!-- Example4 --><title>VisualBuilder.com</title></head><body><font size=3>Your info has been received:<br><br><%String sName = request.getParameter(website);out.print(sName);%></font></body></html>

Your First JSP Page 04/28/09 03:44:52

24/148

Page 25: Jsp Tutorials

Creating a Form (more elements)

Creating a Form (more elements)This example shows how to create and process more form elements.Copy the code below and place in a file named: fullform.jsp

<html><head><!-- Example5 --><title>VisualBuilder.com</title></head><body><h1>Website submission form</h1><form action=fullformconfirm.jsp method=post>Enter in the website name:<input type=text name=website><br><br>Enter in the url:<input type=text name=url><br><br>category:<select name=category size=1><option selected value=java>java</option><option value=ejb>ejb</option><option value=servlet>servlet</option><option value=jsp>jsp</option><option value=jdbc>jdbc</option></select><br><br>Description:<textarea rows=4 cols='42' name=desc></textarea> <br><br>Search engines:<input type=checkbox name=yahoo value=T>Yahoo<input type=checkbox name=google value=T CHECKED>Google<input type=checkbox name=altavista value=T>Altavista<br><br><input type=submit name=submit value=Go></form></body>

Your First JSP Page 04/28/09 03:44:52

25/148

Page 26: Jsp Tutorials

</html>

Your First JSP Page 04/28/09 03:44:52

26/148

Page 27: Jsp Tutorials

Processing a Form (more elements)

Processing a Form (more elements)

Here we show how to process the html form your just created.Copy the code below and place in a file named: fullformconfirm.jspGo to fullform.jspFill in some details and submit the formYou should see the results of your submission

<html>

<head><!-- Example4 --><title>VisualBuilder.com</title>

</head><body>

<font size=3>Thank you for your submission,it has been successfully received:<br><br><%String sName = request.getParameter(website);String sUrl = request.getParameter(url);String sCategory = request.getParameter(category);String sDesc = request.getParameter(desc);String sGoogle = request.getParameter(google);String sYahoo = request.getParameter(yahoo);String sAltavista = request.getParameter(altavista);%>

Name:<%=sName%><br>Url:<%=sUrl%><br>Desc:<%=sDesc%><br>Category:<%=sCategory%><br>Desc:<%=sDesc%><br>Google:<%=sGoogle%><br>Yahoo:<%=sYahoo%><br>Altavista:<%=sAltavista%><br>

</font>

</body></html>

Your First JSP Page 04/28/09 03:44:52

27/148

Page 28: Jsp Tutorials

Processing a Form (more elements-2)

Processing a Form (more elements)

Here we show how to process the html form your just created.Copy the code below and place in a file named: fullformconfirm.jspGo to fullform.jspFill in some details and submit the formYou should see the results of your submission

<html>

<head><!-- Example4 --><title>VisualBuilder.com</title>

</head><body>

<font size=3>Thank you for your submission,it has been successfully received:<br><br><%String sName = request.getParameter(website);String sUrl = request.getParameter(url);String sCategory = request.getParameter(category);String sDesc = request.getParameter(desc);String sGoogle = request.getParameter(google);String sYahoo = request.getParameter(yahoo);String sAltavista = request.getParameter(altavista);%>

Name:<%=sName%><br>Url:<%=sUrl%><br>Desc:<%=sDesc%><br>Category:<%=sCategory%><br>Desc:<%=sDesc%><br>Google:<%=sGoogle%><br>Yahoo:<%=sYahoo%><br>Altavista:<%=sAltavista%><br>

</font>

</body></html>

Your First JSP Page 04/28/09 03:44:52

28/148

Page 29: Jsp Tutorials

Your First JSP Page 04/28/09 03:44:52

29/148

Page 30: Jsp Tutorials

Getting Client Info

Getting Client Info

You can get information about a clients computerCopy the code below and place in a file named: clientinfo.jspRun it from your browser -clientinfo.jsp

You should see the results of your submission

<html>

<head><!-- Example5 --><title>VisualBuilder.com</title>

</head><body>Client computer details:<br><br><b>Ip address</b>:<br><%=request.getRemoteAddr()%><br><br><b>Computer name</b>:<br><%=request.getRemoteHost()%><br><br></body></html>

Your First JSP Page 04/28/09 03:44:52

30/148

Page 31: Jsp Tutorials

Review and next steps

What you have learnt so far

Now that you have learnt how to create some simple JSP code and grasped the fundamentals of JSP programming, youcan build on your knowledge and become an expert.

The following pages will cover the following topics

Security• Exception Handling• Database access and use• Design best practice• Lots of ready to use examples and source code snippets•

Your First JSP Page 04/28/09 03:44:52

31/148

Page 32: Jsp Tutorials

Beans scopes in JSP

JavaBeans are reusable components. It represents a simple Java class with some properties. The bean properties areaccessed by Getter and Setter method. They are used to separate Business logic from the Presentation logic. Internally, abean is just an instance of a class. The JSP specification provides three basic tags for working with Beans :-

rn

jsp:useBean id=bean name class=bean class scope = page | request | session |application />

rn

rn<jsp:setProperty name = bean name property = someProperty value = someValue />•

rn<jsp:getProperty name = bean name property = someProperty />•

rn rn

Where bean name = the name that refers to the bean.Bean class = name of the java class that defines the bean.property = name of the property to be passed to the bean.value = value of that particular property.

rn

The following is the explanation for the different scopes of a bean object in jsp:

rn

rnPage scope:- This scope helps to keep the data available while the page is loading. Any object whose scope isdefined as page scope will disappear as soon as the response is sent to the browser. The object with a page scopemay be modified as often as desired within the particular page but the changes are lost as soon as the user movesaway from the page. By default all beans have page scope.

1.

rnRequest scope:- Any object created in the request scope will be available as long as the request object is valid.For example if the JSP page uses a <jsp:forward> tag, then the bean will be accessed in the forwarded page and ifredirect is used then the bean is destroyed.

2.

rnThe Session scope:- In JSP terms, the data associated with the user has session scope. A session does notcorrespond directly to the user; rather, it corresponds with a particular period of time the user spends at a site.Typically, this period is defined as all the hits a user makes to a website between starting and exiting his browser.

3.

rnApplication Scope:- The bean associated with the application scope will be accessible to all the users and all thepages in the application.

4.

Your First JSP Page 04/28/09 03:44:52

32/148

Page 33: Jsp Tutorials

Your First JSP Page 04/28/09 03:44:52

33/148

Page 34: Jsp Tutorials

JSP Bean scope examples

The following example will demonstrate the various bean scopes for the JSP application. All the examples will use theCounter bean which has only one property counter of type int .

(1) Page Scope

Note:- This is the default scope for the bean object. So in the following JSP example bean1 is accessed only in this pageand not anywhere else.

<HTML><BODY><H1>Using Beans and Page Scope</H1><jsp:useBean id=bean1 class=com.visualbuilder.Counter scope=page /> <%bean1.setCounter(bean1.getCounter() + 1);%> The counter value is: <jsp:getProperty name=bean1 property=counter /></BODY></HTML>

(1) Request Scope

index.jsp

<jsp:useBean id=counter scope=request class=com.visualbuilder.Counter /><html><head> <title>Request Bean Example</title></head><body><% counter.setCounter(10);%><jsp:forward page=request.jsp /></body></html>

request.jsp

<jsp:useBean id=counter scope=request class=com.visualbuilder.Counter />

<html><body> <H3>Request Bean Example</H3> <center><b>The current count for the counter bean is: </b> <%=counter.getCounter() %></center></body></html>

(3) Session Scope

Your First JSP Page 04/28/09 03:44:52

34/148

Page 35: Jsp Tutorials

Example for Session Scope.

<HTML><BODY> <jsp:useBean id=bean1 class=com.visualbuilder.Counter scope=session /> <%bean1.setCounter(bean1.getCounter() + 1);%> The counter value is: <jsp:getProperty name=bean1 property=counter /></BODY></HTML>

(3) Application Scope

<jsp:useBean id=counter scope=application class=com.visualbuilder.Counter />

<html><body><center>&nbsp;&nbsp;<b>The current count for the counter bean is: </b> <%=counter.getCounter() %></center></body></html>

Your First JSP Page 04/28/09 03:44:52

35/148

Page 36: Jsp Tutorials

Uploading Application in JSP.

The request object is used to send the raw data in form of key/value pair to the server from the browser. What if, we wantto send the multipart data i.e. images, files and binary data to the server. The below example will demonstrate the multipletype data send to the server.

<%@ page import=java.io.*%><% String contentType = request.getContentType(); if ((contentType != null) && (contentType.indexOf(multipart/form-data) >= 0)) { DataInputStream in = new DataInputStream(request.getInputStream()); int formDataLength = request.getContentLength();

byte dataBytes[] = new byte[formDataLength]; int byteRead = 0; int totalBytesRead = 0; while (totalBytesRead < formDataLength) { byteRead = in.read(dataBytes, totalBytesRead, formDataLength); totalBytesRead += byteRead; } String file = new String(dataBytes); String saveFile = file.substring(file.indexOf(filename=) + 10); saveFile = saveFile.substring(0, saveFile.indexOf(n)); saveFile = saveFile.substring(saveFile.lastIndexOf(\) + 1,saveFile.indexOf()); int lastIndex = contentType.lastIndexOf(=); String boundary = contentType.substring(lastIndex + 1,contentType.length()); int pos; pos = file.indexOf(filename=); pos = file.indexOf(n, pos) + 1; pos = file.indexOf(n, pos) + 1; pos = file.indexOf(n, pos) + 1; int boundaryLocation = file.indexOf(boundary, pos) - 4; int startPos = ((file.substring(0, pos)).getBytes()).length; int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length; String filepath=session.getServletContext().getRealPath(/)+saveFile; FileOutputStream fileOut = new FileOutputStream(filepath);

fileOut.write(dataBytes, startPos, (endPos - startPos)); fileOut.flush(); fileOut.close(); out.println(File saved as +saveFile); }%>

<!-- Starts Here --><form method=post ACTION=upload.jsp name=uploadForm ENCTYPE='multipart/form-data'><input type=file name=uploadfile /><p> <input type=submit name=Submit value=Submit> <input type=reset name=Reset value=Reset> <input type=hidden name=action value=upload>

Your First JSP Page 04/28/09 03:44:52

36/148

Page 37: Jsp Tutorials

</p></form><!-- Ends Here -->

Output:-

Your First JSP Page 04/28/09 03:44:52

37/148

Page 38: Jsp Tutorials

Modularization in JSP

These days, users expect feature rich online applications and companies need flexible application design to deal withcomplex business rules. The day of having a single code file with all the application are gone. Modularization is thesplitting up of complex code into separate modules of code. The following are the advantages of the modularization:-

Coding and debugging both are very easy as compared to single file.1. The code is reused if required in the multiple pages.2. If any logic becomes obsolete then it can be replaced without disturbing other components in the application. Thefollowing tags are used to add the multiple JSP pages into one:-a. <jsp:include>:- The <jsp:include> includes the given file on runtime. When container encounters this tag, itchecks for the JSP file and compile that given JSP file. The output is then included in the page at runtime. As aresult response time increases to some extent. It is always better to use <jsp:include> when the JSP page contentare dynamically changes and the restarts of the servers are not done periodically.b. <%@include%>:- This tag includes the contents of the given file during the compilation of the JSP file. Whenthe container encounter this tag it will generate the servlet and include all the contents of the included file to theservlet. Now if we change the included file then it would not reflect to its parent page until or unless it is reloadedto the container or the server gets a restart. So it is always better to use <%@include%> for the static type of thepages.

3.

Example:-

The below is given the use of the <jsp:include> and also the <%@include%> tag.

<jsp:include page=coretaglib1.jsp/><br><%@include file=coretaglib2.jsp%>

Output

The below output will be displayed.

Your First JSP Page 04/28/09 03:44:52

38/148

Page 39: Jsp Tutorials

Exception Handling in JSP-1

An exception is an event, which occurs during the execution of a program that disrupts the normal flow of the program'sinstructions. When an error occurs within a method, the method creates an object and hands it off to the runtime system.The object, called an exception object, contains information about the error, including its type and the state of the programwhen the error occurred. There are two ways to handle the exceptions in the JSP world. First- is the conventionaltry/catch/finally block in the scriptlet. In this way you have to handle the flow of the program.

The following example will demonstrate the conventional way of error handling.

Example:-

<%try{ String str=11a; int i = Integer.parseInt(str); }catch(Exception e){ out.println(Error Occured); }%>

Output:-

The above example will print the Error occurred as output. The page is throwing a NumberFormatException whileconverting string to integer. As a result, the control is transferred to the catch block of the program.

Your First JSP Page 04/28/09 03:44:52

39/148

Page 40: Jsp Tutorials

Exception Handling in JSP-2

The second way is to define the error page in the page directive as <%@ page errorPage=errorpage.jsp %> and creatingthe error page. When any exception or error occurs while processing the JSP page then the container automatically callsthe error page and redirects the flow to it. Any page can be used to show the errors.Users have to set the ErrorPage=trueproperty on the page directive for example:-<%@ page isErrorPage=true %> for error pages. While processing an errorpage an implicit object named exception automatically created for the page, which is used to display the error messages.

The below example will demonstrate the exception handling in the JSP and use of exception implicit object.

Exceptionhandling.jsp

<%@ page errorPage=errorpage.jsp %><%

String s=null;s.toString();

%>

errorpage.jsp

<%@ page isErrorPage=true %>

This is the Error page.The following error occurs:- <br><%= exception.toString() %>

Output:-

Your First JSP Page 04/28/09 03:44:52

40/148

Page 41: Jsp Tutorials

Session Tracking in JSP

In any web application, a user moves from one page to another. So, it is necessary to track the user's data and objectsthroughout the application. As we know that the session keeps the data particular to a user, so sessions are used to hold theuser's data. For sessions JSP provide an implicit object session, which can be use to save the data specific to the particularuser into the session scope.

There are mainly 4 ways for session Tracking as follows:

1. Cookies:-You can use HTTP cookies to store information about a session. The cookies are small text files stored in the client side.This is an excellent most widely used approach. However, even though servlets have a high-level and easy-to-useinterface to cookies, there are still a number of relatively tedious details that need to be handled, while working withcookies.

2. URL Rewriting:You can append some extra data on the end of each URL that identifies the session, and the server can associate thatsession identifier with data it has stored about that session. This is also an excellent solution, and even has the advantagethat it works with browsers that don't support cookies or where the user has disabled cookies. However, it has most of thesame problems as cookies, namely that the server-side program has a lot of straightforward but tedious processing to do.

3. Hidden form fields:HTML forms have an entry that looks like the following: <INPUT TYPE=HIDDEN NAME=session VALUE=...>. Thismeans that, when the form is submitted, the specified name and value are included in the GET or POST data. This can beused to store information about the session. However, it has the major disadvantage that it only works if every page isdynamically generated, since the whole point is that each session has a unique identifier.

4. Using session object in the JSP.

The implicit object represents the session. The information can be stored in the session for the current session bysetAttribute() and then retrieve by getAttribute() method, whenever needed. The session objects stores at the server so it isadvisable not to put heavy information in the session object.

To understand a session let us take a very simple example of getting the name from the user and saving it in the session,we will retrieve this name from session on next page and display on the page. For this, we will need 2 JSP pages.

Example:-

Sessiontracking1.jsp

<% String action= request.getParameter(action);if(action != null && action.equals(sub mit)){ String username=request.getParameter( username); String password=request.getParameter(password); if(username != null && password != null && username.equals(visualbuilder) && pa ssword.equals(test))

Your First JSP Page 04/28/09 03:44:52

41/148

Page 42: Jsp Tutorials

{ session.setAttribute(username,username); response.sendRedirect(sessiontracking2.jsp); }else{ out.println(<h3>Wrong password!!!!</h3>); } }else{%>

<html><form action=sessiontracking1.jsp method=post><input type=hidden name=action value=submit> Enter the user name :- <input type=text name=username ><br> Enter the password :- <input type=password name=password ><br> <input type=submit name=submit value=submit></form></html><%}%>

Sessiontracking2.jsp

<h3>Welcome <%= session.getAttribute(username)%> To the Site</h3>

Output:-

Your First JSP Page 04/28/09 03:44:52

42/148

Page 43: Jsp Tutorials

Security in JSP -1

Security is defined as the condition of being protected against danger or loss. The security is very important in any webapplication as the web applications are mostly exposed to all the people in the world. The levels of security can be

Transport Level security using HTTPS.• Authentication and Authorization• Role Based Access Control• Container-managed Security• Application-managed Security.•

The web application can be configured to use any level of security as per the requirement and criticality of the site.

Application Managed Vs Container Managed Security

Container Managed Application Managed

Authentication and Authorization are specified inweb.xml.

It uses multiple authentication schemes, such asPassword Authentication Form-basedAuthentication Client side Digital Certificates etc..

Redirects are handled automatically.• User data can be provided by a variety of stores xmlfile or flat files. In tomcat the Data is provided inTOMCAT_HOME/conf/tomcat-users.xml

Using the Username and Password forms..• Cookies• Using Servlet Filters.• Using SSLEXT with Struts to enableHTTPS.

The following is the Example to implement the Container Specific Security in Tomcat.

(1) tomcat-user.xml File

<?xml version =' 1.0 ' encoding =' utf-8 '?><tomcat-users> <role rolename = tomcat /> <role rolename = role1 /> <role rolename = admin /> <user username = tomcat password = tomcat roles = tomcat /> <user username = both password = tomcat roles = tomcat,role1 /> <user username = role1 password = tomcat roles = role1 /> <user username = visualbuilder password = test roles = admin /></tomcat-users>

(2) Web.xml file

<?xml version = 1.0 encoding = UTF-8 ?><web-app version = 2.4 xmlns = http://java.sun.com/xml/ns/j2ee xmlns:xsi =http://www.w3.org/2001/XMLSchema-instance xsi:schemaLocation = http://java.sun.com/xml/ns/j2eehttp://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd ><security-constraint> <web-resource-collection> <web-resource-name> application </web-resource-name> <url-pattern> /security.jsp</url-pattern>

Your First JSP Page 04/28/09 03:44:52

43/148

Page 44: Jsp Tutorials

</web-resource-collection> <auth-constraint> <role-name> admin </role-name> </auth-constraint></security-constraint><login-config> <auth-method> BASIC </auth-method> <realm-name> securityapp </realm-name></login-config><security-role> <description> Testing the Application Security </description> <role-name> admin </role-name></security-role></web-app>

Output:-

The following screen appears when you try to run the application. It will ask for username and password and once youenter visualbuilder as username and test as password then only it will display the pages of the application.

Your First JSP Page 04/28/09 03:44:52

44/148

Page 45: Jsp Tutorials

Security in JSP -2

The user can also use the html forms to accept the username and password. This helps to establish the application level ormodule level security in web world. All sites follow the different security policies and standards. It is always better to usethe application managed security for better results. Also, when the application is moved to some other servers then ithardly impacts the application managed security. The following example will demonstrate a form and shows the welcomemessage if user enters the correct username and password.

Example:-

<% String action= request.getParameter(action);if(action != null && action.equals(submit)){ String username=request.getParameter(username); String password=request.getParameter(password);if(username != null && password != null && username.equals(visualbuilder) && password.equals(test)){ out.println(<h3>welcome to the page</h3>);}else{ out.println(<h3>Wrong password!!!!</h3>);}}else{%>

<html><form action=formsecurity.jsp method=post> <input type=hidden name=action value=submit> Enter the user name :- <input type=text name=username ><br> Enter the password :- <input type=password name=password ><br> <input type=submit name=submit value=submit></form></html><%}%>

Output:-

Your First JSP Page 04/28/09 03:44:52

45/148

Page 46: Jsp Tutorials

Internationalization in JSP application

Few years back, the sites were developed using a single language and the developer used to create the sites to theirspecific languages. As the globalization occured, many frameworks have developed to support the multiple languages at atime. Now this can be achieved by having the multi language text in key/value pair and at runtime the text is read from thekey as per the language required. This multilingual support is known as Internationalization. Internationalization isdefined as the process of designing an application so that it can be adapted to various languages and regions withoutengineering changes.

The following classes are used to implement Internationalization to any site.

Locale - The fundamental Java class that supports internationalization is Locale . Each Locale represents aparticular choice of country and language, and also a set of formatting assumptions for things like numbers anddates.

ResourceBundle - The java.util.ResourceBundle class provides the fundamental tools for supporting messages inmultiple languages.

PropertyResourceBundle - One of the standard implementations of Resource Bundle allows you to defineresources using the same name=value syntax used to initialize properties files. This is very convenient forpreparing resource bundles with messages that are used in a web application, because these messages aregenerally text oriented.

Note:- The fmt is the jstl tag library used to implement the internationalization in JSP. The below example will tell youhow to use the fmt taglib in the application. The example displays the text coming from the different properties files. Theproperties file lables.properties is created with different locale suffix example en is for english, de for Germany etc. Wehave hello key in both the files. hello=This is german File in de file and hello=This is english File in english file.

Example JSP file Internationalization.jsp file .

<%@ taglib prefix=fmt uri=/WEB-INF/fmt.tld%><fmt:setLocale value=de scope=session/><fmt:bundle basename=com.visualbuilder.labels> <fmt:message> hello </fmt:message></fmt:bundle>

Output:-

The file will display This is german File and if the locale is changed to en then it will display the This is english file.

Your First JSP Page 04/28/09 03:44:52

46/148

Page 47: Jsp Tutorials

Introduction To Expression Language.

A primary feature of JSP technology version 2.0 is its support for an expression language (EL). An expression languagemakes it possible to easily access application data stored in JavaBeans components. As the EL is introduced in JSP 2.0,we can also use the page attribute isELIgnored to ignore the EL for a page.

<%@ page isELIgnored =true|false %>

The following is the EL operator table which can be used with the EL language.

Note:- and,eq,gt,true,instanceof,or,ne,le,false,empty, not,lt,ge,null,div and mod are reserved words in the EL so usercannot use these words for the identifiers.

Expression Result${3+2-1} ${3+2-1} <%-- Addition/Subtraction --%>

${1+2} ${1+2} <%-- String conversion --%>

${1 + 2*3 + 3/4} ${1 + 2*3 + 3/4} <%-- Mult/Div --%>

${3%2} ${3%2} <%-- Modulo --%>

${(8 div 2) mod 3} ${(8 div 2) mod 3} <%-- Compares with equals but returns false for null --%>

${1<2} ${1<2} <%-- Numerical comparison --%>

${a<b} ${a<b} <%-- Lexical comparison --%>

${2/3 >= 3/2} ${2/3 >= 3/2} <%-- >= --%>

${3/4 == 0.75} ${3/4 == 0.75} <%-- Numeric = --%>

${null == test} ${null == test}

${(1<2) && (4<3)} ${(1<2) && (4<3)} <%--AND--%>

${(1<2) || (4<3)} ${(1<2) || (4<3)} <%--OR--%>

${!(1<2)} ${!(1<2)} <%-- NOT -%> <%-- Handles null or empty string in request param --%>

${empty } ${empty } <%-- Empty string --%>

${empty null} ${empty null} <%-- null --%>

Your First JSP Page 04/28/09 03:44:52

47/148

Page 48: Jsp Tutorials

Introduction to Tag libraries

JSTL is a component technology within the Java 2 Enterprise Edition (J2EE) specification and is controlled by SunMicrosystems. JSTL is nothing more than a set of simple and standard tag libraries that encapsulates the core functionalitycommonly needed when writing dynamic JSP pages. The following are the problems with the JSPs:-

Java code embedded within scriptlet tags is ugly and obtrusive.1. It is very difficult to modify the java code embedded in the JSP files if the file is large.2. Java code within JSP scriptlets cannot be reused by other JSP pages.3. Retrieving objects out of the HTTP request and session is cumbersome and type casting to the object's class isrequired.

4.

The JSTL tags are basically categorized into four libraries:

core:- Basic scripting functions such as loops, conditionals, and input/output.• fmt:- Internationalization and formatting of values such as currency and dates.• xml:- XML processing• sql:- Database access.•

Advantages of using JSTL:-

JSTL tags are XML based tags which are cleanly and uniformly blend into a page's HTML markup tags.• The four JSTL tag libraries include most functionality that would be needed in a JSP page. JSTL tags are easierfor non-programmers and inexperienced programmers, because they do not require any knowledge of Javaprogramming.

JSTL tags encapsulate reusable logic such as formatting dates and numbers.• JSTL tags can reference objects in the request and session without knowing the object's type and no casting isrequired.

JSP's EL (Expression Language) makes it easy to call getter and setter methods on Java objects. This is notpossible in JSP 1.2, but became available in JSP 2.0. EL is used extensively in JSTL.

JSTL Drawbacks:

JSTL can add processing overhead to the server. Both Java scriptlet code and tag libraries are compiled into aresulting servlet, which is then executed by the servlet container. Java code embedded in scriptlet tags is directlycopied into the resulting servlet. But JSTL tags add more than required code to the servlet.

Although JSTL provides a powerful set of reusable libraries, it cannot do everything that Java code can do. It isdesigned to facilitate scripting the presentation code that is typically found in the view tier ofModel-View-Controller applications.

Your First JSP Page 04/28/09 03:44:52

48/148

Page 49: Jsp Tutorials

Introduction To Core Taglib -1

Core taglib is the important taglib in the JSTL. It includes the core concepts of the programming like declaring thevariable, decision making tags etc.. The next sections will explain all the core taglib tags, which are generally used in theprogramming.

Standard Syntax: <%@ taglib prefix=c uri=http://java.sun.com/jsp/jstl/core %>

Variable Support Tags

The <c:set> tag sets the value of an EL variable or the property in any of the JSP scopes (page, request, session, orapplication). If the variable does not exists, it will be created.

The JSP EL variable or property can be set either from the attribute value:

<c:set var=var scope=session value=.../>

OR

<c:set var=var>...</c:set>

To remove an EL variable, you use the <c:remove> tag as follows:

<c:remove var=test scope=session/>

Conditional TagsThe <c:if> tag allows the conditional execution of its body according to the value of the test attribute. The syntax of the<c:if> conditional block is as follows:-

<c:if test=${condition}> </c:if>

The <c:choose> tag performs conditional block execution by the embedded <c:when> tags. It renders the body of the first<c:when> tag whose test condition evaluates to be true. If none of the test conditions evaluates to be true, then the body of<c:otherwise> tag is evaluated, if present. The syntax is as follows :-

<c:choose> <c:when test=condition1 > ... </c:when> <c:when test=condition2 > ... </c:when> <c:otherwise> </c:otherwise></c:choose>

Your First JSP Page 04/28/09 03:44:52

49/148

Page 50: Jsp Tutorials

Introduction To Core Taglib -2

Iterator Tags

The <c:forEach> tag allows you to iterate over a collection of objects. You specify the collection via items attribute, andthe current item is available through a variable named given in the var attribute. A large number of collection types aresupported by <c:forEach>, including all implementations of java.util.Collection and java.util.Map. If given collection isof type java.util.Map, then the current item will be of type java.util.Map.Entry, which has the following properties:

key: The key under which the item is stored in the underlying Map• value: The value that corresponds to the key•

Arrays of objects as well as arrays of primitive types (for example, int) are also supported. For arrays of primitive types,the current item for the iteration is automatically wrapped with its standard wrapper class (for example, Integer for int,Float for float, and so on).

<c:forEach var=item items=collection></c:forEach>or

<c:forEach begin=0 end=10 varStatus=status step=1 >

</c:forEach>

URL Tags

The <c:url> tag is used to create the URL for the submit actions or the hyperlinks. The <c:url> tag is used to create theURL variable and <c:param> is used to add the parameters in the <c:url> tag. The syntax is as follows:-

<c:url var=var value=... ><c:param name=param1 value=val1 /></c:url>

Example:-

<%@ taglib uri=/WEB-INF/c.tld prefix=c %><% String[] value = new String[10]; value[0]=one; value[1]=two; value[2]=three; value[3]=four; value[4]=five;

Your First JSP Page 04/28/09 03:44:52

50/148

Page 51: Jsp Tutorials

value[5]=six; value[6]=seven; value[7]=eight; value[8]=nine; value[9]=ten; pageContext.setAttribute(values,value);%><b>Iterator For loop <br></b><c:forEach var=item varStatus=status items=${values}> Place <c:out value=${status.index}/> value is <c:out value=${item}/><br></c:forEach><br><b>Coventional For Loop<br></b><c:forEach begin=0 end=10 varStatus=status step=1 > Place <c:out value=${status.index}/> value is <c:out value=${values[status.index]}/><br></c:forEach>

<c:url var=yahoo value=http://www.yahoo.com/>

<a href=${yahoo}>yahoo url</a>

Your First JSP Page 04/28/09 03:44:52

51/148

Page 52: Jsp Tutorials

Your First JSP Page 04/28/09 03:44:52

52/148

Page 53: Jsp Tutorials

Function Taglib

The function taglib contains the basic String functions for the JSTL functionality.

Standard Syntax:

<%@ taglib prefix=fn uri=http://java.sun.com/jsp/jstl/functions %>

Return Type Method Description

boolean contains ( java.lang.String,java.lang.String) Tests if an input string contains the specified substring.

boolean containsIgnoreCase (java.lang.String, java.lang.String)

Tests if an input string contains the specified substring in a caseinsensitive way.

boolean endsWith ( java.lang.String,java.lang.String) Tests if an input string ends with the specified suffix.

java.lang.String escapeXml ( java.lang.String) Escapes characters that could be interpreted as XML markup.

int indexOf ( java.lang.String,java.lang.String)

Returns the index withing a string of the first occurrence of aspecified substring.

java.lang.String join ( java.lang.String[],java.lang.String) Joins all elements of an array into a string.

int length ( java.lang.Object) Returns the number of items in a collection, or the number ofcharacters in a string.

java.lang.String replace ( java.lang.String,java.lang.String, java.lang.String)

Returns a string resulting from replacing in an input string alloccurrences of a before string into an after substring.

java.lang.String[] split ( java.lang.String,java.lang.String) Splits a string into an array of substrings.

boolean startsWith ( java.lang.String,java.lang.String) Tests if an input string starts with the specified prefix.

java.lang.String substring ( java.lang.String, int, int) Returns a subset of a string.

java.lang.String substringAfter ( java.lang.String,java.lang.String) Returns a subset of a string following a specific substring.

java.lang.String substringBefore ( java.lang.String,java.lang.String) Returns a subset of a string before a specific substring.

java.lang.String toLowerCase ( java.lang.String) Converts all of the characters of a string to lower case.java.lang.String toUpperCase ( java.lang.String) Converts all of the characters of a string to upper case.java.lang.String trim ( java.lang.String) Removes white spaces from both ends of a string.

Example:-

<%@ taglib uri=/WEB-INF/fn.tld prefix=fn %><%@ taglib uri=/WEB-INF/c.tld prefix=c %> <c:set var=test value=This is the test String/> Index of i is :- ${fn:indexOf(test, i)}<br> Substring Function:- ${fn:substring(test, 3,10)}<br> Upper Case :- ${fn:toUpperCase(test)}<br> Lower Case:- ${fn:toLowerCase(test)}<br> Replace Function:- ${fn:replace(test,the,a)}<br>

Your First JSP Page 04/28/09 03:44:52

53/148

Page 54: Jsp Tutorials

contains Function:- ${fn:contains(test,the)}<br>

Output:-

Your First JSP Page 04/28/09 03:44:52

54/148

Page 55: Jsp Tutorials

Database Handling in JSP.

The database interaction with the JSP page is similar to the core JDBC interaction. The complete JDBC code for thedatabase interaction is to be written in the scriptlet tags. The following example shows the process of database handlingwith the JSP page. The following example will display the total hit for the current page and update the counter in thedatabase.

<%@page import=java.sql.* %><% int hitCount=0; try{ Class.forName(org.gjt.mm.mysql.Driver); Connection connection = DriverManager.getConnection(jdbc:mysql://localhost:3306/test, root, root); Statement statement = connection.createStatement(); int changed = statement.executeUpdate(update counters set hitCount = hitCount + 1 +where page like ' +request.getRequestURI() + '); if (changed == 0) statement.executeUpdate(insert counters(page) values(' + request.getRequestURI() + ')); ResultSet rs = statement.executeQuery(select hitCount from counters where page like ' + request.getRequestURI()+ '); rs.next(); hitCount = rs.getInt(1); }catch(Exception e ){ }finally{ statement.close(); connection.close(); } out.println(The hit count is +hitCount );%>

Output:-

The page prints The hit count is 5 as output.

Your First JSP Page 04/28/09 03:44:52

55/148

Page 56: Jsp Tutorials

Creating User Defined Custom Tag -1

The most powerful feature of JSP is that - the user can also create their own custom tags. The servlet API contains thejavax.servlet.jsp.tagext.BodyTagSupport class, which is used to create the custom tags. All the tags need to extend thejavax.servlet.jsp.tagext.BodyTagSupport class and override doStartTag(), doEndTag() and doAfterBody() methods. Aftercreating the Java class for the custom tag, the tag library description file is to be created. The extension for the XMLdescription file is .tld. The following example will create a tag, which takes String and prints the reverse of the Stringwhen displayed on the browser.

ReverseTag.java

package com.visualbuilder.taglibrary;

import java.io.IOException;

import javax.servlet.jsp.JspTagException;import javax.servlet.jsp.JspWriter;import javax.servlet.jsp.tagext.BodyContent;import javax.servlet.jsp.tagext.BodyTagSupport;

public class ReverseTag extends BodyTagSupport {

/****/private static final long serialVersionUID = 1L;

public int doStartTag() throws JspTagException{ return EVAL_BODY_TAG;}public int doEndTag() throws JspTagException { try { JspWriter out = pageContext.getOut(); } catch (Exception ex) { throw new JspTagException(All is not well in the world. + ex); } return SKIP_BODY;}

public int doAfterBody() throws JspTagException {

BodyContent body = getBodyContent(); try { // Make sure we put anything in the output stream in the // body to the output stream of the JSP JspWriter out = body.getEnclosingWriter(); String bodyContent = body.getString(); if (bodyContent != null) { for (int i = bodyContent.length() - 1; i >= 0; i--) {

Your First JSP Page 04/28/09 03:44:52

56/148

Page 57: Jsp Tutorials

out.print(bodyContent.charAt(i)); } } out.println(); body.clearBody(); // Clear for next evaluation } catch (IOException ioe) { throw new JspTagException(Error in reverse tag doAfterBody + ioe); } return (SKIP_BODY);

}}

Your First JSP Page 04/28/09 03:44:52

57/148

Page 58: Jsp Tutorials

Creating User Defined Custom Tag -2

The following is the tag lib descriptor file for the reverse tag.

<?xml version=1.0 encoding=ISO-8859-1 ?><!DOCTYPE taglib PUBLIC -//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//ENhttp://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd><taglib> <tlibversion>1.0</tlibversion> <jspversion>1.1</jspversion> <shortname>Visualbuilder</shortname> <info>Visual builder Tag library</info> <tag> <name>stringreverse</name> <tagclass>com.visualbuilder.taglibrary.ReverseTag </tagclass> <info> This is a simple tag which will reverse the text. </info> <!-- Optional attributes --> </tag></taglib>

CustomTag.jsp file

<%@ taglib uri=/WEB-INF/reverse.tld prefix=reverse %>

<html><head> <title>Your Custom Tag library</title></head><body bgcolor=#ffffff><hr /><reverse:stringreverse> Visual Builder</reverse:stringreverse><hr /></body></html>

Output:-

Your First JSP Page 04/28/09 03:44:52

58/148

Page 59: Jsp Tutorials

Best Practices in JSP

There are some standard practices that can be followed while writing the JSP files. The standards of writing JSP codehelps to develop the application easily and effectively. It reduces the complexity and the debugging time for the JSPapplication. The following are the best practices, while working on JSP application:-

Separate HTML from Java:- For small JSP files with least of logic, it seems as best to have the Java and html inthe same JSP file as all available resources and dependencies are in the same file. As the JSP's go on to highercomplexity, this approach fails as the code becomescomplex and less readable and hard to understand.

Place business logic in JavaBeans:- We must write our business logic in JavaBeans as the code will be reusedanywhere in the application. Also if any logical change occurs during the development so it requires to changeonly at one place and hence avoiding rework everywhere.

Factor general behavior out of custom tag handler classes:- If we are using custom tags then we must tend towrite the common code in a Java file separately instead of writing inside the customTagHandler. Because Handlerclasses are not readily used like ordinary Java utility classes rather Handler classes can access the utility classeseasily.

Favor HTML in Java handler classes over Java in JSPs:- Sometimes cleanly separating HTML, JSP tags, andHTML-like custom tags from Java requires unnecessarily convoluted code. In these cases, you either include Javascriptlets and expressions in the JSP or put some HTML code in the Java tag handler class.

Use an appropriate inclusion mechanism: - The JSP is a combination of the tags and the Java code. It is verydifficult to maintain the two types of code in a single file. JSP gives us the flexibility to create the multiple JSPpages and then call those JSP pages into the complex page wherever required.

Use a JSP template mechanism:- Using templates is the best approach when we can see the total structuralchanges in the look and feel of the page. It is not a good way to change each and every JSP page for the htmlchanges, rather we will define the layout of the page in a JSP and will use the templates mechanism to import thecontents of different portions from different JSP's through templates. So, when you want to change the layout, youneed to modify only one template file rather making changes in all pages.

Use stylesheets:- We must use CSS to give the styles to different components across the site, providing same CSSstyles to similar kind of components. If we want to change the look of a particular type of component throughoutthe website, we are required to change one style only and it will be reflected everywhere.

Your First JSP Page 04/28/09 03:44:52

59/148

Page 60: Jsp Tutorials

JSP HTML Form source example

The previous section has explained what all controls are used in HTML for creating the forms. Lets see with the help ofbelow example how do we get the form data in JSP page which is send by the user.

We need to first define which JSP page should be accessed when this form is submitted. This can be achieved by theaction attribute in the <form>. For example:- <form action=/login.jsp> will generate a request for the login.jsp pagewhen the submit button will be clicked for the form.

We will be creating the input1.jsp file which will show the data which user has sent from login.html page from theprevious example.

Example:-

<!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01 Transitional//ENhttp://www.w3.org/TR/html4/loose.dtd><html>

<head><meta http-equiv=Content-Language content=en-us><meta http-equiv=Content-Type content=text/html; charset=windows-1252><title>Login Form</title></head>

<body>

<p align=left><b>Login Form

</b></p>

<form method=POST action=login.jsp name=loginForm>

<table border=1 width=50% cellspacing=1 cellpadding=0 id=table1><tr><td width=50%>&nbsp;Login Name</td><td><input type=text name=loginName size=20></td></tr><tr><td width=50%>Password</td><td><input type=password name=password size=20></td></tr></table><p><input type=submit value=Submit name=B1><input type=reset value=Resetname=B2></p></form>

</body>

</html>JSP page:-

Your First JSP Page 04/28/09 03:44:52

60/148

Page 61: Jsp Tutorials

<%@ page language=java contentType=text/html; charset=ISO-8859-1pageEncoding=ISO-8859-1%><!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01 Transitional//ENhttp://www.w3.org/TR/html4/loose.dtd><html><head><meta http-equiv=Content-Type content=text/html; charset=ISO-8859-1><title>Login Form Data</title></head><body><b>Submitted Values are </b><table border=1 width=50% cellspacing=1 cellpadding=0 id=table1><tr><td width=50%>&nbsp;Login Name</td><td><%=request.getParameter(loginName) %></td></tr><tr><td width=50%>Password</td><td><%=request.getParameter(password) %></td></tr></table></body></html>Output:- The following screen will be displayed when login form will gets submitted.

Your First JSP Page 04/28/09 03:44:52

61/148

Page 62: Jsp Tutorials

Creating Web Application

Creating Web Application in Eclipse

The following are the steps which will create the web application using eclipse.

Goto File > new >project or right click the project explorer and then select new>project option.1. Project dialog box appears.2. Select the Dynamic web application from the Web option.3. Enter the name for the project and select the location where you want to create the project folder.4. Click finish.5. This will create the folders like src, build and WebContent. WebContent is the folder where we will place all thedependent libraries and jsp files where as in src we will have Java source files for the application.

6.

Note:- Click here to see the steps in a movie. We are using the latest version of Eclipse 3.2.2. The downloadable zip file isavailable on the http://eclipse.org site.

Your First JSP Page 04/28/09 03:44:52

62/148

Page 63: Jsp Tutorials

Configuring Server in Eclipse

Configuring Server in Eclipse

The following are the steps for setting the Tomcat server in the eclipse environment.

Select Windows>Preferences from the menu items.1. Select Server from the explorer options.2. Click on Installed Runtimes.3. Click on Add and select the server you need to add. We are using Tomcat so we use Apache object and thenselecting the right version of Tomcat(5.5 in our case).

4.

Click on the Next button.5. Give the Tomcat installed directory path.6. Click Finish. It will display the Tomcat server setting in the Grid.7. Click Ok8.

Note:- Click here to see the steps in a movie.

Your First JSP Page 04/28/09 03:44:52

63/148

Page 64: Jsp Tutorials

Deploy & Run WebApplication

Steps to Deploy And Run Web Application

The following are the steps to run and deploy the web application on the server using the Eclipse IDE. We will create aindex.html file and then run the file in eclipse for testing and deployment.

Select New>HTML from the dialog appears after the right clicking the application.1. Give the file name as index.html2. Click Finish button.3. Put the text on the HTML file and save the file.4. Right Click the project and select Run As option.5. Select 1.Run on Server from the appeared sub menu.6. Select the Runtime server and click Finish.7. Automatically the Tomcat server starts and application is deployed to the server.8. Eclipse will display the output.9.

Note:- Click here to see the steps in a movie.

Your First JSP Page 04/28/09 03:44:52

64/148

Page 65: Jsp Tutorials

Your First JSP Page

Your First JSP Page

Let's see how do we create the JSP pages in eclipse. We start with the classic Hello World Application. Steps to create theJSP page is as follows:-

Right Click on the Project WebContent.• Goto New> JSP• Enter the JSP page name with .jsp extension in the dialog.• Click Finish•

You will see the file is created under the WebContent folder. Enter the following code in the file.

<%@ page language=java contentType=text/html; charset=ISO-8859-1pageEncoding=ISO-8859-1%><!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01 Transitional//ENhttp://www.w3.org/TR/html4/loose.dtd><html><head><meta http-equiv=Content-Type content=text/html; charset=ISO-8859-1><title>Insert title here</title></head><body><%=Hello World %></body></html>Output:-

Hello World

Note:- You have seen the above JSP. The code is written in the <%= %>(expression tags). The next section will explainthe JSP elements more in detail.

Your First JSP Page 04/28/09 03:44:52

65/148

Page 66: Jsp Tutorials

Different JSP tags

Different JSP Tags

There are following basic JSP elements which can be used with the JSP pages.

Scriptlet Element.1. Expression Element.2. Declaration Element.3. Comments4.

The Scriptlet Element

Syntax :-<% Java Code %>

The simplest type of JSP element is the Scriptlet element. A Scriptlet element is simply a section of Java codeencapsulated within the opening and closing JSP tags. The Scriplet is only applicable to the page in which it is declaredand not in the other sub pages. The best part of the JSP is the power of directly using the Java Code with the HTML tags.

Example:- <% if(cond)%> is the sample code for the Scriplet.

Expression Element

Syntax: <%= code %>

The expression tag is used to print the output in the HTML format in the JSP page. In the last section we have just seenthat it is used to output the String object on JSP page.

Declaration Element Syntax

Syntax: <%! code %>

The next type of Scripting element is the Declaration element. The purpose of a Declaration element is to initializevariables and methods and make them available to other Declarations, Scriptlets, and Expressions.

Comments

Syntax: <%-- comment --%> <!-- comment -->

There are two different types of comments in JSP. The difference between the types of comments is that <%-- --%>comment is not viewable at the client side but the other one is viewable by selecting the view page source option.

Your First JSP Page 04/28/09 03:44:52

66/148

Page 67: Jsp Tutorials

Scriptlet Example

Scriptlet Example

Lets see the scriplet tag with example. The below example will print the numbers from 1 to 10.

counting.jsp

<%@ page language=java contentType=text/html; charset=ISO-8859-1pageEncoding=ISO-8859-1%><!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01 Transitional//ENhttp://www.w3.org/TR/html4/loose.dtd><html><head><meta http-equiv=Content-Type content=text/html; charset=ISO-8859-1><title>Insert title here</title></head><body>Going to Print the Numbers from 1 to 10. <br/> <% for(int i=1;i<=10;i++){ %> <%=i %><br> <%} %></body></html>

Output:-

Your First JSP Page 04/28/09 03:44:52

67/148

Page 68: Jsp Tutorials

Declaration Tag Exmaple

Declaration Tag Example

Lets see the scriptlet tag with example. The below example has one method named check() to check the odd and evennumber and return the String object for the same.

oddeven.jsp

<%@ page language=java contentType=text/html; charset=ISO-8859-1pageEncoding=ISO-8859-1%><!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01 Transitional//ENhttp://www.w3.org/TR/html4/loose.dtd><html><head><meta http-equiv=Content-Type content=text/html; charset=ISO-8859-1><title>Insert title here</title></head><body> <%! public String check(int num){

if(num %2 ==0 ){ return The Number + num + is an even number; }else{ return The Number + num + is an odd number; } } %>

<% for(int i=1;i<=10;i++){ %> <%=check(i) %><br> <%} %></body></html>Output:-

Your First JSP Page 04/28/09 03:44:52

68/148

Page 69: Jsp Tutorials

Your First JSP Page 04/28/09 03:44:52

69/148

Page 70: Jsp Tutorials

Directive Elements

Directive Elements

JSP directives are the special tags which are used to send some instructions to the JSP engine. This instruction can beencoding type of the page, packages to import for the page or the tag library location etc. They do not contain businesslogic. They do not modify the out stream. They simply tell the JSP engine how the JSP page should be compiled. Thefollowing table will explain the directive tags which is available in JSP. The coming section will explain the usage andexamples of each tag. Please note the directive tag starts with < %@.

Table for Directive tags

Directive Purpose

< %@ page%>The page directive allows several different page-specificattributes to be set.

<%@ include%>

The include directive used to include the different pages intothe page. This helps in modularization and reusability of theJSP pages.

<%@ taglib%>

The taglib directive specifies a tag library by which thestandard set of JSP tags can be extended. The tags define inthe taglib is used with normal HTML tags.

Your First JSP Page 04/28/09 03:44:52

70/148

Page 71: Jsp Tutorials

Page Directive Attributes

Page Directive Attributes

The page directive allows several different page-specific attributes to be set. A single JSP page can have multiple pagedirectives. Page directives always begin with the standard JSP open tag followed by an @ symbol and the keyword page(<%@ page). For example <%@ page import=java.util.Calendar %> The above page directive imports thejava.utilCalendar class. The below table will explain all the page attributes and their purpose.

Attribute Description

buffer The buffer attribute specifies the buffer size forbuffered JSP page.

autoFlush By default it is set to true. It flushes the outputwhen the buffer is full in buffered JSP pages.

contentTypeIt is used to define the response encoding typethat JSP produces as well as the MIME type ofresponse.

errorPage This attribute is used to specify the URL wherethe control is transferred in case error occurred.

isErrorPage

By default it is false. If set to true then this tellsthe JSP engine that this page is an error page andcan be called from some other page in case ofany exception occurred.

extendsit specified the super class of the JSP page. Thisattribute is not recommended to use. If it is notspecified then the JSP speed is much higher.

import

It is used to import the various Java classes. It issame as import statement in Java program.Multiple imports can be separate with comma insame attribute.

info It is used to specify the information regardingthe JSP page.

isThreadSafe

By default is set to true. This tells the JSPengine to process the simultaneously requestscoming for the page. For better performance thisvalue should not be changed.

language It specifies the language for the JSP page.Normally the value is Java.

sessionThis attribute tells the JSP engine whether thesession object need to be created for the JSPpage or not. The default value is true.

Note:- The next section will show the use of some of the above attributes.

Your First JSP Page 04/28/09 03:44:52

71/148

Page 72: Jsp Tutorials

Page Directive Example

Page Directive Example

Lets see how to declare and use some page directive attributes. The below example will explain the use of the import andresponse encoding type

<%@ page language=java contentType=text/html; charset=ISO-8859-1 buffer=16kbpageEncoding=ISO-8859-1%><%@ page import=java.util.Date; session=true%><!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01 Transitional//ENhttp://www.w3.org/TR/html4/loose.dtd><html><head><meta http-equiv=Content-Type content=text/html; charset=ISO-8859-1></head><body> Current Time is <br><%= new Date().getTime() %></body></html>

Output without Import

Your First JSP Page 04/28/09 03:44:52

72/148

Page 73: Jsp Tutorials

Output with Import

Your First JSP Page 04/28/09 03:44:52

73/148

Page 74: Jsp Tutorials

Include Directive Example

Include Directive Example

Lets see how to use the <@include to include the different files and generate the single output to the user. We will createfirstpage.jsp and secondpage jsp files. The second file is included in the first file.

firstpage.jsp

<%@ page language=java contentType=text/html; charset=ISO-8859-1pageEncoding=ISO-8859-1%><!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01 Transitional//ENhttp://www.w3.org/TR/html4/loose.dtd><html><head><meta http-equiv=Content-Type content=text/html; charset=ISO-8859-1><title>Insert title here</title></head><body>This is First Page.<br>Including the Second Page Here <br><%@include file=secondpage.jsp%></body></html>

secondpage.jsp

<!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01 Transitional//ENhttp://www.w3.org/TR/html4/loose.dtd><html><head><meta http-equiv=Content-Type content=text/html; charset=ISO-8859-1>

</head><body>This is Second Page</body></html>

Output:- Calling secondpage.jsp

Your First JSP Page 04/28/09 03:44:52

74/148

Page 75: Jsp Tutorials

Calling firstpage.jsp

Your First JSP Page 04/28/09 03:44:52

75/148

Page 76: Jsp Tutorials

Stanadard Actions

Standard Actions

The JSP specifications define six standard actions, which can be grouped into two distinct categories. The two categoriesof Actions are as follows:-

Resource Actions.• JavaBean Actions•

The Resource Actions

Resource actions specify external resources that should be used with the JSP page. The following actions comes under thiscategory.

<jsp:include>:- The include action can be used to insert the output of both static and dynamic pages into the currentpage.

<jsp:forward>:- The forward action terminates the action of the current page and forwards the request to anotherresource, such as a static page, another JSP page, or a Java Servlet.

<jsp:plugin>:- The plugin action is used to insert Java components into a JSP page.•

The JavaBean Actions

The JavaBean actions are used to access server side JavaBeans within a JSP page. JavaBeans are the components whichused to make the structured data under a single name. JavaBean has some properties which are accessed with thesetter/getter method defined in the JavaBean class. The following tags are used to communicate with the JavaBeans:-

<jsp:useBean>:-The useBean action finds or creates an instance of an object. It also associates this object with animplicit object specified by the scope attribute (page, request, session, and application).

<jsp:setProperty>:- The setProperty action sets the properties of a Bean.• <jsp:getProperty>:-The getProperty action is used to retrieve the value of a given property and print it.•

Your First JSP Page 04/28/09 03:44:52

76/148

Page 77: Jsp Tutorials

<jsp:include> Action Example

<jsp:include> Action Example

Lets see how to use the <jsp:include to include the different files and generate the single output to the user. We will createincludeexample.jsp and secondpage.jsp files. The second file is included in the first file.

includeexample.jsp

<%@ page language=java contentType=text/html; charset=ISO-8859-1pageEncoding=ISO-8859-1%><!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01 Transitional//ENhttp://www.w3.org/TR/html4/loose.dtd><html><head><meta http-equiv=Content-Type content=text/html; charset=ISO-8859-1><title>Insert title here</title></head><body>This is First Page.<br>Including the Second Page Here <br><jsp:include page=secondpage.jsp/></body></html>

secondpage.jsp

<!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01 Transitional//ENhttp://www.w3.org/TR/html4/loose.dtd><html><head><meta http-equiv=Content-Type content=text/html; charset=ISO-8859-1>

</head><body>This is Second Page</body></html>

Output:- Calling secondpage.jsp

Your First JSP Page 04/28/09 03:44:52

77/148

Page 78: Jsp Tutorials

Calling includeexample.jsp

Your First JSP Page 04/28/09 03:44:52

78/148

Page 79: Jsp Tutorials

Comparison Between include Directive And include Action

Comparison Between include Directive And include Action

Although the <@include and <jsp:include both are used to add the inner pages into the outer pages but both are differentin the way the JSP handles. The following are the differences in both :-

<@include directive <jsp:include Actionfile attribute is present in the directive page is the attribute used in the jsp:include.

The values can be passes only by the queryString. The <jsp;param> is the tag which is used to pass the values to the innerpage. This makes code a little cleaner and easy to understand.

The content of the included page gets compiled at the compile timeand make as inline. So if we modify the inner page we need torecompile all the pages in order to get the changes.

The content is included at the runtime or request time, which means whenthe statement encountered for the inclusion then control is passed to theinner page and get the content. So there is no recompilation needed if theinner page modifies.

As the page is inline so the performance in the include directive ismore. The extra page need to compile so the response time is increased.

Your First JSP Page 04/28/09 03:44:52

79/148

Page 80: Jsp Tutorials

<jsp:forward> example

<jsp:forward> example

Lets create two pages one is where the user need to forward i.e. forward.jsp and other one is from which the user isforwarded without knowing i.e forwardexample.jsp

forward.jsp

<%@ page language=java contentType=text/html; charset=ISO-8859-1pageEncoding=ISO-8859-1%><!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01 Transitional//ENhttp://www.w3.org/TR/html4/loose.dtd><html><head><meta http-equiv=Content-Type content=text/html; charset=ISO-8859-1><title>Insert title here</title></head><body>This is Forwarded page.</body></html>forwardexample.jsp

<%@ page language=java contentType=text/html; charset=ISO-8859-1pageEncoding=ISO-8859-1%><!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01 Transitional//ENhttp://www.w3.org/TR/html4/loose.dtd><html><head><meta http-equiv=Content-Type content=text/html; charset=ISO-8859-1><title>Insert title here</title></head><body><jsp:forward page=forward.jsp/></body></html>

Output:-

Your First JSP Page 04/28/09 03:44:52

80/148

Page 81: Jsp Tutorials

Your First JSP Page 04/28/09 03:44:52

81/148

Page 82: Jsp Tutorials

JavaBean Actions Example

JavaBean Actions Example

Lets consider we have a bean names Person which has name and age as its properties. The below example will set and getthe properties of the Person bean in JSP.

Person.java

package com.visualbuilder.beans;

public class Person { private String name; private int age;

public String getName() { return name; }

public void setName(String name) { this.name = name; }

public int getAge() { return age; }

public void setAge(int age) { this.age = age; }}beanexample.jsp

<%@ page language=java contentType=text/html; charset=ISO-8859-1pageEncoding=ISO-8859-1%><!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01 Transitional//ENhttp://www.w3.org/TR/html4/loose.dtd><html><head><meta http-equiv=Content-Type content=text/html; charset=ISO-8859-1><title>Insert title here</title></head><body><jsp:useBean id=person class=com.visualbuilder.beans.Person/><jsp:setProperty name=person property=name value=Chris/><jsp:setProperty name=person property=age value=18/>The name is :- <jsp:getProperty name=person property=name /><br/>The age is :- <jsp:getProperty name=person property=age /><br/></body></html>

Your First JSP Page 04/28/09 03:44:52

82/148

Page 83: Jsp Tutorials

Output:-

Your First JSP Page 04/28/09 03:44:52

83/148

Page 84: Jsp Tutorials

Scopes in JSP

Bean Scopes in JSP

We have just seen the how beans can be used in the JSP page. The scope attribute in the <jsp:useBean> tag can be used todefine the scope and lifetime of the object created by the action. There are four scope available in the JSP.

page:- Objects with page scope are accessible only in that page and can not go beyond it. By default the scope isrequest.

1.

request:- Objects with request scope can persist with the request object and valid only till the request is valid.2. session:- Objects defined with session scopes will be available with the session. So for shopping cart or ecommerceapplication where the state need to managed we can use this cope more frequently.

3.

application:- Objects defined with application scopes will be available till the application remains in the memory.All static objects whose data does not change frequently will be defined with the application scope.

4.

The coming section will explain the example for the request scope. The session and application scopes will be discussedlater on.

Your First JSP Page 04/28/09 03:44:52

84/148

Page 85: Jsp Tutorials

Request Bean Scope Example

Request Bean Scope Example

The previous example is used and extend it to the request scope. We will set the property in one page and get the propertyin the next page. From first page we will forward the request to second page.

requestbeanscope.jsp

<%@ page language=java contentType=text/html; charset=ISO-8859-1pageEncoding=ISO-8859-1%><!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01 Transitional//ENhttp://www.w3.org/TR/html4/loose.dtd><html><head><meta http-equiv=Content-Type content=text/html; charset=ISO-8859-1><title>Insert title here</title></head><body><jsp:useBean id=person class=com.visualbuilder.beans.Person scope=request/><jsp:setProperty name=person property=name value=Chris/><jsp:setProperty name=person property=age value=18/><jsp:forward page=requestbeanexample1.jsp/></body></html>requestbeanscope1.jsp

<%@ page language=java contentType=text/html; charset=ISO-8859-1pageEncoding=ISO-8859-1%><!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01 Transitional//ENhttp://www.w3.org/TR/html4/loose.dtd><html><head><meta http-equiv=Content-Type content=text/html; charset=ISO-8859-1><title>Insert title here</title></head><body><jsp:useBean id=person class=com.visualbuilder.beans.Person scope=request/>The name is :- <jsp:getProperty name=person property=name /><br/>The age is :- <jsp:getProperty name=person property=age /><br/></body></html>Output:-

Your First JSP Page 04/28/09 03:44:52

85/148

Page 86: Jsp Tutorials

Your First JSP Page 04/28/09 03:44:52

86/148

Page 87: Jsp Tutorials

Implicit Objects

Implicit Objects

The Servlet also creates several objects to be used by the JSP engine. These objects are available for the JSP developerand they can use the objects in the JSP files without declaring the objects in the JSP. The following table will explain allthe implicit objects available in the JSP pages.

Object Description

outThe out object is an instantiation of a javax.servlet.jsp.JspWriter object. Thisobject may represent a direct reference to the output stream, a filtered stream, or anested JspWriter from another JSP.

request

Each time a client requests a page the JSP engine creates a new object to representthat request. This new object is an instance ofjavax.servlet.http.HttpServletRequest and is given parameters describing therequest.

response The response object is an instance of javax.servlet.http.HttpServletResponse and isused to send the response to the browser.

application The application is same as the ServletContext object in Servlet. It has the samemethods and interfaces that the ServletContext object have in Servlets.

session The session object is an instance of HttpSession and used to track informationabout a particular client. Each client has one global session object.

pageContext The pageContext object is used to represent the entire JSP page and containsinformation about the directives issued to the JSP page.

config The config object is an instantiation of javax.servlet.ServletConfig. It has thesame methods and interfaces that the ServletConfig object have in Servlet.

exception

The error handling methods described in . It is available only when the previousJSP page throws an uncaught exception and the <%@ page errorPage=... %> tagwas used. The exception object is a wrapper containing the exception thrownfrom the previous page.

page This object is an actual reference to the instance of the page. In other words we cansay , page object equal to this object.

The coming section will explain the examples of individual object.

Your First JSP Page 04/28/09 03:44:52

87/148

Page 88: Jsp Tutorials

Out Object Example

Out Object Example

We start now understanding the implicit object with the help of examples. First object is out. The next example will showhow do we format the output using the out object.

outexample.jsp

<%@ page language=java contentType=text/html; charset=ISO-8859-1pageEncoding=ISO-8859-1%><!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01 Transitional//ENhttp://www.w3.org/TR/html4/loose.dtd><html><head><meta http-equiv=Content-Type content=text/html; charset=ISO-8859-1><title>Insert title here</title></head><body> <%for(int i=0;i<10;i++){ for(int j=0;j<=i;j++){ out.print(*); } out.println(<br>); } %></body></html>Output:-

Your First JSP Page 04/28/09 03:44:52

88/148

Page 89: Jsp Tutorials

Your First JSP Page 04/28/09 03:44:52

89/148

Page 90: Jsp Tutorials

Request Object Example

Request Object Example

The request object is created for each request and once the response is submitted then it gets destroyed. The request objectis used to pass the information from one page to the other page if the pages are getting invoked during the requestlifecycle. The below example will print all the request attributes as well as it gets the information passed from outer pageto inner page.

requestexample.jsp

<%@ page language=java contentType=text/html; charset=ISO-8859-1pageEncoding=ISO-8859-1%><!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01 Transitional//ENhttp://www.w3.org/TR/html4/loose.dtd><html><head><meta http-equiv=Content-Type content=text/html; charset=ISO-8859-1><title>Insert title here</title></head><body><body><p><font size=5>Request Information:</font></p><table border=1 cellpadding=0 cellspacing=1><tr><td width=33%><b>Request Method:</b></td><tdwidth=67%><%=request.getMethod()%></td></tr><tr><td width=33%><b>Request URI:</b></td><tdwidth=67%><%=request.getRequestURI()%></td></tr><tr><td width=33%><b>Request Protocol:</b></td><tdwidth=67%><%=request.getProtocol()%></td></tr><tr><td width=33%><b>Path Info:</b></td><tdwidth=67%><%=request.getPathInfo()%></td></tr><tr><td width=33%><b>Path translated:</b></td><tdwidth=67%><%=request.getPathTranslated()%></td></tr><tr><td width=33%><b>Query String:</b></td><tdwidth=67%><%=request.getQueryString()%></td></tr><tr><td width=33%><b>Content length:</b></td><td

Your First JSP Page 04/28/09 03:44:52

90/148

Page 91: Jsp Tutorials

width=67%><%=request.getContentLength()%></td></tr><tr><td width=33%><b>Content type:</b></td><tdwidth=67%><%=request.getContentType()%></td></tr><tr><td width=33%><b>Server name:</b></td><tdwidth=67%><%=request.getServerName()%></td></tr><tr><td width=33%><b>Server port:</b></td><tdwidth=67%><%=request.getServerPort()%></td></tr><tr><td width=33%><b>Remote user:</b></td><tdwidth=67%><%=request.getRemoteUser()%></td></tr><tr><td width=33%><b>Remote address:</b></td><tdwidth=67%><%=request.getRemoteAddr()%></td></tr><tr><td width=33%><b>Remote host:</b></td><tdwidth=67%><%=request.getRemoteHost()%></td></tr><tr><td width=33%><b>Authorization scheme:</b></td><tdwidth=67%><%=request.getAuthType()%></td></tr></table><%request.setAttribute(information,This is information passed from outer page);%><jsp:include page=requestinner.jsp/>

</body></html>requestinner.jsp

<%@ page language=java contentType=text/html; charset=ISO-8859-1pageEncoding=ISO-8859-1%><!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01 Transitional//ENhttp://www.w3.org/TR/html4/loose.dtd><html><head><meta http-equiv=Content-Type content=text/html; charset=ISO-8859-1><title>Insert title here</title></head><body>The Passed value from the Outer page is :-&nbsp;<%=request.getAttribute(information)%>

Your First JSP Page 04/28/09 03:44:52

91/148

Page 92: Jsp Tutorials

</body></html>Output:-

Your First JSP Page 04/28/09 03:44:52

92/148

Page 93: Jsp Tutorials

Response Object Example

Response Object Example

The response object is used to send and set the information at client side. The cookies are the small files used to save theinformation in the client machine which can be used for some further actions and state maintenance. The below examplewill set one cookie and then send the user to other page where we access the cookie value.

responseexample.jsp

<%@ page language=java contentType=text/html; charset=ISO-8859-1pageEncoding=ISO-8859-1%><!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01 Transitional//ENhttp://www.w3.org/TR/html4/loose.dtd><html><head><meta http-equiv=Content-Type content=text/html; charset=ISO-8859-1><title>Insert title here</title></head><body> <% Cookie cookie = new Cookie (testcookie,Visualbuilder); cookie.setMaxAge(365 * 24 * 60 * 60); response.addCookie(cookie); response.sendRedirect(getcookie.jsp); %>

</body></html>getcookie.jsp

<%@ page language=java contentType=text/html; charset=ISO-8859-1pageEncoding=ISO-8859-1%><!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01 Transitional//ENhttp://www.w3.org/TR/html4/loose.dtd><html><head><meta http-equiv=Content-Type content=text/html; charset=ISO-8859-1><title>Insert title here</title></head><body> <%

Cookie[] cookies= request.getCookies(); for(int i=0;i<cookies.length;i++){ if(cookies[i].getName().equalsIgnoreCase(testcookie)){ out.println(Cookie Value is + cookies[i].getValue()); } }%></body>

Your First JSP Page 04/28/09 03:44:52

93/148

Page 94: Jsp Tutorials

</html>Output:-

Your First JSP Page 04/28/09 03:44:52

94/148

Page 95: Jsp Tutorials

Session Object Example

Session Object Example

The session object is an instance of HttpSession and used to track information about a particular client. Each client hasone global session object. When user send the fist request to the JSP engine it will issue a session id to track theinformation for the transaction. The below example will show the session id as well as the count which shows how manytimes the page is accessed during the current session.

sessionexample.jsp

<%@ page language=java contentType=text/html; charset=ISO-8859-1pageEncoding=ISO-8859-1%><!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01 Transitional//ENhttp://www.w3.org/TR/html4/loose.dtd><html><head><meta http-equiv=Content-Type content=text/html; charset=ISO-8859-1><title>Insert title here</title></head><body>Sesion id for the Session is :- <%=session.getId() %><br><% if (session.getAttribute(count) != null){ int count = Integer.parseInt((String)session.getAttribute(count)); count++; out.println(The number of times the page accessed + count ); session.setAttribute(count,String.valueOf(count)); }else{ session.setAttribute(count,1); out.println(The page is accessed for the first time); }

%></body></html>Output:- When user refershed the page with in same session.

Your First JSP Page 04/28/09 03:44:52

95/148

Page 96: Jsp Tutorials

When user opens a new browser a new session id is generated.

Your First JSP Page 04/28/09 03:44:52

96/148

Page 97: Jsp Tutorials

Application Object Example

Application Object Example

Unlike session object which created separately for each client browser, the application object created one for wholeapplication. This object remains in the memory once the application is initialized and destroyed once the application willbe removed from the server or the server shuts down. This is a static object which is shared by all the clients. Applicationobjects normally used to cache the data for better performance. We change the session example with the application objectand see what will be happen when we run the page in multiple browsers.

applicationexample.jsp

<%@ page language=java contentType=text/html; charset=ISO-8859-1pageEncoding=ISO-8859-1%><!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01 Transitional//ENhttp://www.w3.org/TR/html4/loose.dtd><html><head><meta http-equiv=Content-Type content=text/html; charset=ISO-8859-1><title>Insert title here</title></head><body>Sesion id for the Session is :- <%=session.getId() %><br> <% if (session.getAttribute(count) != null){ int count = Integer.parseInt((String)session.getAttribute(count)); count++; out.println(The number of times the page accessed + count ); session.setAttribute(count,String.valueOf(count)); }else{ session.setAttribute(count,1); out.println(The page is accessed for the first time); }

%></body></html>Output:- When user refershed the page.

When user opens a new browser.

Your First JSP Page 04/28/09 03:44:52

97/148

Page 98: Jsp Tutorials

Your First JSP Page 04/28/09 03:44:52

98/148

Page 99: Jsp Tutorials

Working With Forms-2

Working With HTML Form -2

The previous section has explained what all controls are used in HTML for creating the forms. Lets see with the help ofbelow example how do we get the form data in JSP page which is send by the user.

We need to first define which JSP page should be accessed when this form is submitted. This can be achieved by theaction attribute in the <form>. For example:- <form action=/login.jsp> will generate a request for the login.jsp pagewhen the submit button will be clicked for the form.

We will be creating the input1.jsp file which will show the data which user has sent from login.html page from theprevious example.

Example:-

<!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01 Transitional//ENhttp://www.w3.org/TR/html4/loose.dtd><html>

<head><meta http-equiv=Content-Language content=en-us><meta http-equiv=Content-Type content=text/html; charset=windows-1252><title>Login Form</title></head>

<body>

<p align=left><b>Login Form

</b></p>

<form method=POST action=login.jsp name=loginForm>

<table border=1 width=50% cellspacing=1 cellpadding=0 id=table1><tr><td width=50%>&nbsp;Login Name</td><td><input type=text name=loginName size=20></td></tr><tr><td width=50%>Password</td><td><input type=password name=password size=20></td></tr></table><p><input type=submit value=Submit name=B1><input type=reset value=Resetname=B2></p></form>

</body>

Your First JSP Page 04/28/09 03:44:52

99/148

Page 100: Jsp Tutorials

</html>JSP page:-

<%@ page language=java contentType=text/html; charset=ISO-8859-1pageEncoding=ISO-8859-1%><!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01 Transitional//ENhttp://www.w3.org/TR/html4/loose.dtd><html><head><meta http-equiv=Content-Type content=text/html; charset=ISO-8859-1><title>Login Form Data</title></head><body><b>Submitted Values are </b><table border=1 width=50% cellspacing=1 cellpadding=0 id=table1><tr><td width=50%>&nbsp;Login Name</td><td><%=request.getParameter(loginName) %></td></tr><tr><td width=50%>Password</td><td><%=request.getParameter(password) %></td></tr></table></body></html>Output:- The following screen will be displayed when login form will gets submitted.

Your First JSP Page 04/28/09 03:44:52

100/148

Page 101: Jsp Tutorials

Exception Object Example

Exception Object Example

Lets see how the exception object can be used in the JSP page. In the below example we will have two JSP files. Firstlywhich has errorPage attribute is set to second page and throws the exception. The second file has the isErrorpage set totrue and displays the exception with the help of exception implicit object.

exception.jsp

<%@ page language=java contentType=text/html; charset=ISO-8859-1pageEncoding=ISO-8859-1 errorPage=exceptionfirst.jsp%><!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01 Transitional//ENhttp://www.w3.org/TR/html4/loose.dtd><html><head><meta http-equiv=Content-Type content=text/html; charset=ISO-8859-1><title>Insert title here</title></head><body><%String str=null;str.charAt(0);%></body></html>exceptionfirst.jsp

<%@ page language=java contentType=text/html; charset=ISO-8859-1pageEncoding=ISO-8859-1 isErrorPage=true%><!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01 Transitional//ENhttp://www.w3.org/TR/html4/loose.dtd><html><head><meta http-equiv=Content-Type content=text/html; charset=ISO-8859-1><title>Insert title here</title></head><body>The exception which occured during the processing is :- <br><%=exception.toString() %></body></html>Output:-

Your First JSP Page 04/28/09 03:44:52

101/148

Page 102: Jsp Tutorials

Note:- Rest implicit objects will be discussed as and when their requirements occured in the applications.

Your First JSP Page 04/28/09 03:44:52

102/148

Page 103: Jsp Tutorials

Working With HTML Form

Working With HTML Form -1

HTML pages have also used to create the forms which gather the information from user in the interactive web pages. InHTML we have <form> tag and form controls which are used to create the forms in web pages. All the controls related toa particular form need to define inside the <form></form> tag.

The following table will explain the basic form controls available for form building in html.

Control Description Control Appearance Code

Text Box The control is used to accept the text valuesfrom the user. <INPUT type=text name=text1 >

Submit Button Submit is a special kind of button and used tosend the form control information to the server. <INPUT type=submit name=submit>

Reset Button Reset will remove all the control values andmake them default. <INPUT type=reset name=reset>

Normal ButtonNormal buttons are used to control some flowsprogramitically. We will discuss the controlslater in coming sections.

<INPUT type=button name=button>

Checkbox Used to show the user some multiple optionswhich user can choose as per his interest. <INPUT type=checkbox name=check1>

Radio buttonRadio button is used to show various possibleoptions to the user and permit it to select onlyone

<INPUT type=radio name=radio1>

Select List Select list the combo list shows to user.<select name=sel1 > <option value=1>1</option><optionvalue=2>2</option>.....</select>

File SelectUsed to show the user a file dialog and select thedialog. This generally used where user want toselect some files and upload it to server.

<INPUT type=file name=file1>

Hidden fields It will be used to pass some secret values whichis not shown to user with the other form values. <INPUT type=hidden name=hidden>

Password field Password field will be used to accept thepasswords. <INPUT type=password name=pass>

Note:- The browser will always submit the data as name/value pair from form. So all the controls need to have the nameattribute whose data you need to pass to the server.

The below is the sample login form:-

HTML page:-

<!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01 Transitional//ENhttp://www.w3.org/TR/html4/loose.dtd><html>

<head><meta http-equiv=Content-Language content=en-us>

Your First JSP Page 04/28/09 03:44:52

103/148

Page 104: Jsp Tutorials

<meta http-equiv=Content-Type content=text/html; charset=windows-1252><title>Login Form</title></head>

<body>

<p align=left><b>Login Form

</b></p>

<form name=loginForm >

<table border=1 width=50% cellspacing=1 cellpadding=0 id=table1><tr><td width=50%>&nbsp;Login Name</td><td><input type=text name=loginName size=20></td></tr><tr><td width=50%>Password</td><td><input type=password name=password size=20></td></tr></table><p><input type=submit value=Submit name=B1><input type=reset value=Resetname=B2></p></form>

</body>

</html>Output:-The above code will display the login form as follows:-

Your First JSP Page 04/28/09 03:44:52

104/148

Page 105: Jsp Tutorials

Working With Form Contd.

Working With Form Contd.

The previous section has explained what all controls are used in HTML for creating the forms. Lets see with the help ofbelow example how do we get the form data in JSP page which is send by the user.

We need to first define which JSP page should be accessed when this form is submitted. This can be achieved by theaction attribute in the <form>. For example:- <form action=/login.jsp> will generate a request for the login.jsp pagewhen the submit button will be clicked for the form.

We will be creating the input1.jsp file which will show the data which user has sent from login.html page from theprevious example.

Example:-

<!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01 Transitional//ENhttp://www.w3.org/TR/html4/loose.dtd><html>

<head><meta http-equiv=Content-Language content=en-us><meta http-equiv=Content-Type content=text/html; charset=windows-1252><title>Login Form</title></head>

<body>

<p align=left><b>Login Form

</b></p>

<form method=POST action=login.jsp name=loginForm>

<table border=1 width=50% cellspacing=1 cellpadding=0 id=table1><tr><td width=50%>&nbsp;Login Name</td><td><input type=text name=loginName size=20></td></tr><tr><td width=50%>Password</td><td><input type=password name=password size=20></td></tr></table><p><input type=submit value=Submit name=B1><input type=reset value=Resetname=B2></p></form>

Your First JSP Page 04/28/09 03:44:52

105/148

Page 106: Jsp Tutorials

</body>

</html>JSP page:-

<%@ page language=java contentType=text/html; charset=ISO-8859-1pageEncoding=ISO-8859-1%><!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01 Transitional//ENhttp://www.w3.org/TR/html4/loose.dtd><html><head><meta http-equiv=Content-Type content=text/html; charset=ISO-8859-1><title>Login Form Data</title></head><body><b>Submitted Values are </b><table border=1 width=50% cellspacing=1 cellpadding=0 id=table1><tr><td width=50%>&nbsp;Login Name</td><td><%=request.getParameter(loginName) %></td></tr><tr><td width=50%>Password</td><td><%=request.getParameter(password) %></td></tr></table></body></html>Output:- The following screen will be displayed when login form will gets submitted.

Your First JSP Page 04/28/09 03:44:52

106/148

Page 107: Jsp Tutorials

Form Validation -1

Form Validation -1

Form validation is the process of checking that a form has been filled in correctly before it is processed. For example:- Ifuser has asked to give the name and he enter some @! special symbols then it is not valid as these are not the correctname. There are two mainly two types of form validations: server-side (using JSP ASP, etc), and client-side (usually doneusing JavaScript). The following is the difference between the serverside and client side validations: -

Client side validation runs in the browser to check that the form values are of the correct type. JavaScript should alwaysbe used on the client sidesince it is supported by both Netscape and IE. (VBScript is supported only by IE). where as Server side validation checksthe code that is submitted to make sure it is correct.

The following example will show how do we use the javascript to validate the login form.

Example:-

<!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01 Transitional//ENhttp://www.w3.org/TR/html4/loose.dtd><html>

<head><meta http-equiv=Content-Language content=en-us><meta http-equiv=Content-Type content=text/html; charset=windows-1252><title>Registration Form</title></head><script>function validateForm(form){

if(form.firstName.value==''){ alert (First Name can not be blank); return false;}if(form.lastName.value==''){ alert (Last Name can not be blank); return false;}if(form.introduction.value==''){ alert (Introduce Yourself can not be blank); return false;}if(form.phone.value==''){ alert (Phone can not be blank); return false;}if(form.address.value==''){ alert (Address can not be blank); return false;}

Your First JSP Page 04/28/09 03:44:52

107/148

Page 108: Jsp Tutorials

if(form.city.value==''){ alert (City can not be blank); return false;}if(form.state.value==''){ alert (State can not be blank); return false;}}</script><body>

<p align=left><b>Registration Form</b></p>

<form name=registerationForm method=POST action=validateRegistration.jsponsubmit=return validateForm(document.registerationForm); >

<table border=1 width=70% cellspacing=1 cellpadding=0 id=table1><tr><td width=50%>First Name</td><td><input type=text name=firstName size=20></td></tr><tr><td width=50%>Last Name</td><td><input type=text name=lastName size=20></td></tr><tr><td width=50%>Introduce Yourself</td><td><textarea name=introduction cols=40 rows=10></textarea></td></tr><tr><td width=50%>Gender</td><td><input type=radio value=V1 checked name=radio1>male<input type=radio name=radio1 value=V2>female</td></tr><tr><td width=50%>Phone</td><td><input type=text name=phone size=20></td></tr><tr><td width=50%>Address</td><td><input type=text name=address size=20></td></tr><tr><td width=50%>City</td><td><input type=text name=city size=20></td></tr><tr><td width=50%>State</td><td><input type=text name=state size=20></td>

Your First JSP Page 04/28/09 03:44:52

108/148

Page 109: Jsp Tutorials

</tr><tr><td width=50%>Country</td><td><select size=1 name=country><option selected value=United Kingdom>United Kingdom</option><option>USA</option><option>Other</option></select></td></tr></table><p><input type=submit value=Submit name=B1><input type=reset value=Resetname=B2></p></form>

</body>

</html>Output:-

Your First JSP Page 04/28/09 03:44:52

109/148

Page 110: Jsp Tutorials

Your First JSP Page 04/28/09 03:44:52

110/148

Page 111: Jsp Tutorials

Form Validation-2

Form Validation-2

Lets see with the help of below example how the same validations, which is implemented in the JavaScript in the previousexample, will be implemented in the JSP page.

Example:-

<!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01 Transitional//ENhttp://www.w3.org/TR/html4/loose.dtd><html>

<head><meta http-equiv=Content-Language content=en-us><meta http-equiv=Content-Type content=text/html; charset=windows-1252><title>Registration Form</title></head>

<body>

<p align=left><b>Registration Form</b></p>

<form name=registerationForm method=POST action=validateRegistrationWithBean.jsp>

<table border=1 width=70% cellspacing=1 cellpadding=0 id=table1><% String errors=(String)request.getAttribute(errors); if(errors != null && errors.trim().length()>0){ out.println(<tr><td colspan='2'>The following are the errors with givendata<br>+errors+</td></tr>); }%><tr><td width=50%>First Name</td><td><input type=text name=loginName size=20value=<%=request.getParameter(loginName)!=null?request.getParameter(loginName):%>></td></tr><tr><td width=50%>Last Name</td><td><input type=text name=password size=20value=<%=request.getParameter(password)!=null?request.getParameter(password):%>></td></tr><tr><td width=50%>Introduce Yourself</td><td><textarea name=intro cols=40rows=10><%=request.getParameter(intro)!=null?request.getParameter(intro):%></textarea></td></tr><tr><td width=50%>Gender</td>

Your First JSP Page 04/28/09 03:44:52

111/148

Page 112: Jsp Tutorials

<td>

<% if(request.getParameter(gender)==null || request.getParameter(gender).equals(male)){ %><input type=radio value=male checked name=gender>male<input type=radio name=gender value=female>female<%}else{ %><input type=radio value=male name=gender>male<input type=radio name=gender checked value=female>female<%} %></td>

</tr><tr><td width=50%>Phone</td><td><input type=text name=phone size=20value=<%=request.getParameter(phone)!=null?request.getParameter(phone):%>></td></tr><tr><td width=50%>Address</td><td><input type=text name=address size=20value=<%=request.getParameter(address)!=null?request.getParameter(address):%>></td></tr><tr><td width=50%>City</td><td><input type=text name=city size=20value=<%=request.getParameter(city)!=null?request.getParameter(city):%>></td></tr><tr><td width=50%>State</td><td><input type=text name=state size=20value=<%=request.getParameter(state)!=null?request.getParameter(state):%>></td></tr><tr><td width=50%>Country</td><td><select size=1 name=country><option selected value=United Kingdom>United Kingdom</option><option value=USA>USA</option><option value=other>Other</option></select></td></tr></table><p><input type=submit value=Submit name=B1><input type=reset value=Reset name=B2></p></form>

</body>

</html>Validation JSP File is as follows:-

Your First JSP Page 04/28/09 03:44:52

112/148

Page 113: Jsp Tutorials

<%@ page language=java contentType=text/html; charset=ISO-8859-1pageEncoding=ISO-8859-1%><!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01 Transitional//ENhttp://www.w3.org/TR/html4/loose.dtd><html><head><meta http-equiv=Content-Type content=text/html; charset=ISO-8859-1>

</head><body><% String loginName=request.getParameter(loginName); String password=request.getParameter(password); String intro=request.getParameter(intro); String gender=request.getParameter(R1); String phone=request.getParameter(phone); String address=request.getParameter(address); String city=request.getParameter(city); String state=request.getParameter(state); String country=request.getParameter(country); String errors=;

if(loginName ==null || loginName.trim().length() ==0){ errors=errors+<li>Please enter the Login Name<br>; } if(password ==null || password.trim().length() ==0){ errors=errors+<li>Please enter the Password<br>; } if(intro ==null || intro.trim().length() ==0){ errors=errors+<li>Please enter the introduction<br>; } if(gender ==null || gender.trim().length() ==0){ errors=errors+<li>Please select Gender<br>; } if(phone ==null || phone.trim().length() ==0){ errors=errors+<li>Please enter phone<br>; } if(address ==null || address.trim().length() ==0){ errors=errors+<li>Please enter address<br>; } if(city ==null || city.trim().length() ==0){ errors=errors+<li>Please enter city<br>; } if(state ==null || state.trim().length() ==0){ errors=errors+<li>Please enter state<br>; } if(country ==null || country.trim().length() ==0){ errors=errors+<li>Please enter country<br>; } if( errors.trim().length() >0){

Your First JSP Page 04/28/09 03:44:52

113/148

Page 114: Jsp Tutorials

request.setAttribute(errors,errors); %><jsp:forward page=registerwithvalidation.jsp></jsp:forward><% }%><h1>The given data is Valid.</h1></body></html>Output:-

Your First JSP Page 04/28/09 03:44:52

114/148

Page 115: Jsp Tutorials

Your First JSP Page 04/28/09 03:44:52

115/148

Page 116: Jsp Tutorials

Using Beans for Form Data -1

Using Beans for Form Data -1

Most of the time form contains more than one fields. Then it is very difficult to use the request object for the formvalidation and controlling the fields. To solve the issue we have Java Beans which are used to create the structures whichcapture the data. We have seen initially that JSP has explicit tags to set and get the data from the Java Beans. Lets see howBean is used to capture and validate the Registration form data. this also makes our JSP code easy to read as the wholejava code is moved into the Bean class.

Example:-

<!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01 Transitional//ENhttp://www.w3.org/TR/html4/loose.dtd><html>

<head><meta http-equiv=Content-Language content=en-us><meta http-equiv=Content-Type content=text/html; charset=windows-1252><title>Registration Form</title></head>

<body>

<p align=left><b>Registration Form</b></p>

<form name=registerationForm method=POST action=validateRegistrationWithBean.jsp>

<table border=1 width=70% cellspacing=1 cellpadding=0 id=table1><% String errors=(String)request.getAttribute(errors); if(errors != null && errors.trim().length()>0){ out.println(<tr><td colspan='2'>The following are the errors with givendata<br>+errors+</td></tr>); }%><tr><td width=50%>First Name</td><td><input type=text name=loginName size=20value=<%=request.getParameter(loginName)!=null?request.getParameter(loginName):%>></td></tr><tr><td width=50%>Last Name</td><td><input type=text name=password size=20value=<%=request.getParameter(password)!=null?request.getParameter(password):%>></td></tr><tr><td width=50%>Introduce Yourself</td><td><textarea name=intro cols=40rows=10><%=request.getParameter(intro)!=null?request.getParameter(intro):%></textarea></td>

Your First JSP Page 04/28/09 03:44:52

116/148

Page 117: Jsp Tutorials

</tr><tr><td width=50%>Gender</td><td>

<% if(request.getParameter(gender)==null || request.getParameter(gender).equals(male)){ %> <input type=radio value=male checked name=gender>male <input type=radio name=gender value=female>female<%}else{ %> <input type=radio value=male name=gender>male <input type=radio name=gender checked value=female>female<%} %></td>

</tr><tr><td width=50%>Phone</td><td><input type=text name=phone size=20value=<%=request.getParameter(phone)!=null?request.getParameter(phone):%>></td></tr><tr><td width=50%>Address</td><td><input type=text name=address size=20value=<%=request.getParameter(address)!=null?request.getParameter(address):%>></td></tr><tr><td width=50%>City</td><td><input type=text name=city size=20value=<%=request.getParameter(city)!=null?request.getParameter(city):%>></td></tr><tr><td width=50%>State</td><td><input type=text name=state size=20value=<%=request.getParameter(state)!=null?request.getParameter(state):%>></td></tr><tr><td width=50%>Country</td><td><select size=1 name=country> <option selected value=United Kingdom>United Kingdom</option> <option value=USA>USA</option> <option value=other>Other</option></select></td></tr></table><p><input type=submit value=Submit name=B1><input type=reset value=Reset name=B2></p></form>

</body>

</html>

Your First JSP Page 04/28/09 03:44:52

117/148

Page 118: Jsp Tutorials

package com.visualbuilder.beans;

import javax.servlet.http.HttpServletRequest;

public class RegistrationBean {String loginName;String password;String intro;String gender;String phone;String address;String city;String state;String country;public String getLoginName() { return loginName;}public void setLoginName(String loginName) { this.loginName = loginName;}public String getPassword() { return password;}public void setPassword(String password) { this.password = password;}public String getIntro() { return intro;}public void setIntro(String intro) { this.intro = intro;}public String getGender() { return gender;}public void setGender(String gender) { this.gender = gender;}public String getPhone() { return phone;}public void setPhone(String phone) { this.phone = phone;}public String getAddress() { return address;}public void setAddress(String address) {

Your First JSP Page 04/28/09 03:44:52

118/148

Page 119: Jsp Tutorials

this.address = address;}public String getCity() { return city;}public void setCity(String city) { this.city = city;}public String getState() { return state;}public void setState(String state) { this.state = state;}public String getCountry() { return country;}public void setCountry(String country) { this.country = country;}public void validate(HttpServletRequest request){ String errors=;

if(loginName ==null || loginName.trim().length() ==0){ errors=errors+<li>Please enter the Login Name<br>; } if(password ==null || password.trim().length() ==0){ errors=errors+<li>Please enter the Password<br>; } if(intro ==null || intro.trim().length() ==0){ errors=errors+<li>Please enter the introduction<br>; } if(gender ==null || gender.trim().length() ==0){ errors=errors+<li>Please select Gender<br>; } if(phone ==null || phone.trim().length() ==0){ errors=errors+<li>Please enter phone<br>; } if(address ==null || address.trim().length() ==0){ errors=errors+<li>Please enter address<br>; } if(city ==null || city.trim().length() ==0){ errors=errors+<li>Please enter city<br>; } if(state ==null || state.trim().length() ==0){ errors=errors+<li>Please enter state<br>; } if(country ==null || country.trim().length() ==0){ errors=errors+<li>Please enter country<br>; }

Your First JSP Page 04/28/09 03:44:52

119/148

Page 120: Jsp Tutorials

if( errors.trim().length() >0){ request.setAttribute(errors,errors); } }}

Your First JSP Page 04/28/09 03:44:52

120/148

Page 121: Jsp Tutorials

Using Beans for Form Data -2

Using Beans for Form Data -2

The below is the code for the validate file. Now the JSP is setting the properties in the bean and calling the validatemethod for the validations.

<%@ page language=java contentType=text/html; charset=ISO-8859-1pageEncoding=ISO-8859-1%><!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01 Transitional//ENhttp://www.w3.org/TR/html4/loose.dtd><html><head><meta http-equiv=Content-Type content=text/html; charset=ISO-8859-1>

</head><body><jsp:useBean id=bean class=com.visualbuilder.beans.RegistrationBean/><jsp:setProperty name=bean property=*/><%com.visualbuilder.beans.RegistrationBeanregister=(com.visualbuilder.beans.RegistrationBean)pageContext.getAttribute(bean);register.validate(request);String errors= (String)request.getAttribute(errors);if( errors.trim().length() >0){%><jsp:forward page=registerwithbean.jsp></jsp:forward><%}%><h1>The given data is Valid.</h1></body></html>Output:- When form is submitted with invalid data then following screen will be displayed.

Your First JSP Page 04/28/09 03:44:52

121/148

Page 122: Jsp Tutorials

Your First JSP Page 04/28/09 03:44:52

122/148

Page 123: Jsp Tutorials

Mutipage Forms-1

Mutipage Forms-1

Some forms are very long and logically divided into separate long sections. To handle those forms in the JSP is to scatterthe form in multiple pages and then show the user those page in sequence. The muti page forms also used to show forshowing the wizards to the user which helps the user to show only the question based on the answers collected in theprevious sections. The previous example of registration is now divided into two parts and we have created the two pagesfor a single form.

Example:-

mutipage1.jsp

<!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01 Transitional//ENhttp://www.w3.org/TR/html4/loose.dtd><html>

<head><meta http-equiv=Content-Language content=en-us><meta http-equiv=Content-Type content=text/html; charset=windows-1252><title>Registration Form</title></head>

<body>

<p align=left><b>Registration Form</b></p><jsp:useBean id=bean class=com.visualbuilder.beans.RegistrationBean scope=session/><%com.visualbuilder.beans.RegistrationBeanregister=(com.visualbuilder.beans.RegistrationBean)session.getAttribute(bean);%><form name=registerationForm method=POST action=multipage2.jsp>

<table border=1 width=70% cellspacing=1 cellpadding=0 id=table1><% String errors=(String)request.getAttribute(errors); if(errors != null && errors.trim().length()>0){ out.println(<tr><td colspan='2'>The following are the errors with givendata<br>+errors+</td></tr>); }%><tr><td width=50%>First Name</td><td><input type=text name=loginName size=20value=<%=register.getLoginName()!=null?register.getLoginName():%>></td></tr><tr><td width=50%>Last Name</td><td><input type=text name=password size=20

Your First JSP Page 04/28/09 03:44:52

123/148

Page 124: Jsp Tutorials

value=<%=register.getPassword()!=null?register.getPassword():%>></td></tr><tr><td width=50%>Introduce Yourself</td><td><textarea name=intro cols=40rows=10><%=register.getIntro()!=null?register.getIntro():%></textarea></td></tr><tr><td width=50%>Gender</td><td>

<% if(register.getGender()==null || register.getGender().equals(male)){ %><input type=radio value=male checked name=gender>male<input type=radio name=gender value=female>female<%}else{ %><input type=radio value=male name=gender>male<input type=radio name=gender checked value=female>female<%} %></td>

</tr>

</table><p><input type=submit value=Submit name=B1><input type=reset value=Resetname=B2></p></form>

</body>

</html>Form :-

Your First JSP Page 04/28/09 03:44:52

124/148

Page 125: Jsp Tutorials

Your First JSP Page 04/28/09 03:44:52

125/148

Page 126: Jsp Tutorials

Mutipage Forms-2

Mutipage Forms-2

This is the second page of the form. The following is the code and form.

multipage2.jsp

<!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01 Transitional//ENhttp://www.w3.org/TR/html4/loose.dtd><html>

<head><meta http-equiv=Content-Language content=en-us><meta http-equiv=Content-Type content=text/html; charset=windows-1252><title>Registration Form</title></head>

<body>

<p align=left><b>Registration Form</b></p><jsp:useBean id=bean class=com.visualbuilder.beans.RegistrationBean scope=session/><jsp:setProperty name=bean property=loginName/><jsp:setProperty name=bean property=password/><jsp:setProperty name=bean property=gender/><jsp:setProperty name=bean property=intro/><form name=registerationForm method=POST action=multipage3.jsp>

<table border=1 width=70% cellspacing=1 cellpadding=0 id=table1><%com.visualbuilder.beans.RegistrationBeanregister=(com.visualbuilder.beans.RegistrationBean)session.getAttribute(bean);

String errors=(String)request.getAttribute(errors); if(errors != null && errors.trim().length()>0){ out.println(<tr><td colspan='2'>The following are the errors with givendata<br>+errors+</td></tr>);}%>

<tr><td width=50%>Phone</td><td><input type=text name=phone size=20value=<%=register.getPhone()!=null?register.getPhone():%>></td></tr><tr><td width=50%>Address</td><td><input type=text name=address size=20value=<%=register.getAddress()!=null?register.getAddress():%>></td></tr>

Your First JSP Page 04/28/09 03:44:52

126/148

Page 127: Jsp Tutorials

<tr><td width=50%>City</td><td><input type=text name=city size=20value=<%=register.getCity()!=null?register.getCity():%>></td></tr><tr><td width=50%>State</td><td><input type=text name=state size=20value=<%=register.getState()!=null?register.getState():%>></td></tr><tr><td width=50%>Country</td><td><select size=1 name=country><option selected value=United Kingdom>United Kingdom</option><option value=USA>USA</option><option value=other>Other</option></select></td></tr></table><p><input type=submit value=Submit name=B1><input type=reset value=Resetname=B2></p></form>

</body>

</html>Form:-

Your First JSP Page 04/28/09 03:44:52

127/148

Page 128: Jsp Tutorials

Mutipage Forms-3

Mutipage Forms-3

This page is responsible for the validation. If validation fails it will again transfer the control to the first page with theerrors.

multipage3.jsp

<%@ page language=java contentType=text/html; charset=ISO-8859-1pageEncoding=ISO-8859-1%><!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01 Transitional//ENhttp://www.w3.org/TR/html4/loose.dtd><html><head><meta http-equiv=Content-Type content=text/html; charset=ISO-8859-1>

</head><body><jsp:useBean id=bean class=com.visualbuilder.beans.RegistrationBean scope=session/><jsp:setProperty name=bean property=phone/><jsp:setProperty name=bean property=address/><jsp:setProperty name=bean property=city/><jsp:setProperty name=bean property=country/><jsp:setProperty name=bean property=state/>

<%com.visualbuilder.beans.RegistrationBeanregister=(com.visualbuilder.beans.RegistrationBean)session.getAttribute(bean);

register.validate(request); String errors= (String)request.getAttribute(errors); if( errors != null && errors.trim().length() >0){%><jsp:forward page=multipage1.jsp></jsp:forward><%}%><h1>The given data is Valid.</h1></body></html>Output:- The following page wil be displayed if any errors occured in the form.

Your First JSP Page 04/28/09 03:44:52

128/148

Page 129: Jsp Tutorials

Your First JSP Page 04/28/09 03:44:52

129/148

Page 130: Jsp Tutorials

Shopping Cart in JSP-1

Shopping Cart in JSP-1

Now we will be using all the concepts for the JSP learnt so far to implement in the shopping cart. We have a product pagewhere user select the product and add it to cart. Once user has product in the cart he can see the basket page to view theproducts.

Example :-

ProductUtilities.java

ProductUtilities is the class which will have the hardcoded values for products and supplied the products for adding it tobasket and also to display the products to user for choice.

package com.visualbuilder.shopping;

import java.util.ArrayList;import java.util.HashMap;import java.util.List;

public class ProductUtilities {

public static HashMap getProductsAsMap() { HashMap<String, ProductBean> products= new HashMap<String, ProductBean>(); products.put(P1, new ProductBean(P1,Flower,10)); products.put(P2, new ProductBean(P2,Chair,200)); products.put(P3, new ProductBean(P3,Table,400)); products.put(P4, new ProductBean(P4,Microwave,400)); return products;}public static List getProductsAsList() { List<ProductBean> products= new ArrayList<ProductBean>(); products.add(new ProductBean(P1,Flower,10)); products.add(new ProductBean(P2,Chair,200)); products.add( new ProductBean(P3,Table,400)); products.add( new ProductBean(P4,Microwave,400)); return products;}

}ProductBean.java

This is the actual bean for the product. All product has code, name, price and quantity as the properties.

package com.visualbuilder.shopping;

public class ProductBean {String prodCode;

Your First JSP Page 04/28/09 03:44:52

130/148

Page 131: Jsp Tutorials

String prodName;double price;int qty=1; public int getQty() { return qty; } public void setQty(int qty) { this.qty = qty; } public ProductBean(){ this.prodCode=; this.prodName=; } public ProductBean(String code, String name, double price){ this.prodCode=code; this.prodName=name; this.price=price; } public String getProdCode() { return prodCode; } public void setProdCode(String prodCode) { this.prodCode = prodCode; } public String getProdName() { return prodName; } public void setProdName(String prodName) { this.prodName = prodName; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } }

Your First JSP Page 04/28/09 03:44:52

131/148

Page 132: Jsp Tutorials

Shopping Cart in JSP-2

Shopping Cart in JSP-2

The below are the remaining code for the Basket.

Basket.java

package com.visualbuilder.shopping;

import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;

public class Basket { HashMap<String, ProductBean> prodList =new HashMap<String, ProductBean>(); String selectedProducts;

public String getSelectedProdcuts() { return selectedProducts; } public void setSelectedProducts(HttpServletRequest request) { String[] ar = request.getParameterValues(selectedProducts); if(ar != null && ar.length >0){ HashMap<String, ProductBean> map=ProductUtilities.getProductsAsMap(); for(int i=0;i<ar.length;i++){ ProductBean bean =map.get(ar[i]); if(bean != null){ ProductBean product= prodList.get(ar[i]); if(product != null){ product.setQty(product.getQty()+1); }else{ product=bean; } prodList.put(product.getProdCode(),product); } } }}

public HashMap<String, ProductBean> getProdList() { return prodList; } public void setProdList(HashMap<String, ProductBean> prodList) { this.prodList = prodList; }}Productpage.jsp

Your First JSP Page 04/28/09 03:44:52

132/148

Page 133: Jsp Tutorials

<%@ page language=java contentType=text/html; charset=ISO-8859-1pageEncoding=ISO-8859-1%><%@page import=com.visualbuilder.shopping.*,java.util.*; %><!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01 Transitional//ENhttp://www.w3.org/TR/html4/loose.dtd><html><head><meta http-equiv=Content-Type content=text/html; charset=ISO-8859-1>

</head><body><form action=addtobasket.jsp method=post><table border=1 > <tr><th>Product Code</th><th>Product Name</th><th>ProductPrice</th><th>&nbsp;</th></tr><% List<ProductBean> produList= ProductUtilities.getProductsAsList(); for (int i=0;i<produList.size();i++){ ProductBean bean = produList.get(i);%><tr><td><%=bean.getProdCode() %></td><td><%=bean.getProdName()%></td><td><%=bean.getPrice() %></td><td><input type=checkboxname=selectedProducts value=<%=bean.getProdCode()%>></td></tr><%} %></table><input type=submit value=AddToCart></form></body></html>Product Form:-

Your First JSP Page 04/28/09 03:44:52

133/148

Page 134: Jsp Tutorials

Shopping Cart in JSP-3

Shopping Cart in JSP-3

The following is the code and form for addtocart page and basket page of the shopping cart.

<%@ page language=java contentType=text/html; charset=ISO-8859-1pageEncoding=ISO-8859-1%><%@page import=com.visualbuilder.shopping.*,java.util.*; %><!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01 Transitional//ENhttp://www.w3.org/TR/html4/loose.dtd><html><head><meta http-equiv=Content-Type content=text/html; charset=ISO-8859-1>

</head><body><form action=addtobasket.jsp method=post><table> <tr><th>Product Code</th><th>Product Name</th><th>ProductPrice</th><th>Quantity</th></tr>

<% Basket basket = (Basket)session.getAttribute(basket); HashMap<String,ProductBean> prodList= basket.getProdList(); Iterator it=prodList.keySet().iterator(); double totalCost=0.0; while(it.hasNext()){ ProductBean bean = prodList.get(it.next()); totalCost=totalCost+bean.getQty()*bean.getPrice();%><tr><td><%=bean.getProdCode() %></td><td><%=bean.getProdName()%></td><td><%=bean.getPrice() %></td><td><%=bean.getQty() %></td></tr>

<%} %><tr><td>&nbsp;</td><td>&nbsp;</td><td><b>Total</b></td><td><%=totalCost%></td></tr></table><a href=productpage.jsp>Go to Product Page</a><br></form></body></html>Form :-

Your First JSP Page 04/28/09 03:44:52

134/148

Page 135: Jsp Tutorials

<%@ page language=java contentType=text/html; charset=ISO-8859-1pageEncoding=ISO-8859-1%><%@page import=com.visualbuilder.shopping.*,java.util.*; %><!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01 Transitional//ENhttp://www.w3.org/TR/html4/loose.dtd><html><head><meta http-equiv=Content-Type content=text/html; charset=ISO-8859-1>

</head><body>

<jsp:useBean id=basket class=com.visualbuilder.shopping.Basketscope=session></jsp:useBean><%basket.setSelectedProducts(request);%>Products Added succesfully in Basket.<br><a href=productpage.jsp>Go to Product Page</a><br><a href=basketpage.jsp>Go to Basket</a><br></body></html>Form :-

Your First JSP Page 04/28/09 03:44:52

135/148

Page 136: Jsp Tutorials

JDBC and JSP

JDBC and JSP

This section will explain how do we can use the JDBC code in the JSP page. The below example will get the data fromthe customer table of the database and display in the HTML table. The Customer table has only one row and has ID andname as columns.

Example:-

<%@ page language=java contentType=text/html; charset=ISO-8859-1pageEncoding=ISO-8859-1%><%@page import=java.sql.*; %><!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01 Transitional//ENhttp://www.w3.org/TR/html4/loose.dtd><html><head><meta http-equiv=Content-Type content=text/html; charset=ISO-8859-1><title>Insert title here</title></head><body><% Connection con = null; Statement stmt = null; try{ Class.forName(com.mysql.jdbc.Driver); con=DriverManager.getConnection(jdbc:mysql://localhost:3309/test,root,root); stmt= con.createStatement(); ResultSet rs= stmt.executeQuery(select * from Customer); out.println(Retreived Data is as follows:-<br>); while (rs.next()){ out.println(ID is + rs.getInt(id)+<br>);

out.println(Name is + rs.getString(name)+<br>); } }catch(Exception e){ e.printStackTrace(); out.println(Exception Occured); }finally{ if(con != null) con.close(); if(stmt != null) stmt.close(); }

%>

</body></html>Output:- The following screen will be displayed when the file is run.

Your First JSP Page 04/28/09 03:44:52

136/148

Page 137: Jsp Tutorials

Your First JSP Page 04/28/09 03:44:52

137/148

Page 138: Jsp Tutorials

Data Sources in JSP

Data Sources in JSP

Traditional JDBC has the provision to register the driver classes before it is actually used. A driver that is accessed via aDataSource object does not register itself with the DriverManager . Rather, a DataSource object is retrieved though alookup operation and then used to create a Connection object.

Being registered with a JNDI naming service gives a DataSource object two major advantages over the DriverManager .First, an application does not need to hardcode driver information, as it does with the DriverManager . A programmer canchoose a logical name for the data source and register the logical name with a JNDI naming service.

Example:-

The following is the code of defining the datasource in the Tomcat server. We need to add the following resource in theTomcat's server.xml file.

<Context docBase=JSPExample path=/JSPExample reloadable=truesource=org.eclipse.jst.j2ee.server:JSPExample> <Resource name=jdbc/TestDB auth=Container type=javax.sql.DataSourcemaxActive=100 maxIdle=30 maxWait=10000 username=root password=root driverClassName=com.mysql.jdbc.Driverurl=jdbc:mysql://localhost:3309/test?autoReconnect=true/></Context>The following code will bind the JNDI resource with the current application.

<resource-ref> <description>DB Connection</description> <res-ref-name>jdbc/TestDB</res-ref-name> <res-type>javax.sql.DataSource</res-type> <res-auth>Container</res-auth></resource-ref>The following code will use the data source and gets the data from the server.

<%@ page language=java contentType=text/html; charset=ISO-8859-1pageEncoding=ISO-8859-1%><%@page import=javax.naming.*,java.sql.*,javax.sql.*; %><!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01 Transitional//ENhttp://www.w3.org/TR/html4/loose.dtd><html><head><meta http-equiv=Content-Type content=text/html; charset=ISO-8859-1><title>Insert title here</title></head><body><% Context initContext = new InitialContext(); Context envContext = (Context)initContext.lookup(java:/comp/env); DataSource ds = (DataSource)envContext.lookup(jdbc/TestDB); Connection con = null;

Your First JSP Page 04/28/09 03:44:52

138/148

Page 139: Jsp Tutorials

Statement stmt = null; try{ con = ds.getConnection(); stmt= con.createStatement(); ResultSet rs= stmt.executeQuery(select * from Customer); out.println(Retreived Data is as follows:-<br>); while (rs.next()){ out.println(ID is + rs.getInt(id)+<br>);

out.println(Name is + rs.getString(name)+<br>); } }catch(Exception e){ e.printStackTrace(); out.println(Exception Occured); }finally{ if(con != null) con.close(); if(stmt != null) stmt.close(); }%></body></html>Output:- The following screen will be displayed when the above program is run.

Your First JSP Page 04/28/09 03:44:52

139/148

Page 140: Jsp Tutorials

Data Source and Servlet

Data Source and Servlet

The following example will explain how do we use the datasource code inside the servlet. We will have a form where wewill have two fields one for id and another one for name. When user submit the form it invoke the database servlet whichwill insert the values in the database table.

Example:-

JSP Form:-

<%@ page language=java contentType=text/html; charset=ISO-8859-1pageEncoding=ISO-8859-1%><!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01 Transitional//ENhttp://www.w3.org/TR/html4/loose.dtd><html><head><meta http-equiv=Content-Type content=text/html; charset=ISO-8859-1>

</head><body><form method=POST action=/JSPExample/insertData>

<table border=1 width=70% cellspacing=1 cellpadding=0 id=table1><tr><td width=50%>ID</td><td><input type=text name=id size=20></td></tr><tr><td width=50%>Name</td><td><input type=text name=name size=20></td></tr></table><p><input type=submit value=Submit name=B1><input type=reset value=Resetname=B2></p></form></body></html>Form:-

Your First JSP Page 04/28/09 03:44:52

140/148

Page 141: Jsp Tutorials

Your First JSP Page 04/28/09 03:44:52

141/148

Page 142: Jsp Tutorials

Data Source and Servlet Contd..

Data Source and Servlet Contd..

The servlet code and its entry in the web.xml is as follows:-

Example:-

Web.xml:-

<servlet> <servlet-name>insertData</servlet-name> <servlet-class>com.visualbuilder.servlet.InsertData</servlet-class></servlet><servlet-mapping> <servlet-name>insertData</servlet-name> <url-pattern>/insertData</url-pattern></servlet-mapping>Servlet Code:-

package com.visualbuilder.servlet;

import java.io.IOException;import java.sql.Connection;import java.sql.Statement;

import javax.naming.Context;import javax.naming.InitialContext;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.sql.DataSource;

public class InsertData extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response)throwsIOException,ServletException{ doPost(request,response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throwsIOException,ServletException{ String id=request.getParameter(id); String name=request.getParameter(name); Connection con = null; Statement stmt = null; try{ Context initContext = new InitialContext(); Context envContext = (Context)initContext.lookup(java:/comp/env); DataSource ds = (DataSource)envContext.lookup(jdbc/TestDB); con = ds.getCnnection();

Your First JSP Page 04/28/09 03:44:52

142/148

Page 143: Jsp Tutorials

stmt=con.createStatement(); stmt.executeUpdate(insert into customer values(+id+,'+name+')); }catch(Exception e){ e.printStackTrace(); }finally{ try{ if(con != null) con.close(); if(stmt != null) stmt.close(); }catch(Exception e){} } response.sendRedirect(/JSPExample/database/datasourceexample.jsp); }}Output:- When the data is entered it will be displayed on the page.

Your First JSP Page 04/28/09 03:44:52

143/148

Page 144: Jsp Tutorials

Handling Transaction in JSP

Handling Transaction in JSP

Transactions in JSP is same as the transactions in JDBC. A transaction is defined as the one task which can be dividedinto multiple tasks. The transactions can be controlled by setting the properties setAutoCommit(false) on connectionobjects and then calling the rollback() or commit() methods as per the requirement. The below example is calling therollback() before commit() so there is no database update in the customer table and no new record gets inserted.

Example:-

<%@ page language=java contentType=text/html; charset=ISO-8859-1pageEncoding=ISO-8859-1%><%@page import=javax.naming.*,java.sql.*,javax.sql.*; %><!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01 Transitional//ENhttp://www.w3.org/TR/html4/loose.dtd><html><head><meta http-equiv=Content-Type content=text/html; charset=ISO-8859-1><title>Insert title here</title></head><body><% Context initContext = new InitialContext(); Contxt envContext = (Context)initContext.lookup(java:/comp/env); DataSource ds = (DataSource)envContext.lookup(jdbc/TestDB); Connction con = null; Statement stmt = null; try{ con = ds.getConnection();

con.setAutoCommit(false); stmt= con.createStatement(); stmt.executeUpdate(insert into customer values(2,'transaction'));

con.rollback(); con.commit(); ResultSet rs= stmt.executeQuery(select * from Customer); out.println(Retreived Data is as follows:-<br>); while (rs.next()){ out.println(ID is + rs.getInt(id)+<br>);

out.println(Name is + rs.getString(name)+<br>); } }catch(Exception e){ e.printStackTrace(); out.println(Exception Occured); }finally{ if(con != null) con.close(); if(stmt != null) stmt.close(); }%>

Your First JSP Page 04/28/09 03:44:52

144/148

Page 145: Jsp Tutorials

</body></html>Output:-

Your First JSP Page 04/28/09 03:44:52

145/148

Page 146: Jsp Tutorials

Calling Stored Procedure

Calling Stored Procedure

Stored procedures and functions helps to optimize the application which requires heavy database interaction. Thefollowing section will explain how do we call the stored procedures stored in MySql database and gets the result in JSP.

Example:-

The following is the code for the procedure which will add 2 numbers num1 and num2 and return the result.

DELIMITER $$

DROP PROCEDURE IF EXISTS `test`.`TestProc` $$CREATE DEFINER=`root`@`localhost` PROCEDURE `TestProc`(in num1 int,in num2int, out result int)BEGINSet result := num1+num2;END $$

DELIMITER ;The following is the code for the JSP page which will pass the values and get the out parameter from the procedure andprints it on JSP page.

<%@ page language=java contentType=text/html; charset=ISO-8859-1pageEncoding=ISO-8859-1%><%@page import=javax.naming.*,java.sql.*,javax.sql.*; %><!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01 Transitional//ENhttp://www.w3.org/TR/html4/loose.dtd><html><head><meta http-equiv=Content-Type content=text/html; charset=ISO-8859-1><title>Insert title here</title></head><body><% Context initContext = new InitialContext(); Context envContext = (Context)initContext.lookup(java:/comp/env); DataSource ds = (DataSource)envContext.lookup(jdbc/TestDB); Connection con = null; CallableStatement stmt = null; try{ con = ds.getConnection(); stmt= con.prepareCall(Call TestProc(?,?,?)); int result=0; stmt.setInt(1,10); stmt.setInt(2,5); stmt.registerOutParameter(3,Types.INTEGER); stmt.executeUpdate(); result = stmt.getInt(3);

Your First JSP Page 04/28/09 03:44:52

146/148

Page 147: Jsp Tutorials

out.println(result); }catch(Exception e){ e.printStackTrace(); out.println(Exception Occured); }finally{ if(con != null) con.close(); if(stmt != null) stmt.close(); }%></body></html>Output:- The above program will print 15 on screen.

Your First JSP Page 04/28/09 03:44:52

147/148

Page 148: Jsp Tutorials

Lifecycle of JSP

Lifecycle of JSP

When any request comes for the JSP the JSP engine checks whether the JSP is loaded in the memory or not. If it is notthen it brings the JSP page and compiled the JSP page. The JSP is then converted into the Servlet. The lifecycle of the JSPalso involved three methods like Servlets. The methods are as follows:-

jspInit() :- This calls by the server when the JSP page is firstly loaded in the memory.• jspService():- This method will be called for all the requests.• jspDestroy():- This method will be called when the JSP's object is removed from the Server's memory.•

The jspService method is container managed method and therefore it can not be overridden by any JSP page. But the othertwo methods can be overridden in the JSP page. The jspInit() method mostly used to set the cache and resources for theJSP page and jspDestroy() method is used to free the resources at the time the JSP page is offloaded or server is rebooted.When we explain the database interaction then we will show how to override both methods.

Date entered : 13th Sep 2006

Rating :No Rating

Submitted by : visualbuilder

Copyright Visualbuilder.com 1999-2006Document created date: 28 Apr 2009

Your First JSP Page 04/28/09 03:44:52

148/148