You are on page 1of 59

JSP element types

Just like any other scripting lang tags, JSP also has got its well defined tags for performing various tasks like declaring vars,methods,exprs,and calling other jsp pages.

JSP element types


JSP tag type description syntax

Directives

Specifies translation time instructions to the JSP engine.


Declares and defines methods and vars

<%@ directive%>

Declaration

<%! Java declarations%>

Scriptlet

Allows the developer to write free-form java code in a jsp page


Used as a shortcut to print values in the output HTML of a JSP page Provides request-time instructions to the JSP engine Used for commenting jsp code

<% some java code%>

Expression

<%=An expr%>

Action

<jsp:actionName/>

Comment

<%-- any time --%>

Directives

Directives provide general information about the JSP page to the JSP engine. There are three types of directives: page, include and taglib. A page directive informs the JSPengine about the overall properties of a JSP page. For eg. The foll. Page directive informs the JSP engine that we will be using Java as the scripting lang in our JSP page. <%@ page language=java %> An include directive tells the JSP engine to include the contents of another file(HTML,JSP,etc.) int the current page. Here is an example of an include directive: <%@ include file=copyright.html %> A taglib directive is used for associating a prefix with a tag library. The foll. Is an ex. Of a taglib directive: <%@ taglib prefix=test uri=taglib.tld%>

<%@ page attr-list %> <%@ include attr-list %> <%@ taglib attr-list %>

The tag names, their attributes and their values are all case sensitive The value must be enclosed within a pair of single or douuble quotes A pair of single quotes is equivalent to a pair of double quotes There must be no space between the equals sign(=) and the value.

Declarations Declarations declare and define vars and methods that can be used in the JSP page.
<%! int count =0; %> The var is only intialized only once to 0. When page is first loaded by JSP engine, and it retains its value in subsequent client requests.

<%! String color[] ={red,green,blue}; String getColor(int i) { return color[i]; }

%>

Scriptlets Scriptlets are Java code fragments that embedded in the JSP page.

<% count++; %> The scriptlet is executed each time it gets executed. The scriptlet gets excuted each time the page is accessed, and the count variable is incremented with each request.

<%@ page language=java%>


<%! int count=0; %> <% out.print(<html><body>); count++; out.print(welcome! U r visitor number+count); Out.print(</body></html>); %>

Expressions Expressions act as placeholders for java Expressions.

Eg.<%=count%> Never to have a semicolon at the end of exprn. <html><body>

<%@ page language=java%>


<%! int count=0; %> welcome! U r visitor number<%= ++count %> </body></html>

JSP life cycle translation


Phase Name
Page translation

Description
The page is parsed and a Java file containing the corresponding servlet is created The java file is compiled The compiled class is loaded An instance of servlet is created This method is called before any other method to allow initilization This method is called for each request This method is called when servlet container decides to take servlet out of service.

Page compilation Load class Create instance Call jspInit() Call _jspService() Call jspDestroy()

Calling life cycle methods

The generated servlet class for a jsp page implements HttpJspPage interface, which is in javax.servlet.jsp pkg. The HttpJspPage extends JSP page interface of the same pkg, which in turn extends Servlet interface of the javax.servlet pkg. The generated servlet class thus implements all three interfaces and also known as pages implementation class.

The JspPage interface has two methods jspInit() and jspDestroy()-that must be implemented by all jsp pages regardless of client server protocol. Http requests,HttpJspPage interface with one method _jspService().

Public void jspInit(); Public void _jspservice(HttpServletRequest req, HttpServletResponse) throws javax.servlet.ServletException,java.io.IOException; Public void jspDestroy();
JspPage interface- two methods jspInit() and jspDestroy(); _jspservice() is added by jsp engine durning translation phase making the implementation class as concrete subclass of three interfaces.

Jspinit() The container calls this method to initialize the servlet instance. We normally define this method for one time setup such as acquiring resources and initializing the instance variables that been declared using <%!...%> declarations Jspdestroy() When the container decides to take out instance out of service,it calls jspDestroy(). This is last method called on servlet instance, and it is used to clean up the resources acquired in jspInit(). We are not req to implement jspInit() and jspDestroy(),bcoz implemented by base class but if wants to override these two methods, then can be done <!....%> But cannot define _jspService() bcoz generated by engine automatically.

Jsp life-cycle example

Lets modify our counter ex to add persistence capabilities to it so that the counter does not start from 1 each time the server is shut down and restrated. Use jspInit() to load the previous value of the counter from a file when server starts. Use jspdestroy() to save the final to the file when the server shuts down.

<%@ page language=java import=java.io.*%. <%! //A var to maintain the number of visits Int count=0; //Path to the file, counter1.txt, which stores the count //value in a serialized form. The file acts like a database. String file; public void jspInit(){ Try { file=getServletContext().getRealPath(/counter1.txt); FileInputStream fis=new FileInputStream(file); DataInputStream dis=new DataInputStream(fis); count=dis.readInt(); dis.close(); } catch(exception e){ System.out.println(e); } }%>

<% count++;%>

Welcome !you r visitor number<%=count%> <%! Public void jspDestroy() { try { FileOutputStream fos=new FileOutputStream(file); DataOutputStream dos=new DataOutputStream(fos); dos.writeInt(count); dos.close(); } Catch(Exception e){] }%>

Page Directive Attributes A page directive informs the JSp engine about overall properties of a JSp page. This directive applies to the translation unit. There 12 attributes for page directive
Attr Name import Description A comma-seprated list of java classes and pkgs that we want to use in the JSP page A boolean literal , whether the jsp page takes part in an Http session. Specifies relative URL to another JSP page that is capable of handling errors on the behalf of current page Default values Java.lang.*; Javax.servlet.*; Javax.servlet.jsp.*; Javax.servlet.http.*; true

session

errorPage

null

isErrorPage

A bolean literal specifying false whether the current JSP page is capable of handling errors Any scripting language supported by the JSP engine java

language

extends

Any valid java class that implements javax.servlet.jsp.JspPage

Implementation dependent

buffer

Specifies the size of output buffer.If buffer size is specified, its in kilobytes.

Implementation dependent

autoflush

An boolean literal true indiacting whether the buffer should be flushed when it is full Any informative text about jsp page Character encoding for the output Specifies the character encoding of the JspPage Impl. dependent

Info

contentType

Text/html;charset= ISO-8859-1 ISO-8859-1

pageEncoding

<%@ page import=java.util.*%> <%@ page import=java.io.*%> <%@ page import=java.util.*,java.io.*%> <%@ page session=false%>

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

errorHandler.jsp
<%@ page isErrorPage=true%> <html><body> Unable to process your request:,<%=exception.getMessage()%> </body></html>

<%@ page extends=mypkg.MySpecialBaseServlet %> <%@ page buffer=32kb%> <%@ page autoFlush=false%> <%@ page buffer=none autoFlush=false%>

<%@ page info=this is a sample Page%>

<%@ page contentType=text\html;charset=ISO-8859-1%>

Implicit Variables and implicit objects

Durning translation phase, the Jsp engine declares and intializes nine commonly used variables in the _jspservice() method.
Class or interface Interface javax.servlet.ServletContext Interface Javax.servlet.http.HttpSessi on Interface Javax.servlet.http.Httpservl etRequest Interface Javax.servlet.http.Httpservl etResponse description Refers to the web applications environment Refers to the users session

Identifier name application session

request

Refers to the current requests to the page Used for sending a response to the client

response

out

Class javax.servlet.jsp.Jspwriter

Refers to the output stream for the page

page

class java.lang.Object

pageContext

config

exception

Refers to the pages servlet instance class Refers to the javax.servlet.jsp. pages PageContext environment Interface Refers to the javax.servlet.Serv servlets letConfig configuration Class Used for error java.lang.Throwa handling ble

Because the page author does not declare these variables explicitly,they are called implicit variables. The objs are to be created by servlet container and are called implicit objects.

Application The application var. is of the type javax.servlet.servletContext and it refers to the env of the web application to which the jsp belongs. <% String path=application.getRealPath(/abc.txt); application.log(using:+path);%>

Session

