Sie sind auf Seite 1von 99

JavaTM Education & Technology Services

Developing Web Applications using Java Server Pages (JSP)


JavaTM Education & Technology Services
Copyright Information Technology Institute 1

Table of Contents

Chapter 1: JSP Basics Chapter 2: JSP Syntax Chapter 3: JSP and Java Beans

JavaTM Education & Technology Services


Copyright Information Technology Institute http://jets.iti.gov.eg 2

Chapter 1
JSP Basics

JavaTM Education & Technology Services


Copyright Information Technology Institute 3

Chapter 1 Outline
What is Java Server Page (JSP)? What is wrong with servlets? What is the difference between servlets and JSP? Advantages of JSP Ad t f JSP. How JSP look like? How JSP works? javax.servlet.jsp package.
JspPage interface HttpJspPage Interface JSP Classes
JavaTM Education & Technology Services
Copyright Information Technology Institute http://jets.iti.gov.eg 4

What is Java Server Page (JSP) ? An extension of the servlet technology created to support authoring of HTML and XML pages pages. What is wrong with servlets ?
Most Web pages are HTML. Every single change will require the involvement of the servlet programmer. No clear separation of presentation and logic. Little bit difficult for web programmers.

JavaTM Education & Technology Services


Copyright Information Technology Institute http://jets.iti.gov.eg 5

What is the difference between servlets and JSP?

Servlets: Are Java programs with embedded HTML HTML. Generate dynamic content. Do not separate static and dynamic content content. JavaServer Pages: Are HTML pages with embedded Java code or they can be pure XML. Generate dynamic content content. Separate static and dynamic content.
JavaTM Education & Technology Services
Copyright Information Technology Institute http://jets.iti.gov.eg 6

Benefits of JSP Easier to author (Web-site development tools). Separating the development team responsibilities. responsibilities Business and presentation logic are separated. Simplify development with JSP J Si lif d l t ith JSP, JavaBeans and B d custom tags. Supports software reuse through the use of components. Recompile automatically when change are made to the source file. Platform independent. independent
JavaTM Education & Technology Services
Copyright Information Technology Institute http://jets.iti.gov.eg 7

How JSP look like?


<HTML> tags stay as they are. When you need to add dynamic content, all you need to do is enclose your code in <% %> tags
<%@ page import="java.util.Enumeration" %> <HTML> <HEAD><TITLE> Using JSP </TITLE></HEAD> <BODY BGCOLOR= #DADADA> <% Enumeration parameters = request.getParameterNames(); String param = null; while (parameters.hasMoreElements()) { param = (String) parameters.nextElement(); out.println(param + ":" + request.getParameter(param) + "<BR>");} out.close(); (); %> </BODY> </HTML>

JavaTM Education & Technology Services


Copyright Information Technology Institute http://jets.iti.gov.eg 8

How JSP works ?


J2EE container Web container
( p g compiler ) page p

First time No

Yes 1 Create servlet date.java 2

http://host/date.jsp

3 Servlet life cycle

Compile servlet date.class

JavaTM Education & Technology Services


Copyright Information Technology Institute http://jets.iti.gov.eg 9

Example

<HTML> <HEAD> </HEAD> <BODY>

<% out.println ( "JSP i easy");%> % t i tl is ") %

</BODY> </HTML>

public void _jspService(..) { out.write("<HTML>\r\n"); out.write( <HEAD>\r\n ); out write("<HEAD>\r\n"); out.write("</HEAD>\r\n"); out.write("<BODY>\r\n"); out.println("JSP i easy"); t i tl ("JSP is ") out.write("\r\n"); out.write("</BODY>\r\n"); out.write("</HTML>"); }

JavaTM Education & Technology Services


Copyright Information Technology Institute http://jets.iti.gov.eg 10

Notes on JSP life Cycle

* Source: Core Servlets and Javaserver Pages By Marty Hall, Larry Brown ISBN 0130092290
JavaTM Education & Technology Services
Copyright Information Technology Institute http://jets.iti.gov.eg 11

Why JSP developers need servlets? 1. JSP pages are translated into servlets. 2. 2 JSP consists of static HTML, JSP tags, and i t f t ti HTML t d Java code (Servlet code). 3. Some tasks are better accomplished b servlets 3 S t k b tt li h d by l t than by JSP. 4. 4 Combination of servlets and JSP JSP.

JavaTM Education & Technology Services


Copyright Information Technology Institute http://jets.iti.gov.eg 12

javax.servlet.jsp.*

JSP is involved in two main packages:


javax.servlet.jsp javax.servlet.jsp.tagext j j p g custom tags - Advanced g

javax.servlet.jsp contains 2 interfaces , 2 Exceptions and 4 classes Interfaces :


JspPage HttpJspPage

