You are on page 1of 94

JSP Java Server Pages



JSP technology has facilitated the segregation of the work of a Web designer and a Web developer. 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 the business logic. The simultaneous construction of the static and dynamic content facilitates development of quality applications with increased productivity.   



A JSP page , after compilation , generates a servlet and therefore incorporates all servlet functionalities. 

Servlets and JSP thus share common features, such as platform independence , creation of database-driven Web applications , and server side programming capabilities. 

However , there are also some basic differences between servlets and JSP :

JSP on the other hand allows Java to be embedded directly into an HTML page by using tags. The HTML content and the Java content can also be placed in separate files. a change made to any file requires recompilation of the servlet. Due to this . Any changes made to HTML content is automatically compiled and loaded onto the servlet     . Servlets tie up files (an HTML file for the static content and a Java file for the dynamic contents) to independently handle the static presentation logic and the dynamic business logic.

 On the other hand. any change made to the code requires identification of the static code content (for the designer) and dynamic code content (for the developer) to facilitate incorporation of the changes.  Therefore. by virtue of the separate placement of the static and dynamic content . Servlet programming involves extensive coding. facilitates both Web developers and the Web designer to work independently. a JSP page. .

. that compiles a JSP page to a servlet.  A JSP engine is a part of a Web container .  The following figure represents the process of the flow of events that occur after a client requests for a JSP page.the server in turns sends a request to the JSP engine.JSP Life Cycle  When the client browser requests for a particular JSP page .

Request-Response Cycle for a JSP Page Response Servlet reloaded No Request Browser Response Web Container ( JSP Engine) Check to ensure if the call to JSP is first of its kind Yes Servlet generation and recompilation Response .

that implements the servlet interface.     . The request-response cycle essentially comprises of two phases . Internally . and saves time that would otherwise be lost in reloading a servlet at each time. this results in the creation of a class file for the JSP page . During the request-processing phase. processes all the subsequent requests . it remains active . namely the translation phase and the request-processing phase. the response is generated according to the request specifications. After the servlet is loaded for the first time. The translation phase is implemented by the JSP engine and involves generation of a servlet.

2. 3. that are defined in the javax. the container invokes the following life cycle methods on the servlet . jspService() : This method is invoked when request for the JSP page is received.Once a JSP is translated to a servlet . jspInit() : This method is invoked at the time when the servlet is initialized. jspDestroy() : This method is invoked before the servlet is removed from the service.JspPage interface: 1.servlet.jsp. .

 Create Calculate.Assignment  Accept two numbers form the user form the AcceptInput.jsp to process the request and displays the results .jsp page .

Assignment DatePage.Date () %> </body> </html> .util.jsp <html> <body> <%= new java.

