You are on page 1of 41

JAVA SERVER PAGES(JSP)

Java server pages (JSP) is based on java languages and used to develop dynamic web pages JSP was developed by Sun Microsystems to allow server side development. JSP files are HTML files with special Tags containing Java source code that provide the dynamic content.JSP provide excellent server side scripting support for creating database driven web applications. JSP is a java technology which allows developers to create wide ranges of web services like ecommerce, banking ,corporate intranet banking. JSP combines HTML, XML, Java Servlet and JavaBeans technologies into one highly productive technology which allow web developers to develop reliable, high performance and platform independent web applications . WHY JSP? JSP is easy to learn. as JSP is based on java it provide robust plateform for web development. JSP file contains the HTML , XML , Java Servlet and Java Beans technologies. you can take one JSP file move it to the different plateform. web server or JSP servlet engine. ADVANTAGES OF JSP 1.Write once run anywhere:- As JSP is based on java so , it provide it plateform independent functionality .once the program of JSP is written it can be deployed or run on any JSP enabled server. without rewriting the changes 2.Uses Servlet API:-If you are a servlet developer, then it is easy to move over to JSP. In fact, servlet developers are at a distinct advantage because JSP is nothing but a high-level abstraction of servlets. You can do almost anything that can be done with servlets using JSP in a easy way. 3.Separate dynamic part from the static:- JSP provide a new feature that it separate a dynamic part of program from the static HTML part 4. JSP container provide easy way for accessing objects and actions. Compatibility of JSP with ASP , ASP.net ,and Servlet Comparison between JSP and ASP Functionally both the languages are same with some differences. JSP is developed by Sun Microsystems so it acquire the features of java .while ASP is developed by Microsoft .JSP is plateform independent it run on any operating system that confirm to the J2EE specifications. Whereas ASP is mostly found on Microsoft platforms i.e. NT, JSP allow component reuse by using JavaBeans and EJBs. ASP provides the use of COM / ActiveX controls. Comparison of JSP with ASP.net The main difference between JSP and ASP .net is that ASP. net is based Microsoft .NET frame work. but JSP is idependent just like java. Comparison of JSP with Servlet A java class which provide special side services is called server.but t is hard work to write

HTML code in Servlets. In Servlets number of println statements are used to generate HTML. JSP pages are converted to Servlets so actually can do the same thing as old Java Servlets. JSP ARCHITECTURE JSPs are built on SUN Microsystems' servlet technology. JSPs are HTML page with special JSP tags. These JSP tags can contain Java code. The JSP file extension is .jsp . The JSP engine parses the .jsp and creates a Java servlet source file. when first time jsp file compile , the JSP is probably slower the first time it is accessed. Any time after this the special compiled servlet is executed and is therefore returns faster. SETTING UP JSP ENVIRONMENT 1.Download the latest JDK . 2.Setting the path and class path for window 2000 and XP edit the environment variables control panel-->system-->Environment variable 3.Download JSP environment. FIRST JAVA PAGE A JavaServer Page, is a web page which is embedded Java code. Java code is executed in the server side and merge with the static elements of the web page such as HTML tags then returns the result which is plain old HTML code, JavaScript and CSS to the web browser.

<%@page contentType="text/html" pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>JSP Page!</title> </head> <body> <h1> <% out.println("Hello to all!"); %> </h1> </body> </html>

JSP is composed of HTML and java code. java code is embedded between the notations <% and %> and it is called Scriplet .Inside the scriptlet block, we call the method println of the out object to print the text "Hello to all" JSP SCRIPTING ELEMENTS JSP scripting allows you to add java code the servlet which is generated from the jsp page. These are the forms of scripting elements such ascomments, expression , scriptlet , declaration and expression language. JSP Comments JSP comments are used to explain the complicated logic code or to mark some region inside

a JSP page for later changes. Comments in JSP is declared inside a JSP page as follows: comments are embedded inside <%-- and --%>

<%-- This is a JSP comment for single line --%> <%-This is a JSP comment for multiple lines --%> JSP Expressions Expression is used to insert values directly to the output. Syntax of expression is as follows <%= expression %> there is no space between <% and = for example: To show the current date and time

Date : <%= new java.util.Date() %> JSP Scriptlet Scriplet are just like Expressions without having "=" equal sign. any java code can be insert inside the scriplet. Syntax of Scriptlet

<% // any java source code here %> JSP Declaration If you want to define methods or fields you can use JSP declaration. The JSP declaration is surrounded by the sign <%! and %>. Syntax to declare a variable

<%! int a = 30; %> here variable a is declare JSP Directive tag JSP directive tag gives special information about the page to the JSP engine. Syntax of Directive tag

Directive tag ( <%@ directive ... %> ) there are mainly three type of directive tags 1.page:- used to provide the information about the page .2.include: - include is used to include a file in a JSP page.

3.tag library:-taglib is used to use the custom tags in the JSP pages (custom tags allows us to defined our own tags).

JSP LIFE CYCLE JSP Life cycle can be divided into four phases 1.Translation:In translation phase, JSP engine translate JSP page into its page implementation class if the syntax is correct. This class is actually a standard Java servlet. After that, JSP engine compiles the source file into class file and ready for use. When the container get the request, then it checks for the changes in the JSP page since it was last translated. If no changes was occur, JSP loads the servlet otherwise the process of check occurs ,then it translate and compile again. Because the compilation process takes time so JSP engine wants to minimize it to increase the performance of the page processing .2.Initialization:JSP engine loads the class file and create an instance of of the servlet to handle processing of the initial request. JSP engines will call a method jspInit() to initialize the a servlet. jspInit method is generated during the translation phase which is normally used for initializing application-level parameters and resource

