MELJUN_CORTES_JEDI Course Notes Web Programming Lesson4 Basic JSPs

download MELJUN_CORTES_JEDI Course Notes Web Programming Lesson4 Basic JSPs

of 25

Transcript of MELJUN_CORTES_JEDI Course Notes Web Programming Lesson4 Basic JSPs

  • 8/3/2019 MELJUN_CORTES_JEDI Course Notes Web Programming Lesson4 Basic JSPs

    1/25

    Basic JSPs

    Introduction

    In the previous chapter, we have learned how to produce dynamic content for our usersusing Java technology through the use of servlets. However, while Java developers cancreate sites with such dynamic content using only servlets, there are several disadvantagesto doing so.

    One, using only servlets to produce HTML content does not make for very maintainable orclean code. Strings to be used for HTML output can become very large spanning multiplelines and can easily become a maintenance nightmare.

    Second, using only servlets to produce HTML content assumes that the developer is familiarwith both Java & HTML. Especially in the case of large organizations, site designers are aseparate group from programmers. Having to train the designers to give them even a basicunderstanding of Java, or to have Java developers gain expertise in HTML site design can betime-consuming and/or expensive activities for an organization.

    This is where JSP technology comes in handy.

    Overview

    What is JSP?

    Java Server Pages (JSP) is a servlet-based technology used in the web tier to present bothdynamic and static content. It is text-based and contains mostly HTML template textintermixed with tags specifying dynamic content.

    Why JSP?

    Since JSPs are text documents much like HTML, developers avoid having to formatand manipulate a possibly very long String to produce output. The HTML content isnow not embedded within a lot of Java code. This makes it easier to maintain.

    JSPs are immediately familiar to anyone with knowledge of HTML, with only thedynamic markup to learn. This makes it possible for dedicated site designers tocreate the HTML template of the site, with developers processing it later to includethe tags producing dynamic content. This makes for ease of web page development.

    JSPs have built-in support for the use of reusable software components (JavaBeans).This not only lets developers avoid possibly reinventing the wheel for eachapplication, having support for separate software components to handle logicpromotes separation of presentation and business logic.

    JSPs, as part of Java's solution to web application development, are inherently multi-

  • 8/3/2019 MELJUN_CORTES_JEDI Course Notes Web Programming Lesson4 Basic JSPs

    2/25

    platform and can be run in any compatible servlet container, regardless of vendor oroperating system.

    Due to the way JSPs work, they do not need explicit compilation by the developer.This compilation is done for us by the servlet container. Modifications to JSPs are alsoautomatically detected and result in recompilation. This makes them relativelysimpler to develop.

    Sample JSP

    Welcome

    Greetings!

    Thank you for accessing our site.

    The time is now

    Figure 1: welcome.jsp

    Above is a simple JSP file that performs a generic greeting to the site's users as well asinforming them of the date and time current to user access.

    From the example above, we can see that the JSP file is mostly HTML in nature. The onlypart that stands out is this snippet:

    This is the piece of Java code responsible for displaying the current date and time. It doesso by simply creating a new instance of a Date object and displaying its String equivalent.

    Below is the output from this JSP file.

  • 8/3/2019 MELJUN_CORTES_JEDI Course Notes Web Programming Lesson4 Basic JSPs

    3/25

    Running the sample JSP

    . Using the IDE

    A JSP can be run from any web application project in the IDE. Assuming that a project

    already exists, simply place the JSP file within the Web Pages folder within the Project view.

    Figure 2: Output of welcome.jsp

  • 8/3/2019 MELJUN_CORTES_JEDI Course Notes Web Programming Lesson4 Basic JSPs

    4/25

    This specific JSP page can then be run from the IDE directly by pressing on Shift + F6.Alternatively, the web project can be packaged as a WAR file and uploaded into a server.The JSP can then be accessed by typing in the following URL:http://[host]:[port]/[WEB_PROJECT_NAME]/[JSP_NAME]

    . Using an Ant build file

    The JSP can also be run by packaging it into a WAR file using a build tool (such as the oneoutlined in the Basic Servlet chapter), and then deploying the WAR file into a web server.The directory structure is replicated below for recall:

    Figure 3

  • 8/3/2019 MELJUN_CORTES_JEDI Course Notes Web Programming Lesson4 Basic JSPs

    5/25

    Following the development directory structure discussed in the earlier chapter, our JSP fileshould be placed in the web directory.

    JSP Lifecycle

    The servlet container manages JSPs in a similar manner as it does servlets: through the useof a well-defined lifecycle.

    JSPs have a three-phase lifecycle: initialization, service, and destruction. These lifecycleevents are similar to that of servlets though the methods invoked by the container aredifferent: jspInit() for the initialization phase, _jspService() for the service phase, and

    jspDestroy() for the destruction phase.

    Given the sample JSP given above, it seems confusing to talk about jspInit or _jspService()methods. The sample JSP was just a simple text page with mostly HTML content : it had nomethods whatsoever. The answer to that is: JSPs are compiled into an equivalent servlet

    Figure 4: JSP 3-phase Lifecycle

  • 8/3/2019 MELJUN_CORTES_JEDI Course Notes Web Programming Lesson4 Basic JSPs

    6/25

    class by the server. It is this servlet class that handles all requests to the JSP page. Thistranslation into a servlet and subsequent compilation is done transparently by the server :the developer need not worry about how this procedure is done.

    If you wish to view the generated servlet class, installations of Sun Application Server 8.1places them in the following directory:

    ${SERVER_HOME}/domains/domain1/generated/jsp/j2ee-modules/${WEB_APP_NAME}/org/apache/jsp

    Below is the servlet equivalent of our JSP example.

  • 8/3/2019 MELJUN_CORTES_JEDI Course Notes Web Programming Lesson4 Basic JSPs

    7/25

    package org.apache.jsp;

    import javax.servlet.*;

    import javax.servlet.http.*;import javax.servlet.jsp.*;

    public final class index_jsp extends org.apache.jasper.runtime.HttpJspBaseimplements org.apache.jasper.runtime.JspSourceDependent {

    private static java.util.Vector _jspx_dependants;

    public java.util.List getDependants() {return _jspx_dependants;}

    public void _jspService(HttpServletRequest request, HttpServletResponse response)throws java.io.IOException, ServletException {

    JspFactory _jspxFactory = null;PageContext pageContext = null;HttpSession session = null;ServletContext application = null;ServletConfig config = null;JspWriter out = null;Object page = this;JspWriter _jspx_out = null;PageContext _jspx_page_context = null;

    try { _jspxFactory = JspFactory.getDefaultFactory();response.setContentType("text/html");response.addHeader("X-Powered-By", "JSP/2.0");pageContext = _jspxFactory.getPageContext(this, request, response,null, true, 8192, true);

    _jspx_page_context = pageContext;application = pageContext.getServletContext();config = pageContext.getServletConfig();session = pageContext.getSession();out = pageContext.getOut();

    _jspx_out = out;

    out.write("\n");out.write("\n");out.write(" Welcome\n");

  • 8/3/2019 MELJUN_CORTES_JEDI Course Notes Web Programming Lesson4 Basic JSPs

    8/25

    out.write("\n");out.write(" \n");out.write(" Greetings!
    \n");

    out.write("\n");out.write(" Thank you for accessing our site.
    \n");out.write("\n");out.write(" The time is now ");out.print( new java.util.Date());out.write("\n");out.write("\n");out.write(" \n");out.write("\n");out.write("");} catch (Throwable t) {if (!(t instanceof SkipPageException)){out = _jspx_out;if (out != null && out.getBufferSize() != 0)out.clearBuffer();if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);}} finally {if (_jspxFactory != null) _jspxFactory.releasePageContext(_jspx_page_context);}}}

    It is not important to understand the code above. What is important here is to see that JSPsare handled just like Servlets, even if it is not immediately obvious. Another point here isthat JSPs ARE servlets. They only differ in the way they allow a developer to producecontent : JSPs are more text-oriented, while servlets allow the developer greater freedomwith Java code.

    JSP Syntax and Semantics

    Although JSP is Java-based, and is handled as Java code by the servlet, the syntax it allowsdevelopers to use is different from that in the Java 2.0 specification and instead follow rulesdefined in the JSP specification. The following section describes JSP syntax in more detail

    Elements and Template Data

    Components of all JavaServer Pages can be qualified into two general categories: elementsand template data . Elements are dynamically produced information. Template data arestatic information that takes care of presentation. In hello.jsp, the JSP expression, is the only element data the rest are template data.

  • 8/3/2019 MELJUN_CORTES_JEDI Course Notes Web Programming Lesson4 Basic JSPs

    9/25

    Listing 1: hello.jsp

    Hello World!Hello World! It's

    Two Types of Syntax

    Two styles of authoring JSP are supported by JSP containers: the JSP Style and the XMLStyle. Both are presented in this text. Choosing one syntax format over the other is just amatter of preference and standardization. The normal syntax is designed to be easier toauthor. The XML-compatible syntax is just the normal syntax modified to become XML-compliant. The XML-compatible syntax is preferred when using JSP authoring tools.However, most prefer the normal syntax because it is easier to read and understood. Thistext will be using the normal syntax in its examples.

    Scripting Elements

    As mentioned in the previous lesson, JSPs may be viewed as HTML or XML documents withembedded JSP scripts. JSP scripting elements allow you insert Java code into the Servletthat will be generated from the JSP page.

    The simplest way to make a JSP dynamic is by directly embedding scripting elements intotemplate data.

    In this lesson you will be learning the following JSP scripting elements:1. Scriptlets,2. Expressions, and3. Declarations.

    . Scriptlets Scriptlets provide a way to directly insert bits of Java code in between chunks of template

    data and has the following form:

    Defining Java code in between is just the same as writing normal Java codeexcept that there is no need for a class declaration. Scriptlets are useful for embeddingsimple java codes like conditional statements loops, etc. There is no specific limit as to the

  • 8/3/2019 MELJUN_CORTES_JEDI Course Notes Web Programming Lesson4 Basic JSPs

    10/25

    complexity of Java codes to be placed in between scriptlets. However, we should take greatprecaution in overusing scriptlets. Putting too heavy computation inside scriptlets is a codemaintainability issue. Also, using scriptlets extensively violates JSPs role of being primarily apresentation layer component.

    We will be discussing later how we can make use of JavaBeans to encapsulate data resultspassed from another component, drastically reducing the amount of scriptlets necessary ina page. Even later on, we will be discussing how to use custom tags to provide commontasks such as looping, logic branching, etc. This combined with JavaBeans usage will cutscriptlet usage down to nearly 0.

    If you want to use the characters "%>" inside a scriptlet, write "%\>" instead. This willprevent the compiler from interpreting the characters as the closing scriptlet tag.

    Below are two examples defining very simple Java codes in between HTML tags.

    Example: Simple Println

    Figure 5: PrintlnScriplet.jsp

    The example above is a simple illustration embedding Java code into your JSP. The codeabove outputs the text, jedi, into the web browser.

    Example: For-Loop in a scriptlet

    Figure 6: LoopScriplet.jsp

  • 8/3/2019 MELJUN_CORTES_JEDI Course Notes Web Programming Lesson4 Basic JSPs

    11/25

    The example above shows the Java code implementation of the for-loop enclosed inside thescriptlet tag ().

    The output you get in the browser after running this JSP should be the text This line isprinted 10 times. printed 10 times due to the for-loop running from iteration 0 through 9as shown below.

    Take note that the scriptlet itself is not sent to the client but only its output. Try viewing thesource of the jsp output you've produced in your browser to understand this point. All youshould see are HTML tags plus the scriptlet output but minus the scriptlet.

    Finally, the XML-compatible syntax for writing scriptlets is:

    Java code;.

    . Expressions

    Expressions provide a way to insert Java values directly into the output. It has the followingform:

    Figure 7: Output of LoopScriplet.jsp

  • 8/3/2019 MELJUN_CORTES_JEDI Course Notes Web Programming Lesson4 Basic JSPs

    12/25

    It is actually short for out.println().

    Notice that a semicolon ( ; ) does not appear at the end of the code inside the tag.

    Any Java expression placed in between is evaluated at run-time, converted toa string, and inserted in the page. The expression always sends a string of text to the client,but the object produced as a result of the expression does not necessarily have to end up asan instance of a String object. All non-String object instances are converted to stringsthrough their inherent toString() member methods. If the result is a primitive, then theprimitive's string representation is displayed.

    It was mentioned earlier that evaluation is performed at run-time (when the page isrequested), this gives expressions full access to information about the request.

    A number of predefined variables have actually been made available to JSP authors tosimplify expressions. These predefined variables are called implicit objects and arediscussed in more detail later. For the purpose of expressions, the most important ones are:

    request, the HttpServletRequest; response, the HttpServletResponse; session, the HttpSession associated with the request (if any); and out, the PrintWriter (a buffered version of type JspWriter) used to send output to the

    client. For example, to print the hostname, you just need to include the simple jsp expressionshown below:

    Hostname:

    Finally, the XML-compatible syntax for is:

    Java Expression

    . Declarations

    Declarations allow you to define methods or variables. It has the following form:

    Declarations are used to embed code just like scriptlets but declarations get inserted intothe main body of the servlet class, outside of the _jspService() method processing therequest. For this reason code embedded in a declaration can be used to declare newmethods and global class variables. On the other hand, code in declarations are not thread-safe, unless explicitly programmed by the JSP author therefore, caution must be taken

  • 8/3/2019 MELJUN_CORTES_JEDI Course Notes Web Programming Lesson4 Basic JSPs

    13/25

    when writing JSP declarations.

    Following are a few simple reminders in using the declaration tag: Before the declaration you must have Code placed in this tag must end in a semicolon ( ; ). Declarations do not generate output but are used with JSP expressions or scriptlets.

    Since declarations do not generate any output, they are normally used in conjunction withJSP expressions or scriptlets. For example, here is a JSP that prints out the number of timesthe current page has been requested since the server booted (or the servlet class waschanged and reloaded):

    Example

    The JSP is able to print out the number of visits by declaring a class-wide variableaccessCount, using a scriptlet to increment the value of the number of page visits and anexpression to display the value.

    The illustration below displays a sample output of this JSP page refreshed 4 times.

    Figure 8: AccessCountDeclaration.jsp

  • 8/3/2019 MELJUN_CORTES_JEDI Course Notes Web Programming Lesson4 Basic JSPs

    14/25

    For us to appreciate better how a JSP page is translated into a Servlet let us examine theServlet output of our JSP container for the AccessCountDeclaration.jsp. My JSP containergenerated a Java file called AccessCountDeclaration_jsp.java and the contents follow. Notethat the declaration, the scriptlet and the expression have been highlighted for easierreference.

    Listing 2: AccessCountDeclaration_jsp.java

    package org.apache.jsp.JSP;

    import javax.servlet.*;import javax.servlet.http.*;import javax.servlet.jsp.*;

    public final class AccessCountDeclaration_jspextends org.apache.jasper.runtime.HttpJspBaseimplements org.apache.jasper.runtime.JspSourceDependent {

    private int accessCount = 0;

    private static java.util.Vector _jspx_dependants;

    public java.util.List getDependants() {return _jspx_dependants;}

    public void _jspService (

    Figure 9: Output of AccessCountDeclaration.jsp

  • 8/3/2019 MELJUN_CORTES_JEDI Course Notes Web Programming Lesson4 Basic JSPs

    15/25

    HttpServletRequest request, HttpServletResponse response)throws java.io.IOException, ServletException {

    JspFactory _jspxFactory = null;PageContext pageContext = null;HttpSession session = null;ServletContext application = null;ServletConfig config = null;JspWriter out = null;Object page = this;JspWriter _jspx_out = null;PageContext _jspx_page_context = null;

    try {

    _jspxFactory = JspFactory.getDefaultFactory();

    response.setContentType("text/html");pageContext = _jspxFactory.getPageContext(this, request, response, null, true,8192, true);

    _jspx_page_context = pageContext;application = pageContext.getServletContext();config = pageContext.getServletConfig();session = pageContext.getSession();

    out = pageContext.getOut(); _jspx_out = out;out.write("\n");out.write("\n");out.write("\n");out.write("\n");out.write("Declaration Example\n");out.write("\n");out.write("\n");accessCount++;out.write("Accesses to page since server reboot: \n");out.print( accessCount );out.write("\n");out.write("\n");out.write("\n");out.write("\n");

    out.write("\n");

    } catch (Throwable t) {

    if (!(t instanceof SkipPageException)){out = _jspx_out;if (out != null && out.getBufferSize() != 0)

  • 8/3/2019 MELJUN_CORTES_JEDI Course Notes Web Programming Lesson4 Basic JSPs

    16/25

    out.clearBuffer();

    if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);

    }

    } finally {

    if (_jspxFactory != null) _jspxFactory.releasePageContext(_jspx_page_context);

    }

    }

    }

    Notice how the declaration for accessCount is placed outside of the _jspservice() method asa member variable. This makes accessCount available not only for the _jspservice() methodbut for any other method defined in the JSP. Examining the preceding code has shown usthe actual placement of declarations, scriptlets and expressions in a Java source codetranslated from a JSP page.

    Finally, note that the XML-compatible syntax for is

    Java Code;

    . Template Text

    Use

  • 8/3/2019 MELJUN_CORTES_JEDI Course Notes Web Programming Lesson4 Basic JSPs

    17/25

    request of the client..

    response : The instance of the javax.servlet.http.HttpServletResponse object associatedwith response to the client.

    pageContext : the PageContext object associated with current page.

    out : References the javax.servlet.jsp.JspWriter object which can be used to write actionsand template data in a JSP page, similar to that of the PrintWriter object we used in theservlet discussion. The implicit variable out is initialized automatically using methods in thePageContext object.

    session : An instance of a javax.servlet.http.HttpSession object. It is equivalent to callingthe HttpServletRequest.getSession() method.

    application : The ServletContext is an instance of the javax.servlet.ServletContext object.

    It is equivalent to calling getServletConfig().getContext() method. This implicit object isshared by all servlets and JSP pages on the server.

    config : The config implicit object is an instance of the javax.servlet.ServletConfig object forthis page. Same as Servlets, JSPs have access to the parameters initially defined in the WebApplication Deployment Descriptor.

    JSP Directives

    Directives are messages to a JSP container. They affect the overall structure of the servletclass. It usually has the following form:

    A list of attribute settings can also be enumerated for a single directive as follows:

    Note : Whitespaces after are optional.

    Directives do not produce any visible output when the page is requested but theychange the way the JSP Engine processes the page. For example, you can make sessiondata unavailable to a page by setting a page directive (session) to false.

    A JSP directive gives special information about the page to the JSP Engine. directive can beone of page, include or taglib. Each of these directives has its own set of attributes.

    . Page directive

  • 8/3/2019 MELJUN_CORTES_JEDI Course Notes Web Programming Lesson4 Basic JSPs

    18/25

    The page directive defines the processing information for this page. It allows you to importclasses, customize the servlet superclass, and the like;Directives have the following optional attributes that provide the JSP Engine with specialprocessing information. Note that these are case-sensitive attributes:

    Directive Description Sample Usage

    extends Superclass used by the JSPengine for the translatedServlet. Analogous to theextends keyword in the Javaprogramming language.

    language Indicates which scriptinglanguage the scriptlets,expressions and declarationsfound in the JSP page uses.The only defined value forthis attribute is java.

    import Import the classes in a javapackage into the current JSPpage.

    Session Indicates whether the pagemakes use of sessions. Bydefault all JSP pages havesession data available.Switching session to false has

    performance benefits.

    Default is set to true.

    buffer Controls the use of bufferedoutput for a JSP page. If values is none, then there isno buffering and output iswritten directly to theappropriate PrintWriter.Default value of buffer is 8kb.

    autoFlush When set to true, flushes theoutput buffer when it is full.

    isThreadSafe Indicates if the generatedServlet deals with multiplerequests. If true, a newthread is started to handlerequests simultaneously.Default value is true.

  • 8/3/2019 MELJUN_CORTES_JEDI Course Notes Web Programming Lesson4 Basic JSPs

    19/25

    Directive Description Sample Usage

    info Developer uses info attributetoadd information/document forapage. Typically used to addauthor, version, copyright anddate info.

    errorPage Defines the page that dealswitherrors. Must be URL to errorpage.

    IsErrorPage A flag that is set to true tomake a JSP page a special

    Error Page.This page has access to theimplicit object exception

    The XML syntax for defining directives isFor example, the XML equivalent of is

    . Include directive

    The include directive defines the files to be included in the page. It lets you insert a file intothe servlet class ( to include contents of a file inside another) during translation time .Typically, include files are used for navigation, tables, headers and footers, etc. -components that are common to multiple pages.

    The include directive follows the syntax:

    For example, if you want to include a menubar found in the current directory, you wouldwrite:

    . Tag Lib directive

    A tag library is a collection of custom tags. The taglib directive defines the tag library to beused in this page. Taglibs are written this way:

  • 8/3/2019 MELJUN_CORTES_JEDI Course Notes Web Programming Lesson4 Basic JSPs

    20/25

    This directive tells the container which markup in the page should be considered customcode and what code the markup links to. Take the example of index.jsp in the followinglisting. The first line declares that index.jsp uses the "struts/template" custom code and isprefixed "template" for easier typing. The succeeding lines references the taglib by properlyprefixing the markup.

    index.jsp

    Custom tags were introduced in JSP 1.1 and allow JSP developers to hide complexserver side code from web designers.

    JavaBeans in JSP

    The use of JavaBeans are not mandated in the JSP specification. However, they provideuseful functionality in that usage of JavaBeans can greatly reduce the amount of scriptingelements to be found in a Java page.

    First of all, a refresher course on JavaBeans: JavaBeans are just simple Java classesadhering to a certain coding standard:

    provides a default, no-argument constructor provides get and set methods for properties it wishes to expose

    A sample of a simple JavaBean can be found below:

  • 8/3/2019 MELJUN_CORTES_JEDI Course Notes Web Programming Lesson4 Basic JSPs

    21/25

    package jedi.beans;

    public class User {

    private String name;private String address;private String contactNo;

    public User() {}

    public String getName() {return name;}

    public void setName(String name) {this.name = name;}

    public String getAddress() {return address;}

    public void setAddress(String address) {this.address = address;}

    public String getContactNo() {return contactNo;

    }public void setContactNo(String contactNo) {this.contactNo = contactNo;}}

    . How are JavaBeans used in a JSP?

    As a Data Transfer Object - JavaBeans are more widely used in JSPs as objects thattransfer data from another source. In most applications, actual processing is done ina servlet, not in a JSP. Only the results of the passing are passed on to the JSP in theform of one or more JavaBeans.

    As a Helper object In some small applications, it is not efficient to have a separateservlet to process the data. In this case, it is better to place the functionality insideJavaBeans which can be accessed by the JSP.

    . JavaBeans-related JSP Actions

  • 8/3/2019 MELJUN_CORTES_JEDI Course Notes Web Programming Lesson4 Basic JSPs

    22/25

    JSP defines standard actions that simplify the usage of JavaBeans.

    To use a JavaBeans component, the first thing to do is to enable the use of a bean withinthe page through instantiation, which we can do with this action.

    The attributes of the action are as follows:

    id - This attribute specifies the name of the bean and how you will refer to it in thepage.

    scope - This attribute specifies the scope in which you want to store the beaninstance. It can be set to page (the default), session, request, or application.

    class - This attribute specifies the Java class that the bean is drawn from. If youhave specified beanName, you do not have to specify class.

    beanName - This attribute specifies the name of a bean that is stored on the server.

    You refer to it as you would a class (for example, com.projectalpha.PowerBean). If you have specified class, you do not need to specify beanName.

    type -This attribute specifies the type of scripting variable returned by the bean. Thetype must relate to the class of the bean

    The following is a sample of how to use the User JavaBean in a JSP page:

    When the page encounters a useBean action, it first tries to see if there is already aJavaBean instance of the given type located in the given scope. If there is, the page willmake use of that bean instance. If not, the container will automatically create a new bean

    instance using the bean's default no-argument constructor and place that bean in the givenscope.

    If the above functionality were to be expressed as a scriptlet, it would look like this:

    Once a bean has been enabled using the jsp:useBean action, it can be used inside the JSPpage like any other object instance using the name specified in the id attribute. An exampleof this is provided below:

  • 8/3/2019 MELJUN_CORTES_JEDI Course Notes Web Programming Lesson4 Basic JSPs

    23/25

    Hello !!

    This action retrieves the value of a property inside a specified JavaBean and outputs itimmediately to the response stream.

    This action has two attributes:

    name the name of the JavaBean whose property is to be retrieved. This must havethe same value as the id attribute used in an earlier action

    property the name of the property whose value will be retrieved.

    If the developer wishes to be able to retrieve the value of a JavaBean property withoutimmediately placing it in the output stream, there is no choice but to make use of scriptletsor EL (to be discussed in a future chapter).

    Continuing with our examples above, to display the name property of the User JavaBean,we make use of the getProperty action like this :

    This action allows developers to set the properties of a given JavaBean without thedeveloper having to write a line of scriptlet code.

    This action has the same attributes with the getProperty action, with the addition of twomore:

    value the value to be set into the property. This can be either a static value or anexpression that can be evaluated at runtime.

    param specifies the request parameter from which the property will retrieve itsvalue. Placing * as the param value

    Developers making use of this action must specify one of either value or param attribute.Including both in the action will cause an exception to be thrown.

    Error Handling

    JSPs can make use of the page directive to specify a page that will handle any uncaughtexceptions. The errorPage attribute of the page directive can be passed a relative URL tothe JSP page designated as an error page. The page thus designated can set the isErrorPage

  • 8/3/2019 MELJUN_CORTES_JEDI Course Notes Web Programming Lesson4 Basic JSPs

    24/25

    attribute to true. Doing so will give them access to an implicit object named exception thiscontains details about the exception thrown.

    An example of this is provided below. The first listing shows a JSP page using the pagedirective to describe an error page that will be used for unhandled exceptions.

    // call a method on the null object, so that an exception will be thrown and the errorpage calledThe length of the string is

    In the designated error page, the isErrorPage page directive must be set to true. Notice howthe page is able to use an exception object to retrieve the error message generated fromthe calling page.

    < %@page isErrorPage="true"%> Error!An Error has occurred.
    Sorry, but an error has occurred with the page you were previously accessing. Pleasecontact any member of the support team, and inform them that was the cause of the error

    EXERCISE1) Consider the following class :

    public class Recipe {private String recipeName;private String[] ingredients;private int cookTime;

    // getter and setter methods here}

    Given a scenario where an instance of this class has been stored in request scope underthe key "currentRecipe", create a JSP page that will perform the following :

    mailto:%25@pagemailto:%25@page
  • 8/3/2019 MELJUN_CORTES_JEDI Course Notes Web Programming Lesson4 Basic JSPs

    25/25

    a) Retrieve the Recipe instance using JSP actions.b) Display the details contained in the instance. This includes displaying each element in

    the ingredient list. The details should be displayed using JSP actions as well.

    2) Given the same class and scenario as above, create another page displaying the samedetails. This time, make use of the available implicit objects to retrieve the Recipe objectinstance, and use expressions to display the details.

    3) Given the same Recipe object class definition, perform the following tasks :a) create a JSP page that will create an instance using JSP actions.b) Set the recipeName property to have a value of "Monte Carlo Sandwich" and cookTime

    to 0. Set these properties using JSP actions as well.c) Display the values of the object instance.

    4) A JSP file named otherContent.jsp is located in the document root. It is defined asfollows :

    This is very important content

    Inclusion successful!

    Create a JSP file that will include the content defined in otherContent.jsp.