IncludePage.jsp is shown above </h3>´).jsp <html> <body> <h4> Today¶s Date is : <jsp:include page=³DatePage.println(³<h4> The ouput of the file DatePage. %> </body> </html> .jsp´ flush=³true´ /> </h4> <% out.

These classes and interfaces are contained in the javax. Some of the classes defined in the javax.jsp package . ErrorData 2. JspWriter 3.servlet.servlet. PageContext   .Classes of JSP API  JSP API is a set of classes and interfaces that you can use to create a JSP pages.jsp package are : 1.

 The ErrorData class extends the java.  You need to set the value of the page directive .Object class .The ErrorData Class  The ErrorData class defines error information for error pages.lang.  Some of the methods defined in the ErrorData class that you can use in a jsp page are : . isErrorPage to be true to indicate that a page is an error page.

4.1. getServletName () : -> Returns the name of the servlet invoked in the form of a String. . getRequestURL () : -> Returns the requested URL in the form of a String. 2. getThrowable () : -> Returns the Throwable exception that caused the error. 3. getStatusCode () : -> Returns the status code of the error in the form of an interger.

  The JspWriter class extends the java.The JspWriter Class  The JspWriter class is used to write action and template data in a JSP page. The object of JspWriter class is referenced by the implicit variable .Writer class. out .  Some of the methos defined in the JspWriter class that you can use in a JSP page are : .io.

io.It throws java. if the buffer is already cleared.1. flush() : ->Flushes the buffer stream. close() : -> Closes and flushes the stream 3.IOException exception if you make a call to the write () or flush() after closing the stream . The flush() method flushes all the buffers in a chain of Writers and OutputStream. clear() : -> Clears the contents of the buffer. 2. The clear() method throws an IOException exception .

long integer . 6. string . The print() throws the java. an array of character . getBufferSize () : -> Returns the size of the buffer used by the JspWriter 5.character . println() : -> Prints a value of type boolean . The Println () throws the java. double ±precision floating ±point number.character . floating point .io. and object. print() : -> Prints a value of type boolean .IOException exception if any error occurs while printing . floating point . double ±precision floating ±point number. interger . interger . an array of character . string .IOException exception if any error occurs while printing.io.4. and object.This method writes a line separator string to terminate the current line.long integer .

Some of the methods defined in the PageContext class are :    .The PageContext Class  The PageContext class provides context information when the JSP technology is used in the servlet environment. A PageContext instances provides access to namespaces associated with a JSP page. The PageContext class extends the JspContext class.

3.1. This method accepts the URL of a target page as an argument. The return type of the getResponse () method is the servlet response. The return type of the getRequest () is the servlet request. forward () : -> Redirects the current servlet request and servlet response to another page. 2. . 4. getRequest () : -> Returns the current value of the request object. getPage () : ->Returns the current value of the page object. getResponse(): -> Returns the current value of the response object.

getSession () : ->Returns the HttpSession for the current PageContext. include () : ->Processes the current servlet request and the response specified in the URL. 7. 8. getServletContext () : -> Returns the ServletContext of the current page. The return type of getSession () is HttpSession. getServletConfig (): -> Returns the ServletConfig of the current page. a URL path and the flush value of boolean type . The include () method asscepts two arguments.5. 6.

out.println(³Be in Peace´).<html> <head> <title>My first JSP Page</title> </head> <body> <%@page language=³java´%> <% System. %> </body> <html> .

3.Using JSP tags There are five main tags: 1. 2. 5. Declaration tag Expression tag Directive tag Scriptlet tag Action tag . 4.

 Declarations do not generate output.).Declaration tag (<%!  %>) This tag allows the developer to declare variables or methods.  Before the declaration you must have <%! And at the end of the declaration the developer must have %>  Code placed in this must end in a semicolon(. . so are used with JSP expressions or scriptlets.

%> .Example Of Declaration tag <%! private int counter = 0 . private String getAccount (int accountNo).

) does not appear at the end of the code inside the tag.println(). .Expression tag (<%=  %>) This tag allows the developer to embed any java expression and is short for out.  A semicolon (.

Date() %> .Example Of Expression tag Current Date and Time is : <%= new java.util.

3.files to be included Tag library . %>)  A JSP directive gives special information about the jsp page . 2.Directive tag (<%@ directive«.processing information for this page .  There are three main types of directives: 1.tag library to be used in this page . to the JSP Engine. page Include .

)  Directives do not produce any visible output when the page is requested but change the way the JSP engine processes the page.Directive tag (Continue«.  For example . .. you can make session data unavailable to a page by setting a page directive (session) to false.

. Page directive  This directive has 11 optional attributes that provides the JSP Engine with special processing information.1.  The following table lists the 11 different attributes with a brief description.

* javax.servlet.Language : Which language the file uses.lang.* <%@ page import=³java. <%@ page language=³java´ %> Import : Import all the classes in a java package into the current JSP page.servlet.util. java.jsp.*´ %> .* javax. The following packages are implicitly imported.This alllows the JSP page to use other java classes.* javax.servlet.http.

buffer : Controls the use of the buffered output for the JSP page. Default is 8 kb <%@page buffer =³none´ %> autoFlush : Flush output buffer when full <%@ page autoFlush=³true´ %> . Default is set to true. By default all JSP pages have session data available.session : Does the page make use of sessions.

copyright 2001.com test page.´ %> .isThreadSafe : Can the generated Servlet deal with multiple requests? If true a new thread is started so requests are handled simultaneously. copyright and date info <%@ page info=³abc. version. Typically used to add author . info : Developer uses info attribute to add information/document for a page.

errorPage : Different page to deal with errors. Must be URL to error page <%@ page errorPage=³/error/error. This page has access to the implicit object exception .jsp´ %> isErrorPage : This flag is set to true to make a JSP page a special Error Page.

tables .  Typically include files are used for navigation. .2. headers and footers that are common to multiple pages.Include directive  Allows a JSP developer to include contents of a file inside another.

<%@ include file = ³navigation. Two examples of using include files: This include the html from privacy.html found in the include directory into the current jsp page.html´ %> OR To include a navigation menu (jsp file ) found in the current directory. <%@ include file = ³include/privacy.jsp´ %> .

3. <%@ taglib uri=³tag lib URI´ prefix=³tag Prefix´ %> Custom tags were introduced in JSP 1.Tag Lib directive  A tag lib is a collection of the custom tags that can be used by the page. .1 and allow JSP developers to hide complex server side code from web designers.

%>)  Between <% and %> tags .. any valid Java Code is called a Scriptlet.. .Scriptlet tag (<%.  This code can access any variable or bean declared.

out. For example .println(message). to print a variable . %> . <% String message = ³Be in Peace´ .

Transfer control between pages browser independent support for applets   .Action tag There are three main roles of the action tags:  Enable the use of the server side Javabeans.

  . This way there would be no code in the JSP page dealing with sending emails. if you wanted to make a feedback form that automatically sent out an email. when the visitors presses the submit button this sends the details to a JavaBeans that sends out the emails. The JSP page can call these methods so can leave most of the code in these Javabeans.Javabeans  A Javabeans is a special type of the class that has a number of methods. By having a JSP page with a form. For example.

´ /> . To use a Javabean in a JSP page use the following syntax: <jsp:usebean id=³ id´ scope=³application´ class=³««.

 The following is a list of Javabean scopes: page ± valid until page completes request ± bean instance lasts for the client request. session ± bean lasts for the client session application ± bean instance created and lasts until application ends.    .

To include a page at run time you should use dynamic JSP includes.html´%> This is a useful for including common pages that are shared and is included at compile time. Dynamic JSP Include You have seen how a file can be included into a JSP using an include Directive: <%@ include file = ³include/privacy. <jsp:include page=³URL´ flush=³true´/> .

<HTML> <HEAD> <TITLE> JSP Example </TITLE> </HEAD> <BODY> JSP Example <BR> <%! String message = ³Be in Peace´. %> Todays Message is <%=message%> <Br> Counter is <%=counter%> </BODY> </HTML> . int counter = 0 .

.Implicit Objects  There are several objects that are automatically available in JSP called implicit objects.

http.Variable request response out session pagecontent application config page exception Of type javax.JspWriter javax.servlet.Object java.servlet.ServletConfig javax.servlet.httpServletRequest javax.PageContext javax.lang.jsp.servlet.http.http.HttpSession javax.http.http.servlet.ServletContext javax.jsp.servlet.lang.httpServletResponse javax.servlet.Throwable .

 config object Stores the Servlet configuration data. page object Represents the JSP page and is used to call any methods defined by the servlet class. .

 request object Access to information associated with a request. <% String str = request.getParameter(³uname´). This object is normally used in looking up parameter values and cookies. %> .

Cookie can be disables in the browser settings so are not always available. Works when cookies are not supported but can make bookmarking of web pages a problem because they have session specific information at the end of a URL.  . URL rewriting ± store session information in the URL.Session Tracking in JSP (Session Object)  Cookies ± a small text file stored on the clients machine.

 Hidden form fields .HTML hidden edit boxes such as <input type = ³hidden´ name=³user´ value=³ ---´>  Session objects ± JSP Implicit Object .

If there is not a session key with that name .getValue(³msg´) The return type of the method getValue is Object . so you will need to typecast to get the reuired value. A session object uses a key / value combination to store information. . null is returned. To retrieve information from a session: session.

 To set a session key with a value. session.putValue (³msg´ . val) .

> except JSP comments are never sent to the user¶s browser.JSP comment--%>  JSP comments are similar to HTML comments <!± HTML comment -.JSP comments<%-. HTML comments are visible in the page source.  .

<html> <head> <title> HTML and JSP Comments </title> </head> <body> <h2> Comments </h2> <!² This HTML Comment-visible in the page source --> <%-.This JSP comment-Not visible in the page source -.%> </body> </html> .

So what makes an error page different from other JSP pages?    . JSP can handle these situations so when an exception is thrown . a default error page is sent to the browser. this is when an exception gets thrown.Error pages  Eventually there will come a time when sometime unexpected happens. In Java terms.

toString() %> </Body> <HTML> . One of the first lines in an error page must be the page directive isErrorPage=³true´ Inside your default error page (errorPage. above the<HTML> tag type:  <%@ page isErrorPage=³true´ import=³java.util.jsp).*´ %> <HTML> <BODY> Error Occurred <%= exception.

</HTML>  This code will go to errorPage. Our error page also uses the exception object and the toString() method to display a brief description of the error. To use a specific error page in your JSP pages. Even after an error.jsp if an error occurs.. . the HTTP session remains available. again above the <HTML> tag type: <%@ page errorPage=³errorPage.jsp´%> <HTML> «««.

getParameter(³name´) %> </body> </html> .jsp <%@ page errorPage=³errorHandler. <%= request.jsp´%> <html> <body> <% if(request.Hello.getParameter(³name´)==null) { throw new RuntimeException(³Name not Specified´). } %> Hello.

jsp <%@ page isErrorPage=³true´ %> <html> <body> Unable to process your request: <%= exception. <body> </html> .errorHandler.getMessage()%> <br> Please try again.

 In JSP 1. It can also be a static file .2 . it is not necessary that the errorPage value be a JSP page. such as an HTML page: <%@ page errorPage = ³errorHandler.html´ %>  .

The Need for JSP ‡ With servlets. it is easy to ² Read form data ² Read HTTP request headers ² Set HTTP status codes and response headers ² Use cookies and session tracking ² Share data among servlets ² Remember data between requests ² Get fun. high-paying jobs ‡ But. it sure is a pain to ² Use those println statements to generate HTML ² Maintain that HTML .

‡ Idea:

The JSP Framework

² Use regular HTML for most of page ² Mark servlet code with special tags ² Entire JSP page gets translated into a servlet (once), and servlet is what actually gets invoked (for each request) ‡ Example: <HTML> <HEAD> <TITLE>Order Confirmation</TITLE> </HEAD> <BODY> <H2>Order Confirmation</H2> Thanks for ordering <I> <%= request.getParameter("title") %> </I> ! </BODY> </HTML>

Benefits of JSP
² Write HTML. ² Read and maintain the HTML. ² Use standard HTML tools such as Macromedia DreamWeaver or Adobe GoLive. ² Have different members of your team do the HTML layout than do the Java programming. ² Separate the (Java) code that creates the content from the (HTML) code that presents it.

Advantages of JSP Over Competing Technologies ‡ Versus ASP or ColdFusion ² Better language for dynamic part ² Portable to multiple servers and operating systems ‡ Versus PHP ² Better language for dynamic part ² Better tool support ‡ Versus pure servlets ² More convenient to create HTML ² Can use standard tools (e.g., DreamWeaver) ² Divide and conquer ² JSP programmers still need to know servlet programming

BroadVision) ² Richer language ‡ Versus static HTML ² Dynamic features ² Adding dynamic features no longer "all or nothing" decision .‡ Versus Velocity or WebMacro ² Standard ‡ Versus client-side JavaScript (in browser) ² Capabilities mostly do not overlap with JSP.g. LiveWire.. not client ‡ Richer language ‡ Versus server-side JavaScript (e. but ‡ You control server.

‡ Use packages to avoid name conflicts : Not. ² Use same URLs as for HTML pages (except for file extensions) . ‡ Put JSP page in special directory: Not.Setting Up Your Environment ‡ Set your CLASSPATH : ‡ Compile your code : Not. Not. ‡ Use special URLs to invoke JSP page: Not.

util.getId() %> <LI>The <CODE>testParam</CODE> form parameter: <%= request.Date() %> <LI>Server: <%= application.<HTML> <HEAD> <TITLE>JSP Expressions</TITLE> </HEAD> <BODY> H2>JSP Expressions</H2> <UL> <LI>Current time: <%= new java.getServerInfo() %> <LI>Session ID: <%= session.getParameter("testParam") %> </UL> </BODY> </HTML> .

System.util.<HTML> <BODY> <% // This is a scriptlet. %> Hello! The time is now : <%= date %> </BODY> </HTML> . java.println( "Evaluating date now´ ).Date(). Notice that the "date" // variable we declare here is available in the // embedded expression later on.util.Date date = new java.out.

valueOf( date )). %> Hello! The time is now <% // This scriptlet generates HTML output out.util.<HTML> <BODY> <% // This scriptlet declares and initializes "date" System.println( "Evaluating date now" ).println( String. %> </BODY> </HTML> . java.Date().out.util.Date date = new java.

println( "Evaluating date now" ).util.Date(). %> </BODY> </HTML> . out.println( date ).<HTML> <BODY> <% // This scriptlet declares and initializes "date" System.println( "<BR>Your machine's address is " ).out.util. java. out.println( request.getRemoteHost() ).Date date = new java. %> Hello! The time is now <% out.

i < n. i++ ) { %> <TR> <TD> Number </TD> <TD> <%= i+1 %> </TD> </TR> <% } %> </TABLE> .<TABLE BORDER=2> <% for ( int i = 0.

world <% } else { %> <P>Goodbye. world <% } %> .<% if ( hello ) { %> <P> Hello.

*" %> . Date date = new Date().JSP Directives <%@ page import="java. A JSP "directive" starts with <%@ characters. java. %> Hello! The time is now <%= date %> </BODY> </HTML> The first line in the above example is called a "directive".println( "Evaluating date now" ). <%@ page import= "java.text.out.util.util.*" %> <HTML> <BODY> <% System.*.

The included file can be HTML or JSP or anything else -.. The include directive is used to physically include the contents of another file.jsp" %> </BODY> </HTML> . <HTML> <BODY> Going to include hello.the result is as if the original JSP file actually contained the included text..jsp.<BR>  <%@ include file="hello.

return theDate.out. } %> Hello! The time is now <%= getDate() %> </BODY> </HTML> .println( "In getDate() method´).*" %> <HTML> <BODY> <%! Date theDate = new Date().util. Date getDate() { System.JSP Declarations <%@ page import="java.

java Package foo. public static synchronized int getCount() { count++.Counter. public class counter { private static int count. return count. } } .

BasicCounter.jsp <html> <body> The page count is : <% out.getCount()).println(Counter. %> </body> <html> OutPut ? .

getCount()).JSP code should be : <% out.Counter. %> OR <% page import=³foo.*´ %> .println(foo.

getCount()). %> </body> </html> Expression code: <@ page import=³foo.*´%> <html> <body> The page count is : <%= Counter.getCount() %> </body> </html> .Scriptlet code: <@ page import=³foo.println(Counter.*´%> <html> <body> The page count is : <% out.

 Scriptlet : <% %>  Directive : <%@ %>  Expression : <%= %> .

When the container sees this : <%= Counter.getCount() %> It turns it into this : out.getCount()). .print(Counter.

getCount(). %> That would be bad.getCount().).If you did put a semicolon in your expression: <%= Counter.print(Counter.It would mean this: out. .

random() %> <%= String s = ´fooµ %> <%= new String[3] %> <% = 42*20.random()+5)*2). 7. 9. %> <%= ´27µ %> <%= Math. 6. 8. 5. 3. %> <%= 5>3 %> <%= false %> <%= new Counter() %> Answer ? . 2. 4. 10.Valid or Not ? 1. <%= 27 %> <%= ((Math.

because the new String array is an object . String literal is fine. 4. and ANY object can be sent to a println() statement. 8. . the method returns a double. No! The semicolon can¶t be here. 3. All primitive literals are fine. this resolves to a boolean. 10. Yes.Answers 1. 5. No! you can¶t have a variable declaration here. 2. This is just like the String [] «. 7. It prints the result of the object¶s toString() method. Yes . but there¶s a space between the % and the =. Primitive literals are fine No problem. No! The arithmetic is fine . so it prints µtrue¶. 6. It can¶t be <% = . it must be <%= Sure . 9.

Will it compile? Will it Work?

<html> <body> <% int count = 0; %> The page count is : <%= ++count %> </body> </html> If it compiles see the O/P

What Really happens to your JSP code?
This JSP: <html> <body> <% int count = 0; %> The Page count is now : <%= ++count %> </body> </html>

Becomes this servlet: public class basicCounter_jsp extends SomeSpecialHttpServlet { public void _jspservice(HttpServletRequest req,HttpServletResponse resp) throws java.io.IOException , ServletException { PrintWriter out = response.getWriter(); response.setContentType(´text/htmlµ); out.write(´<html><body>µ); int count = 0; out.write(´The page count is now:µ); out.print(++count); out.write(´</body></html>µ); } }

Larry Williams . Before the changes can be made to the entire application . if the entered customer id or password is incorrect. The customer id has to be in a numeric form.Assignment       John Barrett the Chief Technology Officer has entrusted the development team with the task of creating an application that validates id and password of every customer before they can access their account datails. John wants to test this functionality be making a sample application for a specific customer . He also wants that an error message should be displayed to the customer. Larry decides to use JSP for developing this application . the programmer has been assigned the task of implementing this functionality.