<%! public void jspInit() { // write custom here } %>

.3.Execution:After the initialization phase, the web container calls jspService() to handle the request and returning a response to the client. Each request is handled in a separate thread. 4.Finalization:- In the finalization phase, the web container calls the method jspDestroy(). This method is used to clean up memory and resources.

<%! public void jspInit() { // write custom code here //to cleanup the resources } %> JSP IMPLICIT OBJECTS These objects are available for the JSP developer and they can use the objects in the JSP files without declaring the objects in the JSP. JSP container provides a list of instantiated objects for you to access different kind of data in a web application. These objects are called implicit objects as they are automatically available for the implement. The following is the list of few implicit objects used in JSP. request object response objectsession objectout objectpagecontext objectconfig object exception objectapplication object

JSP FORM PROCESSING The browser uses two methods to pass information to web server. These methods are GET Method and POST Method. GET Method The GET method is the defualt method to pass information from browser to web server. The GET method is used to send request to the server. The page and the encoded information are separated by the ? character as follows: http://www.r4r.co.in/hello?key1=value1&key2=value2 Don't send sensitive information like password using GET method because they are not safe. POST method is safe to pass sensible information. POST METHOD The post method is good method to passing information to a backend program . it sends information as a separate message. This message comes to the backend program in the form of the standard input which you can parse and use for your processing. To handle this type of request JSP uses two methods 1.getparameter method to read simple parameter. 2.getInputStream method to read binary data stream coming from the client. READING OF DATA USING JSP JSP used form data parsing automatically depending on the situation. following are the methods which used by the JSP .1.getParameter():-To get the value of a form parameter you use request.getParameter() 2.getParametervalue():-if the parameter appears more than once and returns multiple values, than use this for example in case of chekbox 3.getParametername():- if you want complete list of all parameters in the current request than used this method .4.getInputStream() :-getInputStream() is used to read binary data comes from the client side.

JSP PROGRAM FOR CHECKBOX USING GET METHOD AND POST METHOD First to create html form using checkbox <html> <body> <form action="form.jsp" method="POST" target="_blank"> <input type="checkbox" name="java" checked="checked" /> java <input type="checkbox" name=".net" checked=".net" /> .net <input type="checkbox" name="C#" checked="C#" /> Chemistry <input type="submit" value="Select languages" /> </form> </body> </html> following is the "form.jsp" jsp program to handle the input given by the web browser. <html> <head>

<title>Reading Checkbox Data</title> </head> <body> <center> <h1>Reading Checkbox Data</h1> <ul> <li><p><b>java Flag:</b> <%= request.getParameter("java")%> </p></li> <li><p><b>.net Flag:</b> <%= request.getParameter(".net")%> </p></li> <li><p><b>C# Flag:</b> <%= request.getParameter("C#")%> </p></li> </ul> </body> </html> JSP CUSTOM TAG JSP is the technology which helps to separate the front end presentation from the middle and backend tiers. The custom tag library is a important feature of JSP that comes in that separate form. This technology is valuable to anyone who is building production-quality web applications. It is a user-defined JSP language element. Custom tag allows programmer to hide code in a Java class and access it from a tag in JSP.Some examples of tasks that can be performed by custom tags include operating on implicit objects, processing forms, accessing databases and other enterprise services such as email and directories, and implementing flow control. Custom tags increase productivity because they can be reused in more than one application. The following steps are to be taken to create a custom tag.

1. Create Tag Handler 2. Create Tag Library Descriptor (.TLD )


3Register TLD in JSP and use tags declared in TLD The first task is creating a simple tag. This is mainly to understand the overall process involved in creating a custom tag in JSP 2.0. TAG HANDLER Tag handler is a Java class that responds to events raised by container when custom tag is encountered. Every Tag handler must implement Tag interface or extend TagSupport class provided by JSP API. import import import import javax.servlet.jsp.*; javax.servlet.jsp.tagext.*; java.io.*; java.util.Date;

public class CurrentTime extends SimpleTagSupport {

public void doTag() throws JspException , IOException { JspWriter out = getJspContext().getOut(); out.println( new Date().toString()); } } // end of class

TAG LIBRARY DESCRIPTOR TLD file is an XML file containing details of tags. TLD file can be placed any where within WEB-INF indirectory. The TLD file provides details regarding the library such as its version and the version of JSP it needs and tags. <?xml version="1.0" encoding="ISO-8859-1" ?> <!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN" "http://java.sun.com/j2ee/dtd/web-jsptaglibrary_1_2.dtd"> <taglib> <tlib-version>1.0</tlib-version> <jsp-version>2.0</jsp-version> <short-name>st</short-name> <tag> <name>time</name> <tag-class>st.CurrentTime</tag-class> <body-content>empty</body-content> </tag> <tag> <name>formattime</name> <tag-class>st.FormatCurrentTime</tag-class> <body-content>empty</body-content> </tag> </taglib> REGISTERING TAG Before a custom tag is used, its tag library descriptor (TLD) is to be registered in JSP using taglib directive. taglib directive specifies the name of TLD file and prefix to be used while using the tags in the library. The following JSP registers st.tld and uses time tag with prefix st.

<%@ taglib uri="/WEB-INF/tlds/st.tld" prefix="st"%> <st:time/> Full code of JSP page is as follows: CustomTag.jsp <%@ taglib uri="/WEB-INF/taglib.tld" prefix="custom" %> <html> <head> <title>Custom Tag </title> </head> <body bgcolor="fffff"> <H1>Welocome ! </H1> Custom tag work starts here... <custom:empty/> here Custom tag work ends... Body Content of JSP page write here </body> </html>

1. A brief introduction of JSP? 2. Java Server pages Introduction? 3. History of web pages 4. What is common gate way interface? 5. Microsoft ASP alternative of CGI 6. What is JSP? 7. what exactly is a JavaServer Page? 8. First JSP program. 9. JSP Architecture 10. How to set up the JSP environment? 11. What are JSP tags and how they used? 12. Example of JSP using Tags 13. What are implicit objects? 14. What are Scripting elements in JSP? 15. What are embedded control flow statements in JSP? 16. Write a program usinf loop statements in JSP? 17. What is the syntex of Comments in JSP? 18. What are the types of Directive tags in JSP? 19. Explain the page directive in brief what are its attributes? 20. What are optional attributes for page directives? 21. What is include directive Tag? 22. What is Tag Lib directive? 23. What is Action tag in JSP? 24. What is JSP Request object ? 25. What are the methods of Request Object ? 26. What is Session object in JSP? 27. What is JSP Response Object and what is its use? 28. How work with sessions in JSP? 29. What is JSP out object and what are its methods? 30. What is include Action tag explain with example? 31. What is forward Action tag? 32. What is javabean Action tag? 33. JSP Request -Response cycle 34. Example using JSP scriplets 35. Write program using useBean action for Scope attribute 36. What are JSP custom tags? 37. What are the advantages of custom tags? 38. Why XML needed in creation of custom tags? 39. What are the advantages of XML? 40. What are the components of the tag library? 41. What is the structure of tag handler in JSP? 42. What is the structure of TLD file ? define it

A brief introduction of JSP? Introduction:


The need for the server side scripting gradually began to give birth to the Java Server Pages(JSP).Microsoft introduced Active Server pages (ASP) to capture the market demand for server side scripting. Working on the similar line Sun Microsystems released Java Server Pages.(JSP) to ad server side programming functionality to the java. JSP has same advantages as of servlets .but JSP let you separate the presentation logic and business logic.JSP pages after compilation generates a servlet and therefore incorporates all servlet functionalities.

Descriptions:
JSP enables web applications to be broken down into separate components.A web designer can design and formulate the layout for the web page by using HTML .on the other hand a web developer working independently can use java code and other JSP specific tags to code for the business logic.The simultaneous construction of the static and dynamic contents facilitates development of quality application.

Java Server pages Introduction? Introduction:


JSP is a technology which provides powerful and efficient creation of dynamic contents. JSP uses the java programming language for creating dynamic pages.JSP follow the features of java Language. object oriented feature , plateform independent feature etc.

Descriptions:
JSP Technology has facilitates the segregation of the work profiles of a web designer and a web developer. JSP allows the use of standard HTML,and adds the flexibility of the java programming language.

SourceCode:

A simple JSP program <%-Document : index Created on : Mar 5, 2011, 12:36:04 AM

Author --%>

: R4R

<%@page contentType="text/html" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JSP Page</title> </head> <body> <h1>Hello World!</h1> <p> This is my first web page </p> </body> </html>

Output of SourceCode:

Hello World!

This is my

first web page

History of web pages Introduction:


To understand the influence off JSP it is must to take a look at the past approaches to creating web pages.Traditional web pages are static pages .they

are unchangeable they will always remain the same.request from the multiple client for the same static page should all receives the same result. As the need of dynamic contents on web were site increasing the requirement of dynamic web pages was also increased.Today's website requires more than static contains and feed back forms.Dynamic data is important on the web pages from online banking to the online shopping.

Descriptions:
Dynamic web pages are those webpages which are created at the time they are requested.changing content depend on specified criteria.Dynamic pages are those page which are generated by an application on the server receiving input from the client and responding appropriately.There are various methods of generating dynamic pages JSP is one of them.

What is common gate way interface? Introduction:


Common GateWay Interface (CGI) is the solution of developing webpages. CGI allows request to be send to an external program..these external programs were return in any of the languages C,C++,perl. But CGI programs use large amount of system resources .not only CPU but also memory of the System.for every request of the client server load ,runs and unload .it takes long time.

Descriptions:
CGI is a part of web server that communicate with the programs those are running on the server.

What is JSP? Introduction:


Java Server Pages(JSP) is a technology provided by the Sun Microsystems . it was developed in competition of ASP. ASP is the product of the Microsoft .both languages are developed to provide server side Scripting. As JSP is Sun MicroSystems product it is freely available on the internet. but ASP is not. On the other hand as JSP used java APis it is more secure . it inherit all the features of the java. Like security ,plateform independent.,scalability,Extensibility etc. JSp makes the work of web developers and web designers to design and maintain the web pages easily. JSP make it possible to develop web based applications that are plateform independent. as it is followed Java APIs

what exactly is a JavaServer Page? Introduction:

JSP is a simple HTML page which consists additional code that execute application logic to generate dynamic content.these logics are EJB, JDBC, RMI objects. A JSP page consists simple HTML code for static text and graphics and also consist the JDBC object to call the database. When the page is displayed on the user,s browser it will contain both the text and the data that is processed.

Descriptions:
Java server pages are extension of java servlets API .JSP pages are compiled into servlets before they are used. JSP is contains presentation code with logics.

First JSP program. Introduction:


The first java server pages program to display hello. Simply inside the HTML code using H1 heading we write Hello World!

Descriptions:

SourceCode:

<%-Document : index Created on : Mar 5, 2011, 12:36:04 AM Author : R4R --%> <%@page contentType="text/html" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JSP Page</title> </head> <body> <h1>Hello World!</h1> <p> This is my first web page </p>

</body> </html>

Output of SourceCode:

Hello World!

This is my

first web page

JSP Architecture Introduction:


JSP architecture consists two main components WebBrowser and WebServer. the communication is established between these two. The extension of the JSP file is .jsp.The JSP engine parses the .jsp and creates a java servlet source file.Then servlet compiles the source file to the class file.

Descriptions:
Architecture of JSP is defined below step wise... 1.A web browser /client send a request to the 2.JSP send request to the server. 3.When the request reach the server then it is send to the JSP servlet engine. 4.Now the parser present on server side pars the JSP file. webserver/server.

5.Now the servlet code is generated on the server. 6.The compiler compile the servlet source code into class. 7.After that servlet is instantiated on the server. 8.When the servlet is instantiated the server Response to the client and send the output in the form of HTML file.HTML from the servlet output send via the internet.

How to set up the JSP environment? Introduction:


To run a JSP program it is must that JSP is installed on your system.And for that JDK is must be there in the system. Steps to installed JSP 1. Make sure JDK is installed on the system if yes then proceed if not first installed the JDK. 2.Down load the JSP environment from http://java.sun.com/products/jsp/index.jsp 3.Installed tom cat server. 4To start the server change to the tomcat\bin directory and type: Setup 5.Now open the web browser and in address box type http://localhost:8080/--This will display the example page . 6.Place any new JSP files in the "webapps" directory under your installed Tomcat directory. 7.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 shows the executed JSP file

What are JSP tags and how they used? Introduction:


There are five types of tags used in JSP. Declaration tag ,Expression tag ,Directive tag,Scriplet tag ,Action tag. 1.Declaration Tag All the functions , methods, variables used in java server pages are defined inside the Declaration tag. Declaration tag has following notation <%! %> Method ,variables ,functions are declare inside the <%! %> notation. 2.Expression tag Expression tag is used to display the output data on any generated page. The data placed in this tag is print on the output stream and the data is automatically convert to the string. Notation of Express tag %= %> 3.Directive tags

Directive tags gives information about the page to the JSP engine.Using directive tags user can import packages. Notation for directive tag <%@ % > There are three type of directive tags :-page ,include ,tag library 4.Scriplet tag This tag is used to add java code to the JSP. Notation &lt;% %gt; 5.Action tag These tags are used to transfer the control between pages.It is also enable the use of server side java beans. <jsp:action attributes />

SourceCode:
Examples Declaration tag Example <%! // Start declaration tag private int example = 0 ;//define variales private int test = 5 ; %> // end the decllaration tag Expression tag Example <%! Currentdate: <%= new java.util.Date() %> %>

Example of JSP using Tags Introduction:


This example shows the use of JSP tags directive tags , Expression tags , Declarative tags action tags etc. Declaration ,directive ,Expression ,Action ,Scriplet are the tags used in this example.

Descriptions:

SourceCode:

<%-Document : index Created on : Mar 8, 2011, 11:17:49 PM Author : R4R --%> <%@page contentType="text/html" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JSP Page</title> </head> <body> <%@ page language="java"%> <% out.println("Hello world");%> <h1>Hello world!</h1>

</body> </html>

Output of SourceCode:

Hello world

Hello world!

What are implicit objects? Introduction:

Implicit objects are the objects provided by the JSP to the developer.JSP container provide these objects to the developers. These objects are called implicit objects because they are automatically instantiated. There are mainly nine implicit objects:--page context ,session,request ,response, exception ,out , application ,config and page.

Descriptions:
Page context :-The page context is written as Javax.servlet.jsp.pagecontext .It is used to access the page attributes and all the name spaces associated with JSP page. Session:-Object session is of type Javax.servlet.http.httpsession.This object session provide the connection or the association between the client and the server.The main function of session object is maintaining states when there are multiple request are executed. Request:-The object request is type Javax.servlet.http.httpservletrequest.. in it data include with the httpRequest.The request made by the client is pass to the server. In it request object is to take value from the client and pass it to the server. Response:Response:-The Object through which the result comes from the server is called response object .The object response is of type Javax.servlet.http.>httpservletresponse. Object response is generally used with cookies. Out:- The out object is denotes the output stream in the context page . this is written as Javax.servlet.jsp.JspWriter Application:-This implicit object is used to share the data with other application pages.This object is written as Javax.servlet.http.ServletContext . Page:-page object is used to denote JSP page and to call any instance of the servlet's page. This is written as Java.lang.Object. Config:-This object is used to get the information about the servlet configuration.The object Config is written Javax.servlet.http.ServletConfig

What are Scripting elements in JSP? Introduction:


Scripting elements enables the coder to insert java code in to the servlets that will be generated from the current JSP page. There are three types of Scripting elements.Expression ,Scriplet ,and Declarative. Expression:-This element contains the java expressions that returns the value.Expression tag contain any Expression but it should be valid according to java language. Syntax <%= Java expression %> Example Your hostname : <%=request.getRemoteHost()%>

Descriptions:

Scriplet:-Sciplet can contain number of language statements ,methods ,variables,expressions and declarations.that are valid in scripting language.Scriplets are executed at the request time when the JSP container process the request. Any text, HTML tags, or JSP elements must be write outside the scriptlet Example:-<% // This scriptlet declares and initializes "date" java.util.Date date = new java.util.Date(); %> Declaration:-methods or variables are initialized inside the declaration tag. Syntax < %! Declaration %> Example:<%! Date getDate() { System.out.println( "In getDate() method" ); return new Date(); } %>

What are embedded control flow statements in JSP? Introduction:


JSP use all important features of java and use all its powerful APIs and building blocks. The embedded statements of the JSP are divided into two categories Decision making statements and control flow statements. Decision making statements are: if ..else and switch case are two decision making statements. control flow statements are: For loop ,while and do-while loop.

Descriptions:
The function of the the statements are same as in java programming.

What is the syntex of Comments in JSP? Introduction:


JSP engine converts JSP comments into java comments in the source code of servlet that implement the JSP page. JSP increase the readability of the JSP page.JSP has two type comments . 1.Hidden comments 2.Output comments.

What are the types of Directive tags in JSP?

Introduction:
JSP directive tags gives special information about the page.User can import the package ,define error handling errors using JSP. there are three directive tags. Page Include Tag Lib

Descriptions:
Syntax for page directive tag <@ page attribute.....> Page directive tag used to established values to the attributes used in page.More than Page directive tag would be used in JSP page. General syntax for page directive is <@ attributes.....> Page directive has number of attributes. Import Extends Buffer Session info IsThreadSafe Errorpage etc.

JSP

Descriptions:
Sample Page directives <@page import="java.util.Date"%> <@page info="info about he page" %> Explanation of some page attributes. Language attribute defines the language used in Scriplets ,expressions and declarations in JSP file and any inclide file. language="java" import attribute is used to specifies the list of packages JSp file has used. import ={package.class\package. *}

What are optional attributes for page directives? Introduction:


Various optional attributes are available for JSP page directive.

Descriptions:
These JSP attributes gives social information to the JSP engine and help in changing the way in JSP engine process.

Some optional attributes available for page directive language import extends session buffer isThreadSafe info autoFlush errorPage contentType IsErrorPage

are:

What is include directive Tag? Introduction:


If a programmer wants include the contents of one file to the other than include tag is used. The include tag is used to include the content of other file to the current tag file. The syntax of include directive tag is &lt;%@ include file = "xxx.html/xx.tagf"%&gt;

Descriptions:
For example to add the dynamic file we write the include directive tag as &lt;%@ include file="r4r.tagf" %&gt; Two types of file are included in this tag Static file or html file with .html extension and other is dynamic file with .tagf extension.

What is Tag Lib directive? Introduction:


Tag Lib is the collection of custom tag .To customize action from tag file programmer can use tag lib. Tag lib is used in JSP code to improve the reuse ability of the JSP code in JSP application. .

Descriptions:
Declaration of tag lib Syntax &lt;%@ taglib uri = "tag library URI" prefix = "tag Prefix" %&gt; In above syntax taglib uri are both keywords.uri identifies the tag lib descriptor and is enclosed in " " .prefix included inside " " is a string that will become the prefix to distinguish a custom action.

What is Action tag in JSP?

Introduction:
Action tag transfer the control between the pages .It transfer the control from one page to the other particular page. JSp action tag enable the programmer to use use server side Java beans. instead of using Java code, the programmer uses special JSP action tags to either link to a Java Bean set its properties, or get its properties. Syntax of JSP Action tag

<jsp:action attributes />

Descriptions:
There are various Action tags but most usable tags are only three: Include Action tag :-Include Action tag is used to include either static or dynamic contents. Syntax <jsp:include page="{relativeURL | <%= expression %>}" flush="true" /> If the included file is a static file than the contents are included as such n the JSP file and if file is dynamic than the request is pass to the dynamic file as the included action completed result sent back. for dynamic page the Syntax of include action tag is <jsp:include page="{relativeURL | <%= expression %>}" flush="true" /> <jsp:include name="parameter name" value="parameter |<%expression" /> Forward Action Tag :-This tag forward the control to the static or dynamic resource. Syntax <jsp:forward page="{relativeURL | <%= expression %>}" /> &nbsp; Usebean Action tag :-This tag allows JSP to create an instance or to receive an instance of java bean.It is also used to create and initiate the bean with specific name and scope. Syntax of Usebean Action Tag <jsp:useBean id="beanInstanceName" scope="page|request|session|application" { class="package.class" | type="package.class" | class="package.class" type="package.class" | beanName="{package.class | <%= expression %>}" type="package.class" } { /> | > other elements </jsp:useBean>

What is JSP Request object ?

Introduction:
Request object in JSP is used to get values for the request that the client made to the web server.. Request object takes the value of request from the client and pass it to the server.

Descriptions:
The object request is written as : Javax.servlet.http.httpservletrequest. Methods of request object getCookies() getHeaderNames() getHeader(String name) getAttribute(String name) getAttributeNames() getParameter(String name) getParameterNames() getMethod() getParameterValues(String name getRequestURI() getQueryString()

What are the methods of Request Object ? Introduction:


There are various method for request object few of them are discussed below. The few methods of Request object is discussed below getCookies() getHeader(String name) getParameterNames() getAttribute(String name) getAttributeNames() getMethod() getHeaderNames() getParameter(String name) getParameterValues(String name) getQueryString() getRequestURI()

Descriptions:
getCookies():-This method return all Cookies sent by client for as a request.These are return as an array of Cookie object. getHeader(String name):- This method of request object is used to return the value of the requested header. General syntax of getHeader() of request object is request.getHeader("String") getParameterNames():-It return the name of parameters given in the current

request. Syntax request.getParameterNames() getMethod():-This method of request object used to returns the methods GET ,POST to the request HTTP method used.

What is Session object in JSP? Introduction:


The session object in JSP provides connection or association between the client and the server . Main function of session object is to maintain the state when number of web pages are requested. The main function of session object is to navigate between multiple pages of an application where variables are stored for whole session.

Descriptions:
The session object is written as follows Javax.servlet.http.httpsession. The session object denotes the associated with a specific session of a user.

What is JSP Response Object and what is its use? Introduction:


The result of the request is get back to the client with this object.It handles the output of the client. The response object is written: Javax.servlet.http.httpservletresponse

Descriptions:
Response object denotes the HTTP response data.It is generally used by cookies. Number of methods are available for response objects few of them are : setContentType() containsHeader(String name) addHeader(String name, String value)

How work with sessions in JSP? Introduction:


Session object is the medium of interaction between the user and the server.Session established a connection between the client and the server and is a medium of exchange of information.

The data can be put and retrieve from the server just like a hashtable. It store information in key value pair just like hashtable.

Descriptions:
Session object increase the security of the application by differentiating the users from each other.Every user have different or unique session ,and server will exchange information till the session get expired. Mostly the session works with user base applications . when user login for the web page if the login is successful then the session will exists for long time till it forcefully destroy by the user. or if login is not successful the the session will expire immediately.

SourceCode:

<%@page import="java.util.Date"%> --%> <%@page import="java.util.Enumeration"%> <%@page import="antlr.collections.Enumerator"%> <%@page contentType="text/html" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>R4R Tech Soft</title> </head> <body> <h1 style="color: brown;background: antiquewhite;bottom: auto ">Hello R4R Tech Soft!</h1> <form action="#" method="post"> <b>Please Fill the Text Block give in form::</b> <BR><BR> Enter your name:<BR> <input type="text" name="name" value="" size="30" maxlength="10" /> <BR><BR> Enter your date: <BR> <input type="text" name="data" value="" size="30" maxlength="25" /> <BR><BR> Enter your password: <BR> <input type="password" name="password" value="" size="30" maxlength="10"/> <P> </p> <input type="submit" value=" Submit my Detail " name="submit" /> </form> <BR><BR> <B> Display Date and Time <%= new java.util.Date() %> <BR><BR> <%! private String element; %> <% here:: </b>

if (request.getParameter("submit") != null) { //Construct the session table and store the value in it out.println("<body bgColor=\"#FDF5E6\">\n"); out.println("<h2><B>Information About your session:</h2>"); out.println("<table border=1><tr bgcolor=\"#FFAD00\">"); out.println("<th>INFO TYPE </th><th>VALUE</th></tr>"); out.println("<tr><td>SESSION ID:</td><td>" + session.getId() + "</td></tr>"); //HttpSession create here:: HttpSession session1 = request.getSession(true); Enumeration enumeration = request.getParameterNames(); session1.setAttribute("second", enumeration); Enumeration enumeration1 = (Enumeration) session1.getAttribute("second"); while (enumeration1.hasMoreElements()) { element = (String)enumeration1.nextElement(); out.println("<tr><td>"+element+"<td><td>" + request.getParameter(element) + "</td></tr>");; } out.println("</table>"); } else { out.println("Don't leave any block empty! "); } %> </body> </html>

What is JSP out object and what are its methods? Introduction:
JSP out object is mean to denote the output stream in the context page of the web application. JSp out object is derived from the class or interface jsp.JspWriter and the object itself is written as: javax.servlet.jsp.JspWriter. The object that write to the JSP's output stream is defined by the out object.Out object represent direct reference to the output stream.or to filter stream and may be to nested JSP writer stream of another JSP.

What is include Action tag explain with example? Introduction:

Include action tag is used to put the output of static as well dynamic pages to the current working page. Include action tag include the static file as it is. and it send the request to the dynamic JSP file .as the include action completed the result is get back.two keywords are used in this tag page and flush. page will contain the reference to the url of the page which will be include .and flush keyword flushed out the existing buffer.

Descriptions:
Syntax of include action tag for static file <jsp:include page="{relativeURL | <%= expression %>}" flush="true" /> Syntax of include action tag for dynamic file <jsp:include page="{relativeURL | <%= expression %>}" flush="true" /> <jsp:param name="parameterName" value="{parameterValue | <%= expression %>}" /> </jsp:include> Relative URL is the path of the file to be included.which is written inside" " The value of flush is always "true"

SourceCode:

Code of the current file index.jsp to be executed <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>JSP page</title> </head> <body> <h1>Hello world!</h1> <p>This is JSP page </p> <p>Here I am include http://localhost:8080/r4r/file.jsp</p> <jsp:include page="file.jsp" /> </body> </html>

Source Code of the file file.jsp to be included

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://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> <p>The current date is :</p> <%= new java.util.Date() %> </body> </html>

Output of SourceCode:

Hello world!
This is JSP page

Here I am include http://localhost:8080/r4r/file.jsp

The current date is : Sat Mar 12 16:51:51 PST 2011

What is forward Action tag? Introduction:

Forward Action tag terminate the action of current page and forward the request to the another page such static page to another jsp application or servlet . Forward action tag receives the request forward it to the new URL. get the response back and than pass it to the client.

Descriptions:
Syntax of forward action tag <jsp:forward page="{relativeURL | <%= expression %>}" /> &nbsp;

SourceCode:

Source code of file use forward action tag. <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>JSP page</title> </head> <body> <h1>Hello world!</h1> <p>This is JSP page </p> <p>Here I am include http://localhost:8080/r4r/file.jsp</p> <jsp:forward page="file.jsp"></jsp:forward> </body> </html> Source code of file which is to be forward in above code. <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <%@page import="java.util.Calendar"%><html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Insert title here</title>

</head> <body> <p>The current date is :</p> <%= new Calendar() %> </body> </html>

Output of SourceCode:

The current date is : Sat Mar 12 17:21:55 PST 2011

What is javabean Action tag? Introduction:


Java bean action tag is used to find and load an existing bean.it is used to reuse the beans. <jsp:useBean> is the java bean action tag. it has four attributes id class Scope beanName

Descriptions:
Id= id attribute uniquely identifies the instance of the bean. Class= class attribute specifies the life of the bean in terms of a page ,session or an application Scope = Scope attribute specifies the life of the bean in terms of a page ,session or an application beanName = beanName attribute specifies a referential name for the bean. we use following example of to show the usebean Action tag of JSP. The useBean action to specify the use of a bean component. here setProperty action is used to specify the use of a bean and HttpServletRequest object is used to accept the values . In below source code

class=java class path is used which apply validations

SourceCode:
Following code uses the JSPdirectives and the useBean actions <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://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="mybean" scope="session"class="java class path"></jsp:useBean> <jsp:setProperty property="mybean" name="age" value="22"/> <jsp:setProperty property="mybean" name="name" value="Nancy"/> <P> <jsp:getProperty property="name" name="mybean"/> <jsp:getProperty property="age" name="mybean"/> <%out.println(mybean.getage()+ " " + mybean.getName()) %> </P> </body> </html>

JSP Request -Response cycle Introduction:


The JSP request-response cycle essentially comprises of two phases the translation phase and the request processing phase. Translation phase This phase is implemented by the JP engine present inside the web engine.and involves the generation of the servlet. Request processing phase In this phase response is generated according to the specification of the request.The servlet then send back the response corresponding to the request processed.

Descriptions:
Working of the Request -Response cycle. Browser send the request to the web server . Webserver pass the request to the JSP engine present inside the web container

which also present inside the webserver. JSP engine than check the request to ensure if the call tothe JSP is first of its kind. IF Yes , than servlet generation and recompilation occurs .and the response get back to the web server to the client browser. NO, than The new servlet loaded and response to the web server and than to the client browser.

Example using JSP scriplets Introduction:


A JSP scriplet is consists the valid code that are enclosed inside the <% and %> JSP tag. called Scriplet tag Scriplet tags specify the java java code inside the JSP file.

Descriptions:
This code create a request session object and retrieve variable values using getParameter() method. This code snippet accept a name from the user and forwards the input parameters to the JSP page.

SourceCode:

The code to accept the input from the user and forward the input parameter to the JSP page save it as form.jsp <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <%@page import="java.util.Date"%><html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Simple JSP Example</title> </head> <body> <h1>Scriplet tag Example </h1>

<form method ="post" action="Test.jsp"> Your name <input type ="text" name="t1" size="30"> <input type="submit" value="submit"> </form> </body> </html> The code for the JSP scriplet to accept parameters and display the name save it as Test.jsp <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>JSP page</title> </head> <body> <% String name=(request.getParameter("t1")); out.println("<h3>A scriplet Example</h3>"); out.println("Hello" + %> </body> </html> " " + name );

Output of SourceCode:

A scriplet Example
Hello jsp

Write program using useBean action for Scope attribute

Introduction:
The scope attribute is used to specify the life of the object and takes the values in four different forms. Scope of an object takes values in four different ways page session application and request

Descriptions:
page = it is used to check the availability of the object corresponding to the response of the particular page to the current user request.the object is created on the initiation of the user's request and destroy on the completion. session = it is used to check the availability of the object corresponding to the existence of a particular session. application = is used to check the availability of the object through out the application request = is used to check the availability of an object corresponding to the existence of the HttpServletRequest object. First prepare a registration page in jsp name as front.jsp then make java class for validation in the same folder of diferent package.save it as .java file it will call in the bean An error page is make in jsp also .

SourceCode:

Source code for front page. save it as frontpage.jsp <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <%@page import="java.util.Date"%><html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Simple JSP Example</title> </head> <body bgcolor="#fffffr"> <h1 style="color: blue;background: grayantiquewhite;bottom: auto"> Welcome to R4R Tech Soft!Registration Form</h1>

<form action="#" method="post"> <BR><b>Your name: </b> <input type="text" name="name" value="" size="30" maxlength="10" /> <BR><b>Your date of birth: </b> <input type="text" name="data" value="" size="30" maxlength="25" /> <BR> <b>Your password: </b> <input type="password" name="password" value="" size="30" maxlength="10"/> <BR> <b>Your Mobile No.:</b> <input type="text" name="mobile" value="" size="30" maxlength="15"/> <P> </p> <input type="submit" value=" Submit " name="submit" /> </form> <%! private String name, data, password, mobile; %> <% //Get the property from the form name = request.getParameter("name"); data = request.getParameter("data"); password = request.getParameter("password"); mobile = request.getParameter("mobile"); %> <%-Activate the JSP:Beans --%> <jsp:useBean id="dataBeans" class="bean.databean" scope="session" ></jsp:useBean> <!-- Set the property into the beans --> <jsp:setProperty name="dataBeans" property="name" value="<%=name%>"></jsp:setProperty> <jsp:setProperty name="dataBeans" property="data" value="<%=data%>"></jsp:setProperty> <jsp:setProperty name="dataBeans" property="password" value="<%= password%>"></jsp:setProperty> <jsp:setProperty name="dataBeans" property="mobile" value="<%= mobile%>"></jsp:setProperty> <% if (request.getParameter("submit") != null) { //Calling the Beandisplay.jsp page response.sendRedirect("Beandisplay.jsp"); } else { out.println("<BR> <B>Fill all the fields"); } %> </body>

</html> Source code for displaying session bean save it as Beandisplay.jsp <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <%@page import="bean.databean"%><html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Insert title here</title> </head> <body bgcolor="#fffff"> <h1 style="color: blue; background: silver; bottom: auto ">R4R Tech soft!Display Page</h1> <h2 style="color: brown; background-color: blanchedalmond">The property of BEANS::</h2> <!-- Taking the property of from the beans --> <jsp:useBean id="dataBeans" class="bean.databean" scope="session" ></jsp:useBean> <% //Create a instance of beans in which all the data store from Beans bean.databean beans = (databean) session.getAttribute("dataBeans"); //Get and Display the property from the beans out.println("<body bgColor=\"#FFFFFF\">\n"); out.println("<h2><B>Information About your session:</h2>"); out.println("<table border=1><tr bgcolor=\"#FFAD00\">"); out.println("<th>Information </th><th>VALUE</th></tr>"); out.println("<tr><td><B>Client Session ID:</td><td>" + session.getId() + "</td></tr>"); out.println("<tr><td><B>Name of client:</td><td>" + beans.getName() + "</td></tr>"); out.println("<tr><td><B>Date of birth of client:</td><td>" + beans.getData() + "</td></tr>"); out.println("<tr><td><B>Password of client:</td><td>" + beans.getPassword() + "</td></tr>"); out.println("<tr><td><B>Mobile Number of Client:</td><td>" + beans.getMobile() + "</td></tr>"); out.println("</table></body> "); %> </body> </html> Source code for error page save it as errorpage.jsp <%@ page language="java" contentType="text/html; charset=ISO-8859-1"

pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <%@page isErrorPage="true" %> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Insert title here</title> </head> <body> <h1 style="color: aliceblue; background: appworkspace; bottom: auto "> R4R Tech soft!Error page</h1> <h2 style="color: brown; background-color: blanchedalmond">Following Error generated in Pages</h2> <% //Error catch here try { exception.getLocalizedMessage(); exception.fillInStackTrace(); } catch (UnknownError ue) { out.println(ue.getMessage()); } %> </body> </html> Source code for java file save it as databean.java /* * Save as a databean.java * Program for handle the JSP:Beans */ package bean; public class databean { private private private private String String String String name; data; password; mobile;

public void setName(String name){ this.name=name; } public String getName(){ return name; } public void setData(String data){ this.data=data; } public String getData(){

return data; } public void setPassword(String password){ this.password=password; } public String getPassword(){ return password; } public void setMobile(String mobile){ this.mobile=mobile; } public String getMobile(){ return mobile; } }

Output of SourceCode:

Welcome to R4R Tech Soft!Registration Form

Your name: Your date of birth: Your password: Your Mobile No.: Fill all the fields

R4R Tech soft!Display

Page
The property of BEANS:: Information About your session:
Information Client Session ID: Name of client: Date of birth of client: Password of client: VALUE 2CEE77EFDB3D152EACE95EB787E68756 meenakshi 1235 1234565

Mobile Number of Client: 569843

What are JSP custom tags? Introduction:


Custom tags are user defined tags which explicitly render the information about the type of data.The structure of custom tags in JSP is similar to XML tags. Custom tags have a library which consist the custom tags ,those can be reuse to decrease the cycle time of development of the application and improve the the productivity.

Descriptions:
JSP 1.0 does not support the tag libraries.however JSp1.1 support incorporation of user created tags in JSP files.

What are the advantages of custom tags? Introduction:

Custom tags provide better packaging functionality. by which custom tags productively differentiate the work profiles of web designers and developers. following are the advantages of using custom tags. 1.Reduction of scriplets in the code:-The attributes of a custom tag can be used to accept parameters .therefore inclusion of declarations ( to define variables) and scroplets(to set properties of java components) can be avoided or reduced. 2.Reusability:-Scriplets are non-reusable java codes snippets.while custom tags are reused. This enables the saving of time in development and deployment of codes.

Why XML needed in creation of custom tags? Introduction:


Extensible Markup Language(XML) is used in web applications to create custom or user-defined tags. XML tag is just like similar to the HTML tag as it allows interaction between the user and the browser.

Descriptions:
The use of custom tags defined with the help of XML makes it easier to differentiate the data. The detailed rules and specification followed in the XML code are written in the Document Type Definition(DTD). The DTD defines the tag,tag structure ,attributes and values that are used in a particular document.

What are the advantages of XML? Introduction:


Although the presentation of data is similar to that written in HTML .but the code for XML is more data-centric. Following are the advantages of using XML 1.Easy coding:-As it is similar to HTML so it is easy to code except for the inclusion of custom tags. 2.Easy data interchange:-translating an XML document is easy due to use of explicit custom tags .Therefore data can be exchanged at different levels without the need to decode or interpret its structure. 3.Easy business communication:-Data can be exchanged between organizations without the need to understand the interfaces of the counterpart's business,system organization or structuring.

What are the components of the tag library?

Introduction:
The tag library containing the files to create the custom tags.The components of tag library are Tag handler and Tag library descriptor (TLD) file. Tag handler uses different methods and objects to define the behavior of the tag. The TLD file is a XML file that contains a descriptive list of the custom tags. The developer is responsible for coding the tag handler and the TLD file.

Descriptions:
To use tags in JSP file first create a tag handler containing the tag and body tag interfaces.the tag handler file should define the task to be performed by the tags.and than map the tags and the tag handler file by using the TLD file.the TLD file should define inputs to the tag handler.

You might also like