JavaTM Education & Technology Services


Copyright Information Technology Institute http://jets.iti.gov.eg 13

javax.servlet.jsp.* (contd) Classes:


J F t JspFactory PageContext JspEngineInfo JspWriter

Exceptions:
JspException JspError.

JavaTM Education & Technology Services


Copyright Information Technology Institute http://jets.iti.gov.eg 14

JspPage interface
The JspPage is the interface that must be implemented by all JSP servlet classes. y It contains two methods:
public void jspInit() public void j p p jspDestroy() y() Example:
<% ! (Note it is <%! JSP Declaration Not <%) public void jspInit() { System.out.println("Init"); } public void jspDestroy() { System.out.println("Destroy"); } %>

JavaTM Education & Technology Services


Copyright Information Technology Institute http://jets.iti.gov.eg 15

HttpJspPage Interface
It extends the JspPage interface. It has got only one method : public void _jspService ( HttpServletRequest request,HttpServletResponse response ) throws ServletException, IOException. Its called by the JSP container, to generate the content of the JSP page. you can't include this method in a JSP page, because the page content itself represents this method method.
JavaTM Education & Technology Services
Copyright Information Technology Institute http://jets.iti.gov.eg 16

JSP Classes

The JspFactory class The JspEngineInfo class The PageContext class Implicit objects Implicit objects The JspWriter class

JavaTM Education & Technology Services


Copyright Information Technology Institute http://jets.iti.gov.eg 17

1-The JspFactory Class


