jsp element types

Upload: deepu39

Post on 14-Apr-2018

220 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/29/2019 JSP Element Types

    1/59

    JSP element types

    Just like any other scripting lang tags,JSP also has got its well defined tags for

    performing various tasks like declaringvars,methods,exprs,and calling other jsp

    pages.

  • 7/29/2019 JSP Element Types

    2/59

    JSP element typesJSP tag type description syntax

    Directives Specifies translation timeinstructions to the JSPengine.

    Declaration Declares and definesmethods and vars

    Scriptlet Allows the developer towrite free-form java codein a jsp page

    Expression Used as a shortcut to printvalues in the output HTML

    of a JSP page

    Action Provides request-timeinstructions to the JSPengine

    Comment Used for commenting jsp

    code

  • 7/29/2019 JSP Element Types

    3/59

    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 thatwe will be using Java as the scripting lang in our JSP page.

    An include directive tells the JSP engine to include the contents ofanother file(HTML,JSP,etc.) int the current page. Here is an example ofan include directive:

    A taglib directive is used for associating a prefix with a tag library. Thefoll. Is an ex. Of a taglib directive:

  • 7/29/2019 JSP Element Types

    4/59

    < page a r- s >

    The tag names, their attributes and

    their values are all case sensitive

    The value must be enclosed within apair 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.

  • 7/29/2019 JSP Element Types

    5/59

    DeclarationsDeclarations declare and define vars and methods that can be used

    in the JSP page.

    The var is only intialized only once to 0.

    When page is first loaded by JSP engine, and it retains its value insubsequent client requests.

  • 7/29/2019 JSP Element Types

    6/59

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

    The scriptlet is executed each time it gets executed.

    The scriptlet gets excuted each time the page is accessed, andthe count variable is incremented with each request.

  • 7/29/2019 JSP Element Types

    7/59

    ExpressionsExpressions act as placeholders for javaExpressions.

    Eg.

    Never to have a semicolon at the end ofexprn.

    welcome! U r visitor number

    JSP i i

  • 7/29/2019 JSP Element Types

    8/59

    JSP i e cyc e trans ationPhase Name Description

    Page translation The page is parsed and a Java file

    containing the corresponding servletis created

    Page compilation The java file is compiled

    Load class The compiled class is loaded

    Create instance An instance of servlet is created

    Call jspInit() This method is called before anyother method to allow initilization

    Call _jspService() This method is called for eachrequest

    Call jspDestroy() This method is called when servletcontainer decides to take servlet outof service.

  • 7/29/2019 JSP Element Types

    9/59

    Calling life cycle methods The generated servlet class for a jsp page

    implements HttpJspPage interface, which isin javax.servlet.jsp pkg.

    The HttpJspPage extends JSP pageinterface of the same pkg, which in turn

    extends Servlet interface of thejavax.servlet pkg.

    The generated servlet class thusimplements all three interfaces and also

    known as pages implementation class.

  • 7/29/2019 JSP Element Types

    10/59

    The JspPage interface has two methods

    jspInit() and jspDestroy()-that must be implemented by all jsp pagesregardless 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 asconcrete subclass of three interfaces.

  • 7/29/2019 JSP Element Types

    11/59

    Jspinit()

    The container calls this method to initialize the servlet instance. We normallydefine this method for one time setup such as acquiring resources andinitializing the instance variables that been declared using

    declarations

    Jspdestroy()

    When the container decides to take out instance out of service,it callsjspDestroy(). This is last method called on servlet instance, and it is used toclean up the resources acquired in jspInit().

    We are not req to implement jspInit() and jspDestroy(),bcoz implemented bybase class but if wants to override these two methods, then can be done

    But cannot define _jspService() bcoz generated by engine automatically.

  • 7/29/2019 JSP Element Types

    12/59

    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 shutdown and restrated.

    Use jspInit() to load the previous value of thecounter from a file when server starts.

    Use jspdestroy() to save the final to the filewhen the server shuts down.

  • 7/29/2019 JSP Element Types

    13/59

  • 7/29/2019 JSP Element Types

    14/59

    Welcome !you r visitor number

  • 7/29/2019 JSP Element Types

    15/59

    Page Directive AttributesA page directive informs the JSp engine about overall properties of aJSp page. This directive applies to the translation unit. There 12attributes for page directive

    Attr Name Description Default values

    import A comma-sepratedlist of java classesand pkgs that we

    want to use in theJSP page

    Java.lang.*;

    Javax.servlet.*;

    Javax.servlet.jsp.*;Javax.servlet.http.*;

    session A boolean literal ,whether the jsppage takes part inan Http session.

    true

    errorPage Specifies relativeURL to another JSPpage that iscapable of handlingerrors on the behalfof current page

    null

    i E P A b l lit l if i f l

  • 7/29/2019 JSP Element Types

    16/59

    isErrorPage A bolean literal specifyingwhether the current JSPpage is capable ofhandling errors

    false

    language Any scripting languagesupported by the JSPengine

    java

    extends Any valid java class thatimplementsjavax.servlet.jsp.JspPage

    Implementationdependent

    buffer Specifies the size of

    output buffer.If buffersize is specified, its inkilobytes.

    Implementation

    dependent

  • 7/29/2019 JSP Element Types

    17/59

    autoflush An boolean literalindiacting whetherthe buffer should be

    flushed when it is full

    true

    Info Any informative textabout jsp page

    Impl. dependent

    contentType Character encoding

    for the output

    Text/html;charset=

    ISO-8859-1

    pageEncoding Specifies thecharacter encodingof the JspPage

    ISO-8859-1

  • 7/29/2019 JSP Element Types

    18/59

  • 7/29/2019 JSP Element Types

    19/59

    Hello,

  • 7/29/2019 JSP Element Types

    20/59

    errorHandler.jsp

    Unable to process yourrequest:,

  • 7/29/2019 JSP Element Types

    21/59

  • 7/29/2019 JSP Element Types

    22/59

  • 7/29/2019 JSP Element Types

    23/59

    Implicit Variables and implicit objects

    Durning translation phase, the Jsp engine

    declares and intializes nine commonly usedvariables in the _jspservice() method.

    Identifier name Class or interface description

    application Interfacejavax.servlet.ServletContext

    Refers to the webapplications environment

    session Interface

    Javax.servlet.http.HttpSession

    Refers to the users session

    request Interface

    Javax.servlet.http.HttpservletRequest

    Refers to the currentrequests to the page

    response Interface

    Javax.servlet.http.HttpservletResponse

    Used for sending a responseto the client

    out Classjavax.servlet.jsp.Jspwriter

    Refers to the output streamfor the page

  • 7/29/2019 JSP Element Types

    24/59

    page classjava.lang.Object

    Refers to thepages servletinstance

    pageContext classjavax.servlet.jsp.PageContext

    Refers to thepagesenvironment

    config Interfacejavax.servlet.ServletConfig

    Refers to theservletsconfiguration

    exception Classjava.lang.Throwa

    ble

    Used for errorhandling

  • 7/29/2019 JSP Element Types

    25/59

    Because the page author does notdeclare these variables explicitly,they

    are called implicit variables. The objs are to be created by servlet

    container and are called implicit objects.

  • 7/29/2019 JSP Element Types

    26/59

    Application

    The application var. is of the type

    javax.servlet.servletContext and it refers tothe env of the web application to which the

    jsp belongs.

  • 7/29/2019 JSP Element Types

    27/59

    Session

    Session implicit var, lets clarify that the word session refers to four diff. butrelated things in JSP:

    Session, as in a HTTP session,is a concept that logically groups multiple reqsfrom the same client as part of one conversation.

    Session, as used in a page directive,refers to the attribute named session.

    Its value, which is true or false, determines whether or not the JSP pageparticipates 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.

  • 7/29/2019 JSP Element Types

    28/59

    Session ID=

  • 7/29/2019 JSP Element Types

    29/59

    Request and Response

    The request and response implicit vars are of typejavax.servlet.http.HttpServletRequest andjavax.servlet.http.HttpServletResponse, respectively.

    HI! Your IP address is

  • 7/29/2019 JSP Element Types

    30/59

    Login.jsp

    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;%>

  • 7/29/2019 JSP Element Types

    31/59

    page

    The implicit variable page is classjava.lang.Object and it refers to the

    instance of the generated servlet. It is declared as Object page=this;

    pageConte t

  • 7/29/2019 JSP Element Types

    32/59

    pageContext

    The pageContext var is of type javax.jsp.PageContext. ThepageContext class is an abstarct class, and the JSP engine vendorprovides its concrete subclass.

    Stores reference to the implicit objs. The session,application,configand out implicit vars are intialized using the objs retrieved frompageContext.

    Provides convenient methods for transferring requests to otherresources.

    pageContext.forward(other.jsp);

  • 7/29/2019 JSP Element Types

    33/59

    Unrecognized attr result infatal translationerrors.

    This is to test the page directive.

  • 7/29/2019 JSP Element Types

    34/59

    Include directive test page

  • 7/29/2019 JSP Element Types

    35/59

    Included.jsp

  • 7/29/2019 JSP Element Types

    36/59

    Scopes of JSP page

    Scope Name Existence andAccessibility

    Application Limited to a single webapplication

    Session Limited to a single usersession

    Request Limited to a single

    request

    Page Limited to single pageand a single request

  • 7/29/2019 JSP Element Types

    37/59

    Action tags

    The standard JSP actions

    jsp:include

    jsp:forward

    jsp:useBean

    jsp:setPropertyjsp:getProperty

  • 7/29/2019 JSP Element Types

    38/59

    JavaBeans Components

    A Javabeancomponent is Java tech.class with min. following features

    Properties defined with accessors andmutators.

    No args constructor

    No public instance vars The class implements thejava.io.Serializable interface.

  • 7/29/2019 JSP Element Types

    39/59

    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;}

  • 7/29/2019 JSP Element Types

    40/59

    Public String getEmail()

    {

    return email;}

    Public void setPhone(string phone)

    {

    this.phone=phone;}

    Public String getPhone(){

    Return phone;}

    }

  • 7/29/2019 JSP Element Types

    41/59

    If u want to interact with a JavaBeanscomponents using std tags in a JSP

    page. U must first declare the bean.The action tag usebean syntax

  • 7/29/2019 JSP Element Types

    42/59

    mailto:[email protected]:[email protected]
  • 7/29/2019 JSP Element Types

    43/59

    Property=*|property=propName|property=propName

    value=propValue

    I l d S D I l d d i

  • 7/29/2019 JSP Element Types

    44/59

    Include

    type

    Syntax Donewhen

    Includedcontent

    parsing

    directive

    Compilation time

    Static Parsed bycontainer

    action

    Requestprocessing time

    Static ordynamic Notparsedbutincludedin place

  • 7/29/2019 JSP Element Types

    45/59

    When the JSP page is requested, itsends a request to another object, and

    the object is included in the requestedJSP page. We use and

    The foll. Three constructs areequivalent:

  • 7/29/2019 JSP Element Types

    46/59

  • 7/29/2019 JSP Element Types

    47/59

    In ParamTest1:

    First Name is:

    Last name:

    The file paramTest2.jsp

    First name is

    Last name is

    Looping through all the first names

  • 7/29/2019 JSP Element Types

    48/59

    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;

  • 7/29/2019 JSP Element Types

    49/59

    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(){}

  • 7/29/2019 JSP Element Types

    50/59

    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;

    }

  • 7/29/2019 JSP Element Types

    51/59

    Public void setResultSet(String resultset)

    {

    this. resultset = resultset;}

    Public void getResultSet ()

    {

    return resultSet;

    }}

  • 7/29/2019 JSP Element Types

    52/59

    Custom tags

  • 7/29/2019 JSP Element Types

    53/59

    Custom tags

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

    We can access this extra functionality with XML tags,that is why thy arecalled 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

  • 7/29/2019 JSP Element Types

    54/59

    this is static output.

    This is static outputagain.

  • 7/29/2019 JSP Element Types

    55/59

    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.
    );

    pageContext.getOut().write(my name is +getClass().getName()+and itis+dateString+

    );

    }

  • 7/29/2019 JSP Element Types

    56/59

    Catch(IOException e){

    Throw new JspTagException(fatal error:hello tag could not write to JSPout);

    Return EVAL_PAGE;

    }

    }//class

    1 0

  • 7/29/2019 JSP Element Types

    57/59

    1.0

    1.1

    examples

    hello

    ext.HelloTag

    JSP

    simple example>

  • 7/29/2019 JSP Element Types

    58/59

    webapps

    |

    ROOT__hello.jsp

    |

    |WEB-INF

    |

    |--web.xml

    | --classes

    __ext

    |HelloTag.class|--- tlds/hello.tld

  • 7/29/2019 JSP Element Types

    59/59

    /hello

    /WEB-INF/tlds/hello.tld