Document Sample
Jsp Powered By Docstoc
Java Server Pages

Introduction to JSP
JSP is a template for a web page that uses Java code to generate a HTML document dynamically.  They run in a server-side component known as JSP container, which translates them into equivalent servlets.  It is a server-side scripting environment.

How JSP Works

JSP Source Code
– This is the form the developer actually writes. It exists in a text file with extension .jsp and consists of a mix of HTML template code, Java language statements and JSP directives and actions that describe how to generate a web page to service a particular request.


Java Source Code
– The JSP container translates the JSP source code into the source code for an equivalent Java servlet as needed. This source code is stored in work area and will be helpful in debugging.


Compiled Java Class
– Like any other class, the generated servlet code is compiled into byte codes in a .class file ready to be loaded and executed.

Start Determine class name

Logic used by JSP container to manage JSP Translation


Does class Already exist? No


Translate JSP Source into Java Servlet Source Compile Servlet Source code into Class file Load class and Create instance Send request to This instance End

Class newer Than JSP? Yes


Instance Already Running? Yes

JSP Phases and Components

Has two operational Phases
– Translation time – Generating the Java servlet code from a .jsp file. – Request time – Invoking the servlet to handle the HTTP request.


Components of a JSP Page
– JSP Elements
 Directives  Scripting Elements declarations)  Actions (expressions, scriptlets and

– Fixed Template Data – A combination of JSP Elements and Fixed Template Data

JSP Elements

Directives – are instructions to the JSP container that describe what code should be generated.
– The general form will be
<%@ directive-name [attribute=“value” attribute=value …] %> Three standard directives are available  page  include  taglib

– The page Directive
 Is used to specify attributes for the JSP page as a whole. The syntax will be: <%@ page [attribute=“value” …] %> The list of attributes will be: language, extends, import – a comma separated list of packages, session, buffer, autoflush,isThreadSafe, info, isErrorPage, errorpage, contentType

JSP Elements (Contd..)

The include Directive
– Merges the contents of another file at translation time into the .jsp source inputstream, much like a #include C preprocessor directive. The syntax is:
<%@ include file=“filename” %>


The taglib Directive
– Makes custom actions available in the current page through the use of a tag library. The syntax is:
<%@ taglib uri=“taglibraryuri” prefix=“tagPrefix” %>

JSP Elements (contd..)

– Two means of providing comments.
 Hidden – visible only in .jsp page  HTML comments <%-- This is a hidden comment --%> <!– This is included in generated HTML 


– Provides a simple means of accessing the value of a Java variable or other expression and merging that value in the HTML in that page. The syntax is:
<%= exp %> e.g. The current time is <%= new java.util.Date() %>

JSP Elements (contd…)

– Is a set of one or more Java language statements intended to process a HTTP request. The syntax is:
<% statement; [statement; …] %>

The JSP compiler simply places the scriptlet code verbatim in the body of the _jspService() method.

– Declarations contain Java language statements, but with one big difference from a scriptlet – The scriptlet code becomes part of the _jspServive() method whereas the declarations will be incorporated outside the _jspService() method. The syntax is:
<%! statement;[statement; …] %>

Implicit Objects in JSP
request – ServletRequest or HttpServletRequest  response – ServletResponse or HttpServletResponse  pageContext – The pageContext object for this page.  Session - HttpSession object  Application – ServletContext  out – The character outputstream used to generate HTML.  config – The ServletConfig object of the servlet context  page – A reference to the JSP Page itself  Exception – An uncaught exception that causes the error page to be invoked.

Standard Actions

 

 


Actions are high level JSP elements that create, modify or use other objects. Actions are coded using strict XML syntax. <jsp:useBean> <jsp:setProperty> <jsp:getProperty> <jsp:include> <jsp:forward> <jsp:param> <jsp:plugin>

Is used to associate a JavaBean with the JSP. It ensures that the object is available for the appropriate scope specified in the tag.  The attributes of this tag are:

– class=“className” – type=“typeName” – beanName=“beanName” – id = “identifier” – scope=page|request|application|session


What are the underlying semantics that occur in respect of this tag?

<jsp:useBean> (Contd..)

– The container tries to locate an object that has this id, in the specified scope. – If the object is found and the type has been specified in the tag, the container tries to cast the found object to the specified type. A java.lang.ClassCastException is thrown if the cast fails. – If the object is not found in the scope and no class or beanName is specified in the tag, a java.lang.InstantiationException is thrown. – If the object is not found in the specified scope, and the class specified is a non-abstract class with a public no argument constructor, then that class is instantiated. A new object reference is associated with the variable in the specified scope. If any conditions specified in this step are not met, then a java.lang.InstantiationException will be thrown. – If the object is not found in the specified scope, and a beanName is specified then the instantiate() method of the java.beans.Beans is invoked (with the beanName as an argument). If the method suceeds, the new object reference is associated with the variable in the specified scope. – If the jsp:useBean element has a non-empty body, the body is processed. At this point the variable is initialized and is availablw within the scope of the body. The body is processed like any part of the JSP and any template text is sent to the outputstream.

This is used in conjunction with useBean action and sets the value of simple and indexed properties in the bean.  The properties of a bean can be set either:


Bean introspection is used to discover what properties are present, their names, if they are simple or indexed, their type and the accessor and the mutator methods.

– At request time from parameters in the request object – At request time from an evaluated expression – From a specified string

<jsp:setProperty> (Contd..)

The attributes are:
– name=“beanName” – property=“*” – property=“propertyName” – property=“propertyName” param=“paramName” – property=“propertyName” value=“propertyValue”


This is complementary to jsp:setProperty action. It accesses the value of the property, converts it into String and prints to the output stream.
– Attributes
 name=“beanName”  Property=“propertyName”


Is used to provide other tags with additional information in the form of name-value pairs. This is used in conjunction with jsp:include, jsp:forward and jsp:plugin.
– Attributes:
 name=“paramName”  Value=“paramValue”


This action allows a static or dynamic resource to be included in the JSP at request time. The included page has access only to the JspWriter object and it cannot set headers or cookies. It is equivalent to the include() method of javax.servlet.RequestDispatcher class.
– Attributes:
 page=“urlSpec”|”fileName”  flush=“true|false”


This tag may include one or more param tags in its body.


Allows the request to be forwarded to another JSP, a servlet or a static resource.
– Attribute:
 page=“urlSpec”

<jsp:plugin> is used to generate client browser specific tags that ensures that the Java Plug-in software is available followed by the execution of the applet or JavaBean component specified in the tag.

<jsp:plugin> (Contd..)

– – – – – – – – – – – – – –

type (Bean or Applet) code codeBase align archive height width hspace jreversion name vspace title nspluginurl iepluginurl

A Simple JSP Page printing today’s Date
<%@ page language=“java” import=“java.util.* %> <HTML><BODY> <H1>The current date and time is <%= new java.util.Date() %></H1> </BODY></HTML>

Why Custom Tags?

Custom tags provide a means of bridging the gap between two specialist (a HTML specialist and a Java language specialist). Java programmers can provide application functionality in convenient packages that Web designers can use as building blocks. Custom tags enable a higher-level application specific approach to JSP development.

Tag Extensions (Custom Tags)
Custom tags are XML-like extensions to the syntax and semantics of a JSP page that are backed by user-written tag handlers.  Collections of tags are organized into tag libraries that can be packaged as jar files, enabling their functionality to be easily distributed and installed over any JSP 1.1compliant servlet engine.

Benefits of Custom Tags

Besides separation of content and presentation, other benefits of custom tags include:
– Simplicity – It is significantly easier to express a complex task as a cooperating set of subtasks with their own attributes and control flow than it is to write it as a monolithic block of code. – Opportunity for code reuse – Tag Libraries make it easier to package standard code and share it throughout an application. – Suitability for authoring tools- IDE’s can only see scriptlet blocks as blocks of ASCII text. Custom tags, however by virtue of having a Tag Library Descriptor, lend themselves to being managed by a development tool that can display their descriptions, validate their attributes and so on.

Developing Your First Custom Tag

There are four basic steps to create your custom tags. They are:
– Define the tag. – Write the entry in the Tag Library Descriptor. – Write the tag handler. – Use the tag in the JSP Page

Step 1: Define a Tag
What is the name of the tag?  What attributes does it have?  Will the tag define scripting variables?  Does the tag do anything special with the body contained between its start and end tags? Our tag is called showTime tag. It has no attributes, no scripting variables and the tag has no body.

Step 2: Create the TLD Entry
A Tag Library Descriptor is an XML document that defines the names and attributes of a collection of related tags <?xml version=“1.0” ?> <taglib> <tlibversion>1.0</tlibversion> <jspversion>1.1</jspversion> <shortname>time</shortname> <tag> <name>showTime</name> <tagclass>tagexamples.ShowTimeTag</tagclass> <bodycontent>empty</bodycontent> </tag> </taglib> TLDs are usually installed in a directory named WEB-INF/tlds.

Step 3: Write the Tag Handler

A tag’s action is implemented in a Java class known as tag handler. Instances of tag handlers are created and maintained by the JSP container and predefined methods in these classes are called from a JSP page’s generated servlet. package tagexamples; import javax.servlet.http.*; import javax.servlet.jsp.*; import javax.servlet.jsp.tagext.*; import java.io.*; import java.net.*;

public class ShowTimeTag extends TagSupport { public int doStartTag() throws JSPException { try { JSPWriter out = PageContext.getOut(); out.println(“The current time is “+new java.util.Date().toString()); } catch(Exception ee){} return SKIP_BODY; } }

Step 4: Use it in JSP page
Compile the source and put the class file in tagexamples directory under your application directory’s WEBINF\classes directory.  Incorporate the Tag into the JSP Page Specify the taglib directive <%@ taglib prefix=“time” uri=“/WEBINF/tlds/showTime.tld” %> <HTML> <BODY> <H1>Example for a custom tag</H1> <h3><time:showTime /></h3> </body></html>

Shared By: