MELJUN CORTES Jedi course notes web programming-lesson4-basic js-ps
Upcoming SlideShare
Loading in...5
×
 

MELJUN CORTES Jedi course notes web programming-lesson4-basic js-ps

on

  • 760 views

MELJUN CORTES Jedi course notes web programming-lesson4-basic js-ps

MELJUN CORTES Jedi course notes web programming-lesson4-basic js-ps

Statistics

Views

Total Views
760
Views on SlideShare
760
Embed Views
0

Actions

Likes
0
Downloads
7
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as OpenOffice

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    MELJUN CORTES Jedi course notes web programming-lesson4-basic js-ps MELJUN CORTES Jedi course notes web programming-lesson4-basic js-ps Document Transcript

    • Basic JSPs IntroductionIn 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 disadvantagesin doing so.First, 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 areseparate groups 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, canbe time-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 like HTML, developers avoid having to format and manipulate a possibly very long String to produce output. The HTML content is now not embedded within a lot of Java code. This makes it easier to maintain. • JSPs are immediately familiar to anyone with knowledge of HTML, because they only have dynamic markup to learn. This makes it possible for dedicated site designers to create the HTML template of the site, with developers processing it later to include the 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). These not only let developers avoid possible reinvention of the wheel for each application. Having support for separate software components to handle logic promotes separation of presentation and business logic as well. • JSPs, as part of Javas solution to web application development, are inherently multi-
    • platform and can be run in any compatible servlet container, regardless of vendor or operating 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 also automatically detected and result in recompilation. This makes them relatively simpler to develop. Sample JSP<HTML><TITLE>Welcome</TITLE><BODY><H1> Greetings!</H1> <br>Thank you for accessing our site. <br>The time is now <%= new java.util.Date()%></BODY></HTML> Figure 1: welcome.jspAbove is a simple JSP file that performs a generic greeting to the sites users as well asinforms the current date and time 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: <%= new java.util.Date()%>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 the previous JSP file.
    • Figure 2: Output of welcome.jsp Running the sample JSP . Using the IDEA JSP can be run from any web application project in the IDE. Assuming that a projectalready exists, simply place the JSP file within the Web Pages folder within the Project view.
    • Figure 3: Running JSP from a Web Application ProjectThis specific JSP page can then be directly run from the IDE 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 fileThe 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:
    • After build script has executed, will contain the application in a directory structure recognized by servlet containers. After build script has executed, will contain the WAR file. Used to contain whatever documentation is used by the dev team. Directory under which all Java source files must be placed. Directory containing all static content of the app (HTML, JSP), will be the basis of the document root of your project. Directory containing configuration files such as the deployment descriptor (web.xml), tag library descriptors, etc.Following the development directory structure discussed in the earlier chapter, our JSP fileshould be placed in the web directory. JSP LifecycleThe servlet container manages JSPs in a similar manner as it does with servlets. This isthrough the use of 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, andjspDestroy() for the destruction phase. Figure 4: JSP 3-phase LifecycleGiven 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 no
    • methods whatsoever. JSPs are compiled into an equivalent servlet class by the server. It isthis servlet class that handles all requests to the JSP page. This translation into a servletand subsequent compilation are done transparently by the server. The developer need notworry 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/jspBelow is the servlet equivalent of our JSP example.
    • 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("<HTML>n");out.write("n");out.write(" <TITLE>Welcome</TITLE>n");
    • out.write("n");out.write(" <BODY>n");out.write(" <H1> Greetings!</H1> <br>n");out.write("n");out.write(" Thank you for accessing our site. <br>n");out.write("n");out.write(" The time is now ");out.print( new java.util.Date());out.write("n");out.write("n");out.write(" </BODY>n");out.write("n");out.write("</HTML>");} 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 SemanticsAlthough JSP is Java-based, and is handled as Java code by the servlet, the syntax it allowsdevelopers to use is different from that of the Java 2.0 specification. Instead, it follows rulesdefined in the JSP specification. The following section describes JSP syntax in more detail. Elements and Template DataComponents 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, <%=new java.util.Date()%> is the only element data the rest are template data.
    • Listing 1: hello.jsp<html><head><title>Hello World!</title></head><body><center><h1>Hello World! Its <%= new java.util.Date()%></h1></center></body></html> Two Types of SyntaxTwo 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 simply 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 understand. Thistext will be using the normal syntax in its examples. Scripting ElementsAs 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. . ScriptletsScriptlets provide a way to directly insert bits of Java code in between chunks of templatedata and has the following form:<% Java code; %>Defining Java code in between <% and %> 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
    • 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 in apage. Even later on, we will be discussing how to use custom tags to provide common taskssuch as looping, logic branching, etc. This, combined with JavaBeans usage will cut scriptletusage down to nearly zero.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.Simple Println Figure 5: PrintlnScriplet.jspThe example above is a simple illustration embedding Java code into your JSP. The codeabove outputs the text, jedi, into the web browser.For-Loop in a scriptlet Figure 6: LoopScriplet.jsp
    • 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 bethe text “This line is printed 10 times.” printed 10 times due to the for-loop running fromiteration 0 through 9 as shown below. Figure 7: Output of LoopScriplet.jspTake note that the scriptlet itself is not sent to the client but only its output. Try viewing thesource of the JSP output youve 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:<jsp:declaration>Java code;</jsp:declaration>. . ExpressionsExpressions provide a way to insert Java values directly into the output. It has the followingform:<%= Java Expression %>It is actually an abbreviation 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 <%= and %> 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 theprimitives string representation is displayed.As mentioned earlier, evaluation is performed at run-time (when the page is requested).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: <%= request.getRemoteHost() %>Finally, the XML-compatible syntax for <%= Java Expression %> is:<jsp:expression>Java Expression</jsp:expression> . DeclarationsDeclarations allow you to define methods or variables. It has the following form:<%! Java Code %>Declarations are used to embed code just like scriptlets. Although, declarations get insertedinto the 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 takenwhen writing JSP declarations.The following are a few simple reminders in using the declaration tag:
    • • Before the declaration you must have <%!. • At the end of the declaration, the developer 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 Figure 8: AccessCountDeclaration.jspThe 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 four times.
    • Figure 9: Output of AccessCountDeclaration.jspFor 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.javapackage 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 (
    • 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("<html>n"); out.write("<head>n"); out.write("<title>Declaration Example</title>n"); out.write("</head>n"); out.write("<body>n"); accessCount++; out.write("Accesses to page since server reboot: n"); out.print( accessCount ); out.write("n"); out.write("</body>n"); out.write("</html>n"); out.write("n"); out.write("n"); } 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); } }}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. The preceding code has shown us the actualplacement of declarations, scriptlets and expressions in a Java source code translated froma JSP page.Finally, note that the XML-compatible syntax for <%! JavaCode %> is<jsp:declaration>Java Code;</jsp:declaration> . Template Text • Use <% to get <% in output. • <%-- JSP Comment --%> • <!-- HTML Comment --> • All other non-JSP-specific text passed through to output page. Predefined VariablesIn discussing the expression tag, we came across JSP implicit objects. This section describesthese objects in detail.JSP implicit objects are automatically declared by the JSP container and are always availablefor use in expressions and scriptlets (but not in declarations). What follows are the list ofimplicit objects:request: The instance of the javax.servlet.http.HttpServletRequest object associated with
    • 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 DirectivesDirectives are messages to a JSP container. They affect the overall structure of the servletclass. It usually has the following form:<%@ directive attribute="value" %>A list of attribute settings can also be enumerated for a single directive as follows:<%@ directive attribute1="value1" attribute2="value2" ... attributeN="valueN" %>Note: Whitespaces after <%@ and before %> 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 bea page, include or taglib and each of these directives has its own set of attributes. . Page directive
    • The page directive defines the processing of information for a 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 Usageextends Superclass used by the JSP <%@ page extends = “com.taglib…” engine for the translated %> Servlet. Analogous to the extends keyword in the Java programming language.language Indicates which scripting <%@ page language = “java” %> language the scriptlets, expressions and declarations found in the JSP page uses. The only defined value for this attribute is java.import Import the classes in a java <%@ page import = “java.util.*” %> package into the current JSP page.session Indicates whether the page Default is set to true. makes use of sessions. By default all JSP pages have session data available. Switching session to false has performance benefits.buffer Controls the use of buffered <%@ page buffer = “none” %> output for a JSP page. If values is none, then there is no buffering and output is written directly to the appropriate PrintWriter. Default value of buffer is 8kb.autoFlush When set to true, flushes the <%@ page autoFlush = “true” %> output buffer when it is full.isThreadSafe Indicates if the generated Servlet deals with multiple requests. If true, a new thread is started to handle requests simultaneously. Default value is true.
    • Directive Description Sample Usageinfo Developer uses info attribute <%@ page info = “jedi.org test page, to add information/document alpha version “ %> for a page. Typically this is used to add author, version, copyright and date info.errorPage Defines the page that deals <%@ page errorPage = “/errors.jsp” with errors. Must be URL to %> error page.IsErrorPage A flag that is set to true to make a JSP page a special Error Page. This page has access to the implicit object exceptionThe XML syntax for defining directives is<jsp:directive.directiveType attribute=value />For example, the XML equivalent of<%@ page import="java.util.*" %>is<jsp:directive.page import="java.util.*" /> . Include directiveThe 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 components that are common to multiple pages likenavigation, tables, headers and footers, etc.The include directive follows the syntax:<%@ include file = "relativeURL" %>For example, if you want to include a menu bar found in the current directory, you wouldwrite:<%@ include file = "menubar.jsp" %> . Tag Lib directiveA 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:<%@ taglib uri = “tag library URI” prefix = “tag Prefix” %>
    • 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<%@ taglib uri="struts/template" prefix="template" %><template:insert template="/WEB-INF/view/template.jsp"><template:put name="header" content="/WEB-INF/view/header.jsp" /><template:put name="content" content="/WEB-INF/view/index_content.jsp" /><template:put name="footer" content="/WEB-INF/view/footer.jsp" /></template:insert>Custom tags were introduced in JSP 1.1 and allow JSP developers to hide complex serverside code from web designers. JavaBeans in JSPThe use of JavaBeans are not mandated in the JSP specification. However, they provideuseful functionality. 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:
    • 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 that transferdata from another source. In most applications, actual processing is done in a servlet, not ina JSP. Only the results of the passing are passed on to the JSP in the form of one or moreJavaBeans.As a Helper object – In some small applications, it is not efficient to have a separate servletto process the data. In this case, it is better to place the functionality inside JavaBeanswhich can be accessed by the JSP.
    • . JavaBeans-related JSP ActionsJSP defines standard actions that simplify the usage of JavaBeans.<jsp:useBean>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 the actions listed below.The attributes of the <jsp:useBean> action are as follows: • id - specifies the name of the bean and how you will refer to it in the page. • scope - specifies the scope in which you want to store the bean instance. It can be set to page (the default), session, request, or application. • class - specifies the Java class that the bean is drawn from. If you have specified beanName, you do not have to specify class. • beanName - 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 - specifies the type of scripting variable returned by the bean. The type must relate to the class of the bean.The following is a sample of how to use the User JavaBean in a JSP page:<jsp:useBean id="user" scope="session" class="jedi.bean.User"/>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 beaninstance using the beans 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:<%jedi.bean.User user = (jedi.bean.User)session.getAttribute("user");if (user == null) {user = new User();session.setAttribute("user", user);}%>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:
    • <jsp:useBean id="user" scope="session" class="jedi.bean.User"/><HTML> <BODY> Hello <%= user.getName() %> !! </BODY></HTML><jsp:getProperty>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 have the same value as the id attribute used in an earlier <jsp:useBean> 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 expression language (to be discussed in a future chapter).Adding up to our examples above, to display the name property of the User JavaBean, wemake use of the getProperty action like this :<jsp:getProperty name="user" property="name"/><jsp:setProperty>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 an expression evaluated at runtime. • param – specifies the request parameter from which the property will retrieve its value.Developers who makes use of this action must specify 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 by a relative URL tothe JSP page designated as an error page. The page thus designated can set the isErrorPageattribute 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: <%@page errorPage="errorPage.jsp"%> <HTML> <% String nullString = null; %> // call a method on the null object, so that an exception will be thrown and the error page called The length of the string is <%= nullString.length() %> </HTML><%@page isErrorPage="true"%><HTML><TITLE>Error!</TITLE><BODY><H1>An Error has occurred.</H1><br/>Sorry, but an error has occurred with the page you were previously accessing. Pleasecontact any member of the support team, and inform them that <%=exception.getMessage() %> was the cause of the error</BODY></HTML>The first listing shows a JSP page using the page directive to describe an error page that willbe used for unhandled exceptions.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.EXERCISES1) 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: a) Retrieve the Recipe instance using JSP actions. b) Display the details contained in the instance. This includes displaying each element inthe ingredient list. The details should be displayed using JSP actions as well.2) Given the same class and scenario 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 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:<TABLE cellspacing="5"> <tr> <td colspan="2"> This is very important content </td> </tr> <tr> <td colspan="2"> Inclusion successful! </td> </tr></TABLE>Create a JSP file that will include the content defined in otherContent.jsp.