Session implicit var, lets clarify that the word session refers to four diff. but related things in JSP: Session, as in a HTTP session,is a concept that logically groups multiple reqs from the same client as part of one conversation. Session, as used in a page directive,refers to the attribute named session. <%@ page session=true%> Its value, which is true or false, determines whether or not the JSP page participates in HTTP Session. Session, as an implicit obj, refers to the variable session of type javax.servlet.http.HttpSession. Session, as a scope of an obj, refers to the lifetime and availability of the object. A session-scoped persists throughout the life of an HTTP session.

<body> <%@ page session=true%> Session ID=<%=session.getId()%> </body>

Request and Response


The request and response implicit vars are of type javax.servlet.http.HttpServletRequest and javax.servlet.http.HttpServletResponse, respectively. <% String remoteAddr=request.getRemoteAddr(); Response.setContentType(text/html;charset=ISO8859-1);%> <html><body> HI! Your IP address is <%=remoteAddr%>

Login.jsp <% String str=request.getParameter(user); request.setAttribute(User,str); pageContext.forward(authenicate.jsp);return; %>

File authenticate.jsp String str=request.getParameter(User); If(isValid(str)) { request.removeAttribute(str); Session.setAttribute(User,str); pageContext.forward(account.jsp);} else { pageContext.forward(loginError.jsp);} return;%>

page

The implicit variable page is class java.lang.Object and it refers to the instance of the generated servlet. It is declared as Object page=this; <%=this.getServletInfo()%>

pageContext
The pageContext var is of type javax.jsp.PageContext. The pageContext class is an abstarct class, and the JSP engine vendor provides its concrete subclass. Stores reference to the implicit objs. The session,application,config and out implicit vars are intialized using the objs retrieved from pageContext. Provides convenient methods for transferring requests to other resources. pageContext.forward(other.jsp);

Unrecognized attr result in fatal translationerrors.

<%@ page lanaguage=Java import=java.rmi.*,java.util.* session=true buffer=12kb autoflush=true info=my page directive jsp error=error.jsp isErrorPage=false isThreadSafe=false%> <html> <body> This is to test the page directive. </body> </html>

<html> <head> <title>Include directive test page</title> </head> <%@ include file=included file%> </body> </html>

Included.jsp

<%@ page import=java.util.Date%> <%=current date is +new Date()%>

Scopes of JSP page


Scope Name Application Existence and Accessibility Limited to a single web application

Session
Request Page

Limited to a single user session


Limited to a single request Limited to single page and a single request

Action tags

The standard JSP actions jsp:include jsp:forward jsp:useBean jsp:setProperty jsp:getProperty

JavaBeans Components

A Javabeancomponent is Java tech. class with min. following features Properties defined with accessors and mutators. No args constructor No public instance vars The class implements the java.io.Serializable interface.

Package p1; import java.io.Serializable; Public class Customerbean implements Serializable { private String name; Private String email; Private String phone; Public CustomerBean() { this.name=; this.email=; this.phone=;} Public void setName(String name){ this.name=name;} Public String getName() { Return name;} Public void setEmail(String email) { this.email=email; }

Public String getEmail() { return email;} Public void setPhone(string phone) { this.phone=phone;} Public String getPhone(){ Return phone;} }

If u want to interact with a JavaBeans components using std tags in a JSP page. U must first declare the bean. The action tag usebean syntax <jsp:useBean id=beanName scope=page/request/session/applicatio n class=className />

<jsp:useBean id=myBean scope=request class=p1.CustomerBean /> <% myBean.setName(request.getParamter(name)); myBean.setName(request.getParamter(email));

myBean.setName(request.getParamter(phone)); %> </jsp:useBean>

<jsp:setProperty name=myBean property=email value=abc123@yahoo.co.in /> <jsp:setProperty name=myBean property=email value=<%=someMethodToGetEmail()%> /> <jsp:setProperty name=myBean property=* />

<jsp:getProperty name=myBean property=email />

<jsp:getProperty name=myBean property=email /> <jsp:setProperty name=myBean property=email param=emailaddress /> Property=*|property=propName|pr operty=propName value=propValue

Include type

Syntax

Done when

Included content

parsing

directive

<%@incl Compilati ude on time file=filen ame%>

Static

Parsed by container

action

<jsp:inclu Request Static or de processin dynamic page=fil g time ename/>

Not parsed but included in place

When the JSP page is requested, it sends a request to another object, and the object is included in the requested JSP page. We use <jsp:include> and <jsp:forward> The foll. Three constructs are equivalent:

<% RequestDispatcher rd=request.getRequestDispatcher(other.jsp); rd.include(request,response); %> <% PageContext.include(other.jsp); %> <jsp:include page=other.jsp flush=true /> <jsp:forward page=other.jsp />

<html><body><pre> In ParamTest1: First Name is:<%=request.getParameter(firstname)%> Last name:<%=request.getParameter(lastname) %> <jsp:include page=paramTest2.jsp > <jsp:param name=firstname value=mary /> </jsp:include> </pre></body></html> The file paramTest2.jsp

First name is <%=request.getParameter(firstname) %> Last name is <%=request.getParameter(lastname) %>


Looping through all the first names <% String first[]=request.getParameterValues(firstname); For(int i=0;i<first.length;i++) { Out.println(first[i]);}%>

Expression Language

EL in incorporated JSP2.0 specifications. The purpose of EL is to aid in producing scriptless JSP pages. Syntax overview ${expr} To escape the EL expr from JSP it is /${expr}

Package p1; import java.io.*; import java.sql.*; public class TrialBean implements Serializable { Private String driver; Private String connection; Private String statement; Private String recordset; Public TrialBean(){}

Public void setDriver(String driver) { this.driver=driver;} Public void getDriver() { Return driver; } Public void setConnection(String connection) { this.connection=connection;} Public void getConnection () { Return Connection; }

Public void setStatement(String statement) { this.statement=statement;} Public void getStatement() { Return statement; }

Public void setResultSet(String resultset) { this. resultset = resultset;} Public void getResultSet () { return resultSet; }}

<jsp:useBean id=trial scope=session class=p1.TrialBean/> <jsp:setProperty id=trial name=driver value=sun.jdbc.odbc.JdbcOdbcDriver/ >

Custom tags

Tag libraries are extension of Java Beans in JSP, Although they get and set attributes like JavaBeans,they do much more extra functionality

We can access this extra functionality with XML tags,that is why thy are called customs tags. To use custom tags, need the following -Tag handler -Tag handler descriptor -Deployment descriptor -taglib directive -Custom tags in JSP

JavaBeans provide rasy access to get/set methods, but tag libraries provide

<%@ taglib uri=/hello prefix=examples %> <html> <body>this is static output.<p /> <i><examples:hello></examples:hello> </i> This is static output again.</body></html>

Package ext; Import java.io.IOException; Import java.util.Date; Import javax.servlet.jsp.*; Import javax.servlet.tagext.*;
Public class HelloTag extends TagSupport{ /*This method will be called when JSP engine encounters the start of a tag implements by this class*/ Public int dostartTag() throws JspTagException{ Return EVAL_BODY_INCLUDE;} Public int doEndTag() throws JspTagException{ String dateString=new Date().toString(); Try{ pageContext.getOut().write(hello world.<br/>); pageContext.getOut().write(my name is +getClass().getName()+and it is+dateString+<p/>); }

Catch(IOException e){ Throw new JspTagException(fatal error:hello tag could not write to JSP out);

Return EVAL_PAGE; } }//class

<taglib> <tlibversion>1.0</tlibversion> <jspversion>1.1</jspversion> <shortname>examples</shortname> <tag> <name>hello</name> <tagclass>ext.HelloTag</tagclass> <bodycontent>JSP</bodycontent> <info>simple example></info> </tag></taglib>

webapps | ROOT__hello.jsp | |WEB-INF | |--web.xml | --classes __ext |HelloTag.class tlds/hello.tld

|---

<web-app> <taglib> <tag-uri>/hello<tag-uri> <taglib-location>/WEB-INF/tlds/hello.tld</tagliblocation></taglib></we-app>

You might also like