jsp

11
JSP (Java Server pages) JSP is a Java technology that helps software developers serve dynamically generated web pages based on HTML, XML or other document types. It was developed by Sun Microsystems in 1999. It is a simplified, fast way to create dynamic web content. JSP enables rapid development of web based applications that are server and platform independent. a JSP page is simply an HTML web page that contains additional bits of code that execute application logic to generate dynamic content. This application logic may involve JavaBeans, JDBC objects, Enterprise Java Beans (EJB), and Remote Method Invocation (RMI) objects. The separation of user interface and program logic in a JSP page allows for a very convenient delegation of tasks between web content authors and developers. It also allows developers to create flexible code that can easily be updated and reused. JSP Syntax Syntax is almost similar to that of XML. Tags have either a start tag with optional attributes, an optional body, and a matching end tag or they have an empty tag possibly with attributes. Attribute values in the tag always appear quoted. The special strings &apos; and " can be used if quotes are a part of the attribute value itself. ‘/’ is used as an escape character, ex: <%..../%>

Upload: aadafull

Post on 17-May-2017

213 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: JSP

JSP (Java Server pages)

JSP is a Java technology that helps software developers serve dynamically generated web pages based on HTML, XML or other document types.

It was developed by Sun Microsystems in 1999.

It is a simplified, fast way to create dynamic web content.

JSP enables rapid development of web based applications that are server and platform independent.

a JSP page is simply an HTML web page that contains additional bits of code that execute application logic to generate dynamic content.

This application logic may involve JavaBeans, JDBC objects, Enterprise Java Beans (EJB), and Remote Method Invocation (RMI) objects.

The separation of user interface and program logic in a JSP page allows for a very convenient delegation of tasks between web content authors and developers.

It also allows developers to create flexible code that can easily be updated and reused.

JSP Syntax

Syntax is almost similar to that of XML.

Tags have either a start tag with optional attributes, an optional body, and a matching end tag or they have an empty tag possibly with attributes.

Attribute values in the tag always appear quoted. The special strings &apos; and " can be used if quotes are a part of the attribute value itself.

‘/’ is used as an escape character, ex: <%..../%>

JavaServer Pages are text files that combine standard HTML and new scripting tags.

JSPs look like HTML, but they get compiled into Java servlets the first time they are invoked.

The resulting servlet is a combination of HTML from the JSP file and embedded dynamic content specified by the new tags.

Everything in a JSP page can be divided into two categories:

Elements that are processed on the server

Template data or everything other than elements, that the engine processing the JSP engines.

JSP Page life cycle

Page 2: JSP

The JSP page life cycle can be grouped into following phases:

JSP page Translation

JSP page Compilation

Class loading

Execution

Initialization

jspService() execution

jspDestroy() execution

JSP Page translation

The container validates the syntactic correctness of the JSP pages and tag files. The container interprets the standard directives and actions, and the custom actions referencing tag libraries used in the page.

JSP Page Compilation

The generated java servlet file is compiled into a java servlet class.

Class loading

The java servlet class that was compiled from the JSP source is loaded into the container.

Execution

In the execution phase the container manages one or more instances of this class in response to requests and other events.The interface JspPage contains jspInit() and jspDestroy(). The JSP specification has provided a special interface HttpJspPage for JSP pages serving HTTP requests and this interface contains jspService().

Initialization

jspInit() method is called immediately after the instance was created. It is called only once during JSP life cycle.

jspService() execution

This method is called for every request of this JSP during its life cycle. This is where it serves the purpose of creation. It passes the request and the response objects. jspService() cannot be overridden.

jspDestroy() execution

Page 3: JSP

This method is called when this JSP is destroyed. With this call the servlet serves its purpose and submits itself to heaven (garbage collection). This is the end of jsp life cycle.

JSP Elements

JSP elements can be classified under following categories:

Directives

Scripting elements

Standard actions

1. JSP Directives

2. JSP directives serve as messages to the JSP container from the JSP.

3. They are used to set global values such as class declaration, methods to be implemented, output content type, etc.

4. They do not produce any output to the client. All directives have scope of the entire JSP file.

5. That is, a directive affects the whole JSP file, and only that JSP file.

6. Directives are characterized by the @ character within the tag and the general syntax is:

a. <% @ page language=“java” %>

7. The three directives are page, include and taglib.

2. JSP Scripting elements

They are used to include scripting code (Java Code) within JSP.

They allow to declare variables and methods, include arbitrary scripting code and evaluate an expression.

The three types of scripting elements are:

Declaration

Scriptlets

Expressions.

2.1 Declarations

A declaration is a block of Java code in a JSP that is used to define class-wide variables and methods in the generated class file.

Page 4: JSP

Declarations are initialized when the JSP page is initialized and have class scope.

Anything defined in a declaration is available throughout the JSP, to other declarations, expressions or code.

2.2 Scriplets

A scriptlet consists of one or more valid Java statements. A scriptlet is a block of Java code that is executed at request-processing time. A scriptlet is enclosed between "<%" and "%>".

2.3 Expressions

An expression is a shorthand notation for a scriptlet that outputs a value in the response stream back to the client. When the expression is evaluated, the result is converted to a string and displayed, An expression is enclosed within "<%=" and "%>". If any part of expression is an object, the conversion is done using the toString() method of the object

3. Standard actions

Standard actions are specific tags that affect the runtime behaviour of the JSP and affect the response sent back to the client.

Standard actions provide page authors with some basic functionality to exploit; the vendor is free to provide other actions to enhance behaviour.

How JSP page works?

JSP pages are high level extension of servlet and it enable the developers to embed java code in html pages.

JSP files are finally compiled into a servlet by the JSP engine. Compiled servlet is used by the engine to serve the requests.

javax.servlet.jsp package defines two interfaces:

JSPPage

HttpJspPage

These interfaces defines the three methods for the compiled JSP page. These methods are:

jspInit()

jspDestroy()

jspService(HttpServletRequest request,HttpServletResponse response)

In the compiled JSP file these methods are present.

Page 5: JSP

Programmer can define jspInit() and jspDestroy() methods, but the jspService(HttpServletRequest request,HttpServletResponse response) method is generated by the JSP engine.

JSP Actions

Servlet container provides many built in functionality to ease the development of the applications. Programmers can use these functions in JSP applications. The JSP Actions tags enables the programmer to use these functions. The JSP Actions are XML tags that can be used in the JSP page.

Some of the JSP Action tags are as follows..  

jsp:include The jsp:include action work as a subroutine, the Java servlet temporarily passes the request and response to the specified JSP/Servlet. Control is then returned back to the current JSP page.

jsp:param The jsp:param action is used to add the specific parameter to current request. The jsp:param tag can be used inside a jsp:include, jsp:forward or jsp:params block. 

jsp:forward The jsp:forward tag is used to hand off the request and response to another JSP or servlet. In this case the request never return to the calling JSP page.  

jsp:plugin In older versions of Netscape Navigator and Internet Explorer; different tags is used to embed applet. The jsp:plugin tag actually generates the appropriate HTML code the embed the Applets correctly.

jsp:fallback The jsp:fallback tag is used to specify the message to be shown on the browser if applets is not supported by browser.Example:   <jsp:fallback>       <p>Unable to load applet</p>    </jsp:fallback>

jsp:getProperty The jsp:getPropertyB is used to get specified property from the JavaBean object.  

Page 6: JSP

jsp:setProperty The jsp:setProperty tag is used to set a property in the JavaBean object.  

jsp:useBean The jsp:useBean  tag is used to instantiate an object of Java Bean or it can re-use existing java bean object.

JSP Example (DATE)

This example simply prints the current date and time.

<html><body><p>&nbsp;</p><div align="center"><center><table border="0" cellpadding="0" cellspacing="0" width="460" bgcolor="#EEFFCA">

<tr><td width="100%"><font size="6" color="#008000">&nbsp;Date Example</font></td>

</tr><tr><td width="100%"><b>&nbsp;Current Date and time is:&nbsp; <font color="#FF0000">

<%= new java.util.Date() %></font></b></td></tr></table></center></div></body></html>

Sessions in JSP

In any web application user moves from one page to another and it becomes necessary to track the user data and objects throughout the application.

JSP provide an implicit object "session", which can be use to save the data specific the particular to the user.

Example of session

This file takes an input from the user.

<%@ page language="java" %><html>

Page 7: JSP

<head><title>Name Input Form</title></head><body><form method="post" action="savenametosession.jsp"><p><b>Enter Your Name: </b>

<input type="text" name="username"><br><input type="submit" value="Submit"></form></body>

The JSP savenametosession.jsp retrieves the user name from request attributes and saves into the user session using the function session.setAttribute("username",username);.

<%@ page language="java" %><%String username=request.getParameter("username");if(username==null)

{

username="";}

session.setAttribute("username",username);%><html><head><title>Name Saved</title></head><body><p><a href="showsessionvalue.jsp">Next Page to view the session value</a><p></body>

The above JSP saves the user name into the session object and displays a link to next pages (showsessionvalue.jsp).

When user clicks on the "Next Page to view session value" link, the JSP page showsessionvalue.jsp displays the user name to the user.

<%@ page language="java" %><%String username=(String) session.getAttribute("username");if(username==null) username="";%>

Page 8: JSP

<html><head><title>Show Saved Name</title></head><body><p>Welcome: <%=username%><p></body>

Advantages of JSP

JSP pages easily combine static templates, including HTML or XML fragments, with code that generates dynamic content.

JSP pages are compiled dynamically into servlets when requested, so page authors can easily make updates to presentation code. JSP pages can also be precompiled if desired.

JSP tags for invoking JavaBeans components manage these components completely, shielding the page author from the complexity of application logic.

Developers can offer customized JSP tag libraries that page authors access using an XML-like syntax.

Web authors can change and edit the fixed template portions of pages without affecting the application logic. Similarly, developers can make logic changes at the component level without editing the individual pages that use the logic.

Disadvantages of JSP

JSP implementations typically issue poor diagnostics.  

Because JSP pages are translated, and then compiled into Java servlets, errors that creep in your pages are rarely seen as errors arising from the coding of JSP pages

JSP pages require about double the disk space to hold the page.

Because JSP pages are translated into class files, the server has to store the resultant class files with the JSP pages.

JSP pages must be compiled on the server when first accessed. This initial compilation produces a noticeable delay when accessing the JSP page for the first time.

The layout (.jsp file) is Java specific. It assumes your application speaks Java.