A abstract class that provides methods f obtaining An b t t l th t id th d for bt i i other objects needed for the JSP page processing. The class has the static method getDefaultFactory that returns a JspFactory object. From the JspFactory object, a PageContext and a JspEngineInfo object can be obtained using: public abstract JspEngineInfo getEngineInfo( ) public abstract P bli b t t PageContext getPageContext (S l t C t t tP C t t (Servlet requestingServlet, ServletRequest request, ServletResponse response, String errorPageURL, boolean needsSession int buffer boolean autoFlush) needsSession, buffer,
JavaTM Education & Technology Services
Copyright Information Technology Institute http://jets.iti.gov.eg 18

The JspFactory Class (cont.)

The following code is p of the _ j p g part jspService method that is generated by the JSP container:
JspFactory _jspxFactory = null; jspxFactory PageContext pageContext = null; _jspxFactory =JspFactory.getDefaultFactory(); pageContext = _jspxFactory.getPageContext ( this, request, response,"", "" true, 8192, true);
JavaTM Education & Technology Services
Copyright Information Technology Institute http://jets.iti.gov.eg 19

2-The JspEngineInfo Class

The JspEngineInfo class is an abstract class that provides information on the JSP container. It has only one method, getSpecificationVersion, returns the JSP container's version number.

JavaTM Education & Technology Services


Copyright Information Technology Institute http://jets.iti.gov.eg 20

3-The PageContext Class PageContext represents a class that provides methods that are implementation-dependent. implementation dependent. The PageContext class itself is abstract so in abstract, the _ jspService method of a JSP servlet class, a PageContext object is obtained by calling the getPageContext method of the JspFactory class.

JavaTM Education & Technology Services


Copyright Information Technology Institute http://jets.iti.gov.eg 21

The PageContext Class (cont.) The PageContext class provides methods that are used to create other objects. j
getOut method returns a JspWriter object that is used to send strings to the web browser. getRequest, returns a S tR t t ServletRequest object. l tR t bj t getResponse, returns a ServletResponse object. getServletConfig returns a ServletConfig object getServletConfig, object. getServletContext, returns a ServletContext object. getSession, returns an HttpSession object. getSess o , etu s a ttpSess o object

JavaTM Education & Technology Services


Copyright Information Technology Institute http://jets.iti.gov.eg 22

4-The JspWriter Class The JspWriter class is derived from the java.io.Writer class and represents a Writer that you can use to write to the client browser. Of its many methods, the most important are the print and println methods.

JavaTM Education & Technology Services


Copyright Information Technology Institute http://jets.iti.gov.eg 23

Implicit Objects of PageContext class

request response out session application config

javax.servlet.http.HttpServletRequest javax.servlet.http.HttpServletResponse javax.servlet.jsp.JspWriter javax servlet jsp JspWriter javax.servlet.http.HttpSession javax.servlet.ServletContext javax servlet ServletContext javax.servlet.ServletConfig

JavaTM Education & Technology Services


Copyright Information Technology Institute http://jets.iti.gov.eg 24

Review

Revisiting the generated Servlet out of a JSP file If the code written in the JSP page was only : p g y
<% out.println("JSP is easy"); %>

JavaTM Education & Technology Services


Copyright Information Technology Institute http://jets.iti.gov.eg 25

Strategies for invoking dynamic code


1. Call Java code di tl (S i tl t ) 1 C ll J d directly (Scriptlets) 2. 2 Develop separate utility classes Insert into JSP page classes, only the Java code needed to invoke the utility classes. 3. Develop separate utility classes structured as beans. 4. MVC architecture. A servlet respond to original request, look up data, and store results in beans, forward to a JSP page to present results, JSP page uses beans.
Complex Simple

1. Use the JSP expression language. 2. Use custom tags.


Copyright Information Technology Institute

Advanced

JavaTM Education & Technology Services


http://jets.iti.gov.eg 26

Strategies for invoking dynamic code (cont)

Why limiting the amount of Java code in JSP pages ?


Development. Compilation. Debugging. Division of labor. Testing. Reuse.

JavaTM Education & Technology Services


Copyright Information Technology Institute http://jets.iti.gov.eg 27

Lab Exercise

JavaTM Education & Technology Services


Copyright Information Technology Institute 28

Assignments

Make a simple JSP displaying the time. Make an html page that redirect a request to an JSP

JavaTM Education & Technology Services


Copyright Information Technology Institute http://jets.iti.gov.eg 29

Chapter 2
JSP Syntax

JavaTM Education & Technology Services


Copyright Information Technology Institute 30

Chapter 2 Outline
JSP tags : Directive elements Scripting elements Action elements Converting into XML syntax

JavaTM Education & Technology Services


Copyright Information Technology Institute http://jets.iti.gov.eg 31

JSP Syntax JSP contains 2 main things :


JSP tags/ JSP elements : make up the syntax and t / l t k th t d semantics of JSP. Template Data : anything else ,not understood by the JSP container
example :HTML tags

JSP tags are :


Directive elements S i ti elements Scripting l t Action elements

JavaTM Education & Technology Services


Copyright Information Technology Institute http://jets.iti.gov.eg 32

JSP tags
JSP tags Directive Scripting Action

page

Scriptlets

include

Declarations

taglib

Expressions

JavaTM Education & Technology Services


Copyright Information Technology Institute http://jets.iti.gov.eg 33

1-Directive Elements They are messages to the JSP container containing information on how the JSP container must translate a JSP page into a corresponding servlet. They are actually instructions to the container not a code. Directives Types :
Page directives Include directives Tag library directives (used with custom tags )

JavaTM Education & Technology Services


Copyright Information Technology Institute http://jets.iti.gov.eg 34

1-Directive Elements (contd)

Directive element Syntax


<%@ directive (attribute="value")* %>

Example
<%@ page buffer="16384" session="false" %> <%@ include file=footer.html" %> <%@ talib uri=. prefix =c%> Advanced

JavaTM Education & Technology Services


Copyright Information Technology Institute http://jets.iti.gov.eg 35

1-Directive Elements (contd) a-Page Directive Attributes


Atribute import contentType session buffer autoFlush info errorPage isErrorPage isThreadSafe extends g g language Value Type Fully qualified class name MIME type, character set Boolean Buffer size in Kb or false Boolean String URL Boolean Boolean Class name Scripting language name p g g g Default None "text/html;charset=ISO8859-1 true 8192 "true Depends on the container None "false "true None "java" j

JavaTM Education & Technology Services


Copyright Information Technology Institute http://jets.iti.gov.eg 36

1-Directive Elements (contd) a-Page Directive Attributes

Examples
<%@ page import="java.util.Enumeration" %> <%@ page session="false" %> @p g <%@ page buffer="16384" %> <%@ page autoFlush="false" %> <%@ page errorPage="ErrorPage.jsp" %>

Its not allowed to repeat assigned attributes except for import attribute tf i t tt ib t

JavaTM Education & Technology Services


Copyright Information Technology Institute http://jets.iti.gov.eg 37

1-Directive Elements (contd) a-Page Directive Attributes Notes on import attribute 1st and 2nd strategy for invoking dynamic code. Utility classes should always be in packages and the JSP page should use the import attribute. By default the generated servlet imports java.lang.*, default, java lang * javax.servlet.*, javax.servlet.jsp.*, javax.servlet.http.*. The only page attribute that is allowed to appear multiple yp g pp p times. The utility classes should be placed in /WEB-NF/classes/ Note: <%@ page import="package.class1,...,package.classN" %>

JavaTM Education & Technology Services


Copyright Information Technology Institute http://jets.iti.gov.eg 38

1-Directive Elements (contd) b-The Include Directive

It enables JSP page authors to include the contents of other files in the current JSP page. We can include static page like html or another JSP page. p g Include Syntax:
<%@ include file="relativeURL" %> @

Example:
<%@ include file=header.html" %> @

Note the generated servlets code. g


JavaTM Education & Technology Services
Copyright Information Technology Institute http://jets.iti.gov.eg 39

2-Scripting Elements

It allows you to insert Java code in your JSP pages. 1st and 2nd strategy for invoking dynamic code. gy g y There are three types:
Scriptlets p Declarations Expressions

JavaTM Education & Technology Services


Copyright Information Technology Institute http://jets.iti.gov.eg 40

2-Scripting Elements (contd) a-Scriptlets

Inserted into the servlets _jspService method Syntax


<% //// put here your java code //// %>

E Example: l
<% out.println("Current Time: " + getSystemTime()) ; t i tl ("C t Ti tS t Ti ()) %>

JavaTM Education & Technology Services


Copyright Information Technology Institute http://jets.iti.gov.eg 41

2-Scripting Elements (contd) b-Declarations

I used to d l Its d declare methods or variables. h d i bl Inserted into the body of the servlet class, outside any existing methods. i ti th d Can not access the implict objects of _jspService method Syntax:
<%! //// put your code here //// %>

Examples:
<%! String getSystemTime() { return Calendar.getInstance().getTime().toString(); }% }%> <%! int x; %>
JavaTM Education & Technology Services
Copyright Information Technology Institute http://jets.iti.gov.eg 42

2-Scripting Elements (contd) c-Expressions

Its used to evaluate expressions and print them to the user. Its used instead of out.println() Syntax:
<%= put the variable here %> % %

Example:
<%= java.util.Calendar.getInstance().getTime() %> % % The same result of : out.print( java.util.Calendar.getInstance().getTime() );
JavaTM Education & Technology Services
Copyright Information Technology Institute http://jets.iti.gov.eg 43

Assignment Write a utility class that generates a random number within a given range range. Invoke methods of this utility class from jsp page using scripting elements elements.

JavaTM Education & Technology Services


Copyright Information Technology Institute http://jets.iti.gov.eg 44

3-Standard Action Elements They consists of :


jsp:include jsp:forward jsp:param jsp:plugin jsp:params jsp:fallback jsp:useBean jsp:setProperty jsp:getProperty

JavaTM Education & Technology Services


Copyright Information Technology Institute http://jets.iti.gov.eg 45

3-Standard Action Elements(cont) Include, forward and param

They got the same effect of RequestDispatcher include and forward Syntax:
<jsp:include page="relativeURL> page relativeURL > ( <jsp:param . . . /> )* </jsp:include> j p <jsp:forward page="relativeURL"> ( <jsp:param . . . /> )* </ jsp:forward >
JavaTM Education & Technology Services
Copyright Information Technology Institute http://jets.iti.gov.eg 46

3-Standard Action Elements(cont) Include, forward and param Notes on jsp:include The included pages can be - HTML files, plain text files, JSP pages, S l t fil l i t t fil Servlets - With JSP pages and servlets, only the output of the page is included, not the actual code. Do not use complete HTML documents for the included pages. The included page uses the same request object as the originally requested page and sees the same request parameters. The main page can add to or replace the request parameters using jsp:param.
JavaTM Education & Technology Services
Copyright Information Technology Institute http://jets.iti.gov.eg 47

3-Standard Action Elements(cont) Include, forward and param Notes on jsp:forward Using jsp:forward obtain the complete output from the destination page page. The main page must not have any output. The main page can add to or replace the request parameters using jsp:param.

JavaTM Education & Technology Services


Copyright Information Technology Institute http://jets.iti.gov.eg 48

jsp:include vs. include directive


<jsp:include <j i l d page= url /> l <%@ i l d file= url %> include fil l

I l d th output of Include the t t f a page at request time

Insert JSP code into the main page before that main page is translated into a servlet. The main page must be updated whenever any of the included pages p g change. The included code can contain JSP constructs such as field definitions and content-type settings that affect the main page as a whole.
JavaTM Education & Technology Services
http://jets.iti.gov.eg 49

No change needed in the main page when the included pages change change. The included pages p g cannot use any JSP constructs that affect the main page as a whole.

Copyright Information Technology Institute

Assignment Use both jsp:include and include directive to include header to your jsp and Note the difference.

JavaTM Education & Technology Services


Copyright Information Technology Institute http://jets.iti.gov.eg 50

3-Standard Action Elements(cont.) Plugin, Fallback and params Sun developed a browser plug-in for Netscape and Internet Explorer that lets you use the Java 2 platform in a variety of browser versions. i t fb i In some browsers, the normal APPLET tag will not work with the plug-in. Instead, use OBJECT tag for Internet plug in. Explorer and EMBED tag for Netscape. The <jsp: plugin> is used to generate HTML <OBJECT> or <EMBED> t EMBED tags that instruct the browser to download th t i t t th b t d l d the Java Plugin software, if required, and initiate the execution of the Java applet specified. pp p Note: The applet .class files must not be placed in WEBINF/classes, as the browser, not the server, uses them.
JavaTM Education & Technology Services
Copyright Information Technology Institute http://jets.iti.gov.eg 51

3-Standard Action Elements(cont.) Plugin, Fallback and params


<APPLET CODE="MyApplet.class WIDTH=475 HEIGHT=350> <PARAM NAME="PARAM1" VALUE="VALUE1"> </APPLET>

< jsp:plugin type="applet code="MyApplet class width="475" height="350"> type= applet code= MyApplet.class width= 475 height= 350 > <jsp:params> <jsp:param name="PARAM1" value="VALUE1" /> </jsp:params> </jsp:plugin>

JavaTM Education & Technology Services


Copyright Information Technology Institute http://jets.iti.gov.eg 52

3-Standard Action Elements(cont.) useBean, setProperty and getProperty

Used to contact a bean


Will be described in details in the next chapter

JavaTM Education & Technology Services


Copyright Information Technology Institute http://jets.iti.gov.eg 53

Comment tag
HTML comments <! <!-- HTML Comment --> >

JSP comment <%-- JSP Comment --%>

JavaTM Education & Technology Services


Copyright Information Technology Institute http://jets.iti.gov.eg 54

Assignment Use <jsp: plugin> to embed Applet in your jsp page. g

JavaTM Education & Technology Services


Copyright Information Technology Institute http://jets.iti.gov.eg 55

Converting into XML syntax

Benefits:
The content of the JSP page can be validated against a set of descriptions. The JSP page can be manipulated using an XML tool. The JSP page can be generated from a textual representation by applying an XML transformation

JavaTM Education & Technology Services


Copyright Information Technology Institute http://jets.iti.gov.eg 56

Converting into XML syntax (contd) Syntax


<jsp:directive.directiveName attribute_list /> <jsp:declaration> d l ti code </jsp:declaration> j d l ti declaration d /j d l ti <jsp:scriptlet> scriptlet code </jsp:scriptlet> <jsp:expression> expression </jsp:expression> jsp:expression /jsp:expression

Examples:
<jsp:directive.page attr=value /> j p p g <jsp:scriptlet> String s; s = request.getParameter("user"); </jsp:scriptlet> <jsp:text>.</jsp:text> <jsp:text> </jsp:text>

JavaTM Education & Technology Services


Copyright Information Technology Institute http://jets.iti.gov.eg 57

Converting into XML syntax (contd)


Notes on XML Syntax: XML element names can contain colons, XMLcompatible version of all standard JSP elements tibl i f ll t d d l t starts with the jsp prefix (or namespace). XML tags are case sensitive. XML tags must be explicitly closed. To get ' within an attribute value, use \. To get ", use \; to get \, use \\; to get %>, use %\>; and to get <%, use <\% <% <\%.
JavaTM Education & Technology Services
Copyright Information Technology Institute http://jets.iti.gov.eg 58

Chapter 3
JSP and Java Beans

JavaTM Education & Technology Services


Copyright Information Technology Institute 59

Chapter 3 Outline
What is a Bean? <useBean> Tag Structure. Structure How to use a request parameter to feed the value of a bean variable ?

JavaTM Education & Technology Services


Copyright Information Technology Institute http://jets.iti.gov.eg 60

What is a Bean? A bean is a java class with certain rules defined by the JavaBeans specification. Beans extend no particular class and use no particular interface. The 3rd strategy for invoking dynamic code.

JavaTM Education & Technology Services


Copyright Information Technology Institute http://jets.iti.gov.eg 61

Why beans? Why we should use beans in JSP ?


Avoiding spagitti code. No Java syntax, instead XML-compatible tags. Clear separation of roles. Simpler object sharing. Convenient correspondence between request parameters and object properties. t d bj t ti

JavaTM Education & Technology Services


Copyright Information Technology Institute http://jets.iti.gov.eg 62

Java Beans Rules A bean class must have a default constructor ( (which will be called when JSP elements or servlets create beans). A bean class should have no public instance variables. Persistent values (properties) should be accessed through methods called getXxx and setXxx. Or isXxx and setXxx for bolean properties.
JavaTM Education & Technology Services
Copyright Information Technology Institute http://jets.iti.gov.eg 63

Java Beans Rules (cont) Example:


- If your Book bean class has a long instance variable y g isbn and a boolean borrowed. - Then your bean class should have the following methods to make isbn and borrowed accessible by the standard JSP actions: long getIsbn () void setIsbn (long isbn) boolean isBorrowed () void setBorrowed (boolean borrowed)

JavaTM Education & Technology Services


Copyright Information Technology Institute http://jets.iti.gov.eg 64

Java Beans Rules (cont) Notes on Bean classes :


Place all your beans in packages. Install them in the normal Java code directories: WEB-INF/classes/ for individual classes and WEB-INF/lib for JAR files.

JavaTM Education & Technology Services


Copyright Information Technology Institute http://jets.iti.gov.eg 65

<useBean> Tag Structure <j jsp:useBean ( ib B (attribute="value")+ / " l ") /> Main attributes :
id class scope (page request, session, application) (page, request session

Example: <jsp:useBean id=beanName" scope="session" id= beanName" class=" com.mybeans.MyFirstBean"/> This element can either build a new bean or access a preexisting one in the specified scope scope.
JavaTM Education & Technology Services
Copyright Information Technology Institute http://jets.iti.gov.eg 66

<useBean> Tag Structure (cont) You must use the fully qualified class name for the class attribute regardless of whether you use <%@ page import... %> to import packages. <jsp:useBean id=bookBean class=" com.mybeans.MyBookBean"/>

<% com.mybeans.MyBookBean bookBean = new com.mybeans.MyBookBean(); %>


JavaTM Education & Technology Services
Copyright Information Technology Institute http://jets.iti.gov.eg 67

<getProperty> & <setProperty> Tags Structure

Accessing Properties in a bean through :


jsp:getProperty jsp:setProperty

Syntax: <jsp:getProperty name=" beanName " property="propertyName"/> This element reads and outputs the value of a bean property. Reading a property means calling its getXxx method.
JavaTM Education & Technology Services
Copyright Information Technology Institute http://jets.iti.gov.eg 68

<getProperty> & <setProperty> Tags Structure (cont)

<jsp:setProperty name=" beanName " jsp:setProperty name property=propertyName" value="value"/> This element modifies a bean property (i.e., calls its setXxx method). method)

JavaTM Education & Technology Services


Copyright Information Technology Institute http://jets.iti.gov.eg 69

<getProperty> & <setProperty> Tags Structure (cont)

JSP expression could be used to call a method on the object with the variable specified by the id j y attribute. <%= bookBean.getIsbn() %> <jsp:getProperty name=" bookBean " j pg p y property=isbn"/> It is not advisable but can be useful with loops, conditional statements, and methods not represented as properties.
JavaTM Education & Technology Services
Copyright Information Technology Institute http://jets.iti.gov.eg 70

<getProperty> & <setProperty> Tags Structure (cont)

JSP scriptlet could be used to explicitly call methods on the bean object. j <% bookBean.setIsbn (1234567890); %> <jsp:setProperty name=" bookBean" p p y property=isbn" value=1234567890"/> It is not advisable but can be useful in setting the g value conditionally or calling methods other than getXxx or setXxx on the object.
JavaTM Education & Technology Services
Copyright Information Technology Institute http://jets.iti.gov.eg 71

Example
package com mybeans; com.mybeans; public class MyFirstBean { private String firstName; public String getFirstName() { return firstName; } public void setFirstName(String name) { firstName=name; firstName name } } Note:In beans terminology the class is said to have a String property called firstName.
JavaTM Education & Technology Services
Copyright Information Technology Institute http://jets.iti.gov.eg 72

Example (cont.)

<jsp:useBean id= myBean jsp:useBean id myBean class=com.mybeans.MyFirstBean /> <jsp:setProperty name= myBean p p y property=firstName value= Ali /> The First Name is <jsp:getProperty e st a e s jsp get ope ty name=myBean property=firstName />

JavaTM Education & Technology Services


Copyright Information Technology Institute http://jets.iti.gov.eg 73

Example (cont.) Note You can access the bean methods using scripting tags g g
<jsp:useBean id= myBean class=com.mybeans.MyFirstBean /> <% St i name = Ali % String ; myBean.setFirstName (name); %> The First Name is <%= myBean.getFirstName()%> Note: Whenever possible, avoid mixing the XMLcompatible jsp:useBean tags with JSP scripting elements containing explicit J t i i li it Java code. d
JavaTM Education & Technology Services
Copyright Information Technology Institute http://jets.iti.gov.eg 74

How to use a request parameter to feed the value of a bean variable ? Consider this case: <% int isbn = 1; try { y isbn = Integer.parseInt(request.getParameter(isbNum")); } catch(NumberFormatException nfe) { } %> <jsp:setProperty name=bookBean property=isbn" <j tP t b kB t i b " value="<%= isbn %>" />

JavaTM Education & Technology Services


Copyright Information Technology Institute http://jets.iti.gov.eg 75

How to use a request parameter to feed the value of a bean variable ? (cont) JSP offers a better solution: <jsp:setProperty name="BeanName" property= PropertyName param= parameterName /> property="PropertyName param="parameterName"/> For Example: <jsp:setProperty name=bookBean property=" isbn" param= isbNum/>
isbNum is the name of the request parameter. The value of the request parameter isbNum is automatically used as the value of the bean property isbn. p p y Type conversions from String to primitive types (byte, int, double, etc.) and wrapper classes (Byte, Integer, Double, etc.) are automatically p performed. If the specified parameter is missing from the request, no action is taken
JavaTM Education & Technology Services
Copyright Information Technology Institute http://jets.iti.gov.eg 76

How to use a request parameter to feed the value of a bean variable ? (cont)

If the request parameter name and the bean property name are the same the param attribute could be omitted
Example: p If the request parameter has the name isbn <jsp:setProperty name=bookBean property=" isbn />

To Associate all properties with request parameters (Form Beans)


<jsp:setProperty name=bookBean property=" * />
JavaTM Education & Technology Services
Copyright Information Technology Institute http://jets.iti.gov.eg 77

Scope of the Bean

page request session i application

JavaTM Education & Technology Services


Copyright Information Technology Institute http://jets.iti.gov.eg 78

Scope of the Bean (cont) 1. page:


The default value. The bean is bound to a local variable (accessible by this jsp page only) only). The bean object is placed in the PageContext object for the duration of the current request. The code can access it by calling getAttribute on the predefined pageContext variable of the page. Th bean is not shared and th a new b The b i t h d d thus bean will b ill be created for each request.

JavaTM Education & Technology Services


Copyright Information Technology Institute http://jets.iti.gov.eg 79

Scope of the Bean (cont) 2. request:


The bean is bound to a local variable variable. The bean object is placed in the HttpServletRequest object for the duration of the current request. The servlet code can access it by calling getAttribute on the request variable. N t th t two JSP pages or a JSP page and a servlet Note that t d l t share request objects jsp:include, jsp:forward or the include or forward methods of RequestDispatcher is q p used.

JavaTM Education & Technology Services


Copyright Information Technology Institute http://jets.iti.gov.eg 80

Scope of the Bean (cont) 3. session:


The bean is bound to a local variable. The bean object will be stored in the HttpSession object associated with the current request request. The servlet code can access it by calling getAttribute on the session variable.

JavaTM Education & Technology Services


Copyright Information Technology Institute http://jets.iti.gov.eg 81

Scope of the Bean (cont) 4. application:


Th b The bean i b is bound t a l d to local variable. l i bl The bean object will be stored in the ServletContext available through the predefined application variable or by a call to getServletContext. The ServletContext is shared by all servlets and JSP pages i th W b application. in the Web li ti Values in the ServletContext can be retrieved with the getAttribute method.

JavaTM Education & Technology Services


Copyright Information Technology Institute http://jets.iti.gov.eg 82

Lab Exercise

JavaTM Education & Technology Services


Copyright Information Technology Institute 83

Assignment Write a jsp page that populates a Java bean with the data from the user and forward to another jsp page or servlet that displays the data.

JavaTM Education & Technology Services


Copyright Information Technology Institute http://jets.iti.gov.eg 84

Chapter 4
MVC Frameworks

JavaTM Education & Technology Services


Copyright Information Technology Institute 85

Chapter 4 Outline
MVC Design Pattern. Why MVC? MVC Frameworks. Implementing MVC with RequestDispatcher. I l ti ith R tDi t h

JavaTM Education & Technology Services


Copyright Information Technology Institute http://jets.iti.gov.eg 86

MVC Design Pattern Model-View-Controller (MVC) is an architectural design pattern used to build complex computer applications. It aims to separate data (model) and user interface (view). i t f ( i ) The MVC architecture divides applications into three layers : th l
Model: The data and business logic View: The presentation and User Interface Controller: The flow control

JavaTM Education & Technology Services


Copyright Information Technology Institute http://jets.iti.gov.eg 87

Why MVC? Why MVC?


Business logic and presentation are separated. y g y Flexibility: change in one layer does not affect the other.

1. 1 Dividing responsibilities:

2. Ease of maintenance. 3. 3 Pre and Post Processing (sec rit logging etc ) (security, logging, etc)

JavaTM Education & Technology Services


Copyright Information Technology Institute http://jets.iti.gov.eg 88

MVC Frameworks
The 4th strategy for invoking dynamic code. The original request is handled by a servlet. g q y The servlet invokes the business-logic and data-access code and creates beans to represent the results , decides which JSP page present those results and forwards the request to it. This servlet is the Controller. The beans representing the results are the Model. The jsp that presents the results are the View. The most popular MVC f C framework is Apache S Struts.
JavaTM Education & Technology Services
Copyright Information Technology Institute http://jets.iti.gov.eg 89

MVC Frameworks (cont)

1-request

Controller (Servlet) 2 3

Client browser

5-response

View (JSP)

Model 4 Database (EIS)

Servlet Container

JavaTM Education & Technology Services


Copyright Information Technology Institute http://jets.iti.gov.eg 90

Steps of Implementing MVC


1. Define beans to represent the data. 2. 2 Use a servlet to handle requests requests. 3. The servlet invokes business logic or data-access code to obtain the results. The results are placed in the beans (Populate the beans). 4. Store the bean in the request, session, or servlet context. context 5. Forward the request to a JSP page (using forward method of RequestDispatcher) 6. Extract the data from the beans. The JSP page accesses beans with jsp:useBean and jsp:getProperty tags. tags
JavaTM Education & Technology Services
Copyright Information Technology Institute http://jets.iti.gov.eg 91

Notes on the Steps of Implementing MVC


The Java beans must have a default constructor since a servlet or other Java routine (never a JSP page) will create the beans beans. A controller servlet handles the initial request, it can read request parameters and request headers. The controller servlet can also use the populateBean method of Jakarta Commons BeanUtils component to automatically populate a form bean with the request parameters.

JavaTM Education & Technology Services


Copyright Information Technology Institute http://jets.iti.gov.eg 92

Notes on the Steps of Implementing MVC (cont)


Jakarta Commons BeanUtils component performs the reflection and the type conversion. You can download this component from http://commons.apache.org/components.html http://commons apache org/components html Note that to install and use any external component :
List the JAR files in your CLASSPATH for development. Put the JAR files in the WEB-INF/lib directory of your Web application for deployment . deployment,

To share JAR files across Web applications, put JAR files in /common/lib.
JavaTM Education & Technology Services
Copyright Information Technology Institute http://jets.iti.gov.eg 93

Example on using BeanUtils component


import org.apache.commons.beanutils.BeanUtils; public class MyRequestServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out=response.getWriter(); MyBean bean=new MyBean(); try{ t { BeanUtils.populate (bean, request.getParameterMap()); }catch(Exception e) { e.printStackTrace(); } } }
JavaTM Education & Technology Services
Copyright Information Technology Institute http://jets.iti.gov.eg 94

Notes on the Steps of Implementing MVC (cont)


The Servlet can then call some business logic code, invoke an Enterprise JavaBeans component, or query a database t d t d t b to determine th results and fill i th value i the lt d in the l object beans. A servlet can store data for JSP pages in three main places: in the HttpServletRequest, in the HttpSession, and i th S l tC t t d in the ServletContext.

JavaTM Education & Technology Services


Copyright Information Technology Institute http://jets.iti.gov.eg 95

Notes on the Steps of Implementing MVC (cont)


BeanObject b B Obj t bean = new B BeanObject ( ) Obj t (...); request.setAttribute ("key", bean ); <jsp:useBean id="key" type=myPackage.BeanObject" scope= request /> BeanObject bean = new BeanObject (...); HttpSession session = request.getSession(); session.setAttribute ("key", bean ); <jsp:useBean id="key" type=myPackage. BeanObject " scope= session /> BeanObject bean = new BeanObject (...); getServletContext().setAttribute("key", bean ); <jsp:useBean id="key" type=myPackage. <jsp seBean id "ke " t pe m Package BeanObject " scope= application />
JavaTM Education & Technology Services
Copyright Information Technology Institute http://jets.iti.gov.eg 96

Notes on the Steps of Implementing MVC (cont)


You can place your jsp pages under the WEB-INF directory to prevent clients from accessing them directly and only servlets can forward requests to them. Using forward method of RequestDispatcher, makes the client sees the URL of the original servlet, not the URL of the final JSP page. If the destination page uses relative URLs for images or style sheets, it needs to make them relative to the servlet y URL or the server root, not to the destination pages actual location.
e.g. e g <LINK REL=STYLESHEET HREF="/path/my-styles css HREF= /path/my-styles.css TYPE="text/css">
JavaTM Education & Technology Services
Copyright Information Technology Institute http://jets.iti.gov.eg 97

Project After the user correctly log in to the Application, a specified home page is displayed according to g y g the priviliges of the user. Only the managers can add, edit or delete another employee. Implement the MVC architecture and avoid using direct java code in the jsp pages as much as you can.

JavaTM Education & Technology Services


Copyright Information Technology Institute http://jets.iti.gov.eg 98

References & Recommended Reading Core Servlets and JSP. Java for the Web with Servlets, JSP, and EJB. J f th W b ith S l t JSP d EJB Sun presentations. Oracle presentations. SCJWD study guide.

JavaTM Education & Technology Services


Copyright Information Technology Institute http://jets.iti.gov.eg 99

Das könnte Ihnen auch gefallen