Welcome to - PowerPoint PPT Presentation

1 / 140
About This Presentation
Title:

Welcome to

Description:

Welcome to Java 2 Platform, Enterprise Edition (J2EE) Java Server Pages (JSP) Objectives: In this module, you will learn to: Identify( ) the need for JSP Use ... – PowerPoint PPT presentation

Number of Views:772
Avg rating:1.0/5.0
Slides: 141
Provided by: ash8171
Category:

less

Transcript and Presenter's Notes

Title: Welcome to


1
Welcome to
  • Java 2 Platform, Enterprise Edition (J2EE)
  • Java Server Pages
  • (JSP)

2
Objectives
  • In this module, you will learn to
  • Identify(??) the need for JSP
  • Use JSP to create dynamic Web pages

3
Need for JSP
  • With the advent(??) of the Internet, the
    monolithic(??????) application architecture
    changed to the multi-tiered client-server
    architecture. The need for server side
    scripting(??) gradually(??) began to dominate(??)
    aspects of Web programming. Microsoft introduced
    Active Server Pages (ASP) to capture(??) the
    market demand for server side scripting. Working
    on similar lines, Sun Microsystem released Java
    Server Pages (JSP) to add server side programming
    functionalities to Java.

4
Need for JSP (cont)
  • A typical Web application consists of(??) the
    presentation(??) logic representing the static
    content used to design the structure of a Web
    page in terms of the page layout(??,??), color,
    and text. The business logic or the dynamic
    contents involves application of business
    intelligence and diagnostics(??) in terms of
    financial and business calculations. When
    developing Web applications, time is often lost
    in situations where the developer is required to
    code for the static content.

5
Need for JSP (cont)
  • JSP technology has facilitated(???) the
    segregation(??) of the work profiles(??) of the
    Web designer and a Web developer. A Web designer
    can design and formulate(??) the layout for the
    Web page by using HTML. On the other hand, a Web
    developer working independently can use Java code
    and other JSP specific tags(??) to code for the
    business logic. The simultaneous(???)
    construction of the static and dynamic content
    facilitates development of quality applications
    with increased productivity.

6
Need for JSP (cont)
  • A JSP page after compilation(??) generates a
    servlet and therefore incorporates(??) all
    servlet functionalities. Servlets and JSP thus
    share common features, such as platform
    independence, creation of database-driven Web
    applications, and server side programming
    capabilities. However, there are also some basic
    differences between Servlets and JSP.

7
Servlet Vs. JSP
  • Servlets tie up(????) files (an HTML file for the
    static content and a Java file for the dynamic
    content) to independently handle the static
    presentation(??) logic and the dynamic business
    logic. Due to this, a change made to any file
    requires(??) recompilation(???)of the servlet.
    JSP on the other hand allows Java to be
    embedded(??) directly into an HTML page by using
    special tags. The HTML content and the Java
    content can also be placed in separate files. Any
    changes made to HTML content is automatically
    compiled and loaded onto the server.

8
Servlets Vs. JSP (cont)
  • Servlet programming involves(??) extensive
    coding. Therefore, any change made to the code
    requires identification(??) of the static code
    content (for the designer) and dynamic code
    content (for the developer) to facilitate
    incorporation of(??) the changes. On the other
    hand, a JSP page, by virtue of the separate
    placement(??) of the static and dynamic content,
    facilitates both Web developers and the Web
    designer to work independently.

9
Servlets Vs. JSP (cont)
  • JSP is focused on simplifying(???) the creation
    and maintenance(??) of the HTML.
  • Servlets are best at invoking(??) the business
    logic and performing complicated operations.
  • A quick rule of thumb(??) is that servlets are
    best for tasks oriented(??) toward processing,
    whereas(??) JSP is best for tasks oriented toward
    presentation.
  • For some requests, servlets are the right choice.
    For other requests, JSP is a better option.

10
Which is the best ?
  • Neither Servlets alone nor JSP alone is best, and
    a combination of(??) the two, The Model View
    Controller (MVC) Architecture is best.
  • You need both Servlets and JSP in your overall
    project almost no project will consist
    entirely(???) of Servlets or entirely of JSP.
  • You require both.

11
The JSP Request-Response Cycle
  • JSP files are stored on the Web server with an
    extension of .jsp. When the client/browser
    requests for a particular(???) JSP page, the
    server in turn sends a request to the JSP engine.
  • The figure on the next slide(???) represents the
    process of the flow of events that occur after a
    client requests for a JSP page.

12
  • The Request-Response Cycle for a JSP Page

Web Server (JSP Engine)
Response
Servlet reloaded
No
Request
Check to ensure if the call to JSP is First of
its kind
Browser
Response
Servlet generationand recompilation
Yes
Response
13
JSP
  • Java Server Pages
  • The goal of JSP is to simplify(???) the
    creation(??) and management of dynamic(???) web
    pages, by separating(???) content and
    presentation(??).
  • JSPs are basically(???) files that contains
    standard(???) HTML (or XML) tags and new
    scripting(??) tags(??).

14
JSP
  • JSP pages are translated to Servlets the first
    time they are invoked(??) by the client.
  • JSP is simple
  • JSP is a text file(????)
  • Separates(??) static(??) and dynamic(??) contents

15
(No Transcript)
16
JSP PROGRAMMING
  • JSP allows mixing of Java code and HTML code.
  • This is done by putting JSP (Java) code inside a
    special tag lt and gt
  • This code block is called scriplet(??)

17
Java Server Pages
  • Java Server Pages (JSPs) extend this
    functionality by allowing you to build web pages
    that are converted(??) to Servlets at
    runtime(???).
  • The advantage of JSPs over Servlets is that the
    outer Servlet framework is still available(???),
    yet you can develop HTML and Java
    interchangeably(????) with rapid turnaround.
    Servlets are better suited to application flow
    control and JSPs are better suited to the
    building of interface and display components.

18
JSP Page
  • ltHTMLgt
  • ltHEADgt
  • ltTITLEgtFirst JSP Pagelt/TITLEgt
  • lt/HEADgt
  • ltBODYgt
  • Current Date is
  • ltnew java.util.Date().toString() gt
  • ltb stylecolorredfont-size20gt
  • This page is designed using JSP.
  • lt/bgt
  • lt/BODYgt
  • lt/HTMLgt

19
JSP Page
  • lt_at_ page languagejava import"java.util.Date"
    gt
  • ltHTMLgt
  • ltHEADgt
  • ltTITLEgtFirst JSP Pagelt/TITLEgt
  • lt/HEADgt
  • ltBODYgt
  • Current Date is
  • lt new Date().toString() gt
  • lt/bgt
  • lt/BODYgt
  • lt/HTMLgt

20
Simple Application
  • lthtmlgt
  • ltbodygt
  • lt
  • String text "World"
  • gt
  • Hello lttextgt
  • lt/bodygt
  • lt/htmlgt

21
Output
  • If you access the page with the basic
    URL(???????) (e.g., hello.jsp), the output
  • will be Hello World
  • if you access the page with a URL that has a
    subject
  • parameter (e.g., hello.jsp?subjectwuhan20city),
    the output
  • will be Hello wuhan city

22
Categories
  • JSP fall into three categories(??)
  • Directives(??)
  • Scripting Elements(????)
  • Actions(??)

23
JSP BUILDING BLOCKS
  • Scripting ElementsJSPs are built using
    comments, expressions,
  • scriptlets, and declarations. These are the basic
    building blocks
  • of JSPs.
  • The Scripting Elements let you insert(??) Java
    code into the JSP page.

24
JSP BUILDING BLOCKS
  • DirectivesThe three directives, page, include,
    and taglib(???), extend the basic scripting
    capabilities by providing compiler directives,
  • including class and package libraries, and by
    importing custom tag libraries(?).
  • Directives affect(??) the overall(???) structure
    of the servlet that results from translation.

25
JSP BUILDING BLOCKS
  • ActionsActions further extend JSP by providing
    forward
  • and include flow control, applet plug-ins, and
    access to Java-
  • Bean components.
  • These are special(???) tags available(????) to
    affect the runtime(???) behavior(??) of the JSP

26
JSP BUILDING BLOCKS
  • Implicit ObjectsImplicit objects are instances
    of specific Servlet
  • interfaces (e.g., javax.Servlet.http.HttpServletRe
    quest)
  • that are implemented and exposed by the JSP
    container. These
  • Implicit(???) objects can be used in JSP as if
    they were part of the
  • native Java language.

27
JSP LIFE CYCLE
28
JSP LIFE CYCLE
  • JavaServer Pages have a slightly different life
    cycle than Servlets.
  • Servlets are fully compiled Java classes, whereas
    JSPs must be compiled
  • into Servlets before they can be accessed.
  • The life cycle follows a pattern(??) similar to
    that of a Servlet,
  • except for the extra step of compiling the JSP.

29
JSP Life Cycle
Invoked(??) only the first time
Invoked by the container during the clean up(??)
jspInit()
jspDestroy()
_jspService()
Handles every request
30
Whats Inside
JSP
First Request
Client
Further Request
Translated
Servlet
Response
31
JSP to Servlet Compilation(??)
  • When a JSP file is accessed, the container
    converts(??) it into a Java class that implements
    the javax.servlet.jsp.HttpJspPage interface. The
    various JSP building blocks(?) are translated
    into Java code and compiled into a Servlet.

32
JSP Scripting Elements
  • A JavaServer Page looks much like an ordinary
    HTML document. Much of the JSP syntax(??) is
    based on a set of tags very similar to those of
    HTML or XML.
  • Using server-side scripting tags, you can
    encapsulate(??)Java code directly in the web
    page.

33
JSP building blocks are converted to Java code
inside the Servlet
34
Identify the tags in JSP
Tag Tag name Used to
lt-- --gt Comments Describe the function of the code that is ignored during servlet compilation. HTML comments can also be used but are visible in the pages source code.
lt_at_ gt Directives Control the structure of the servlet and serve as mere messages for the JSP engine specifying action for a particular JSP page.
lt! gt Declaration Define variables and methods. All declarative statements in a JSP page should end with a semi-colon.
lt gt Scriptlet Specify Java Code fragments.
lt gt Expression Specify statements that are evaluated and displayed in the output.
ltjsp gt Action Insert a file, reuse beans, or forward the script control to another HTML.
35
Comments
  • There are several ways to comment(??) your JSP
    code. Some types of comments
  • will be pushed through to the final HTML that is
    passed to the Client(??), whereas others will not
    be displayed. Some comment types are
  • ignored when the JSP is converted to a Servlet.
    These comments are not displayed on the final
    client-side HTML.

36
Comments
  • JSP comments can be encapsulated(??) in lt--
    and --gt tags, or as
  • regular Java comments inside a code segment(?),
    using
  • lt / and / gt tags.
  • Comments that should be visible in the final
    client-side code should be encapsulated with
    standard HTML comment tags
  • lt!-- and --gt.

37
Types of comments
  • lt-- This comment will not appear in the HTTP
    source sent to the client --gt
  • lt / This is a regular Java comment(??) inside
    a code block(?). It will not be sent with the
    html pushed to the client. / gt
  • lt //this is a single line comment in a java
    block.
  • //These comments are also not sent to the client
    gt
  • lt!-- Standard HTML comment. Visible when the
    client chooses to view source for the page --gt

38
Declarations
  • JSP declarations(??) are equivalent(???) to
    member variables(????) and functions of a class.
    The declared variables and methods are accessible
    throughout the
  • JSP. These declarations are identified(??) by
    using lt! gt or the XML
  • equivalent ltjspdeclarationgtlt/jspdeclarationgt
    tags.

39
Types of declarations
  • lt-- Declaring a page level String variable --gt
  • lt! String bookName "J2EE Book" gt
  • lt-- Declaring a page level public method --gt
  • lt! public String palindrome(String inString)
  • String outString ""
  • for (int i inString.length() i gt 0 i--)
  • outString outString inString.charAt(i-1)
  • return outString
  • // palindrome
  • gt
  • lt-- Multiple declarations --gt
  • lt! int maxCounts 50
  • double avagadrosNum 6.02E23
  • gt

40
Use
  • Another use for declarations(??) is accessing
    the jspInit() and jspDestroy() life cycle
    methods. As you will recall from the Life Cycle
    Concept section, jspInit() is called immediately
    after the JSP Servlet has been instantiated(??)
    but before any requests are processed.

41
Use
  • The jspDestroy() method is called immediately
    prior(???) to the Servlet destruction. Both
    methods are automatically created by the JSP
    container however, you can override the
    default(??) methods and include code that should
    be called on page initiation or destruction.
    These methods are rarely used, but they can be
    very useful for initializing(???) and
    releasing(??)resource variables such as
    javax.sql.DataSource objects.

42
The special life cycle control methods
  • lt-- Example jspInit() and jspDestroy() methods
    --gt
  • lt! public void jspInit()
  • //Insert code here
  • public void jspDestroy()
  • //insert code here
  • gt

43
A Warning
  • Method declarations are added as independent
  • sections to the code outside of the main
    _jspService() method.
  • As with any Java class, declarations cannot
    reference(??) any variable or method that has not
    already been declared. In particular, declared
    methods cannot take advantage of(??) any of the
    structure built into _jspService().

44
Within a declared method, you cannot
  • Write HTML directly (using scriptlet tags lt
    gt).
  • Use expressions
  • Use implicit(??) objects
  • Reference a declared(??) variable or method
    that was not declared earlier in the JSP.

45
Work around
  • You can work around most of the limitations by
    having your declared(??) methods return a String
    value containing HTML text.

46
A declared method for writing a table row
  • lt! public String tableRow(String cellValues)
  • String tableHtml "ltTRgt"
  • for (int i0 iltcellValues.length() i)
  • tableHtml "ltTDgt" cellValuesi "lt/TDgt"
  • tableHtml "lt/TRgt"
  • return tableHtml

47
code as the argument(??) in an expression.
  • lt String girlNames yang", liu", "Lady
    xing"
  • String girlAges "3 yrs.", "5 yrs.", "3.5
    yrs"gt
  • This table lists the names of girls I have met
    and their age
  • ltTABLEgt
  • lttableRow(girlNames)gt
  • lttableRow(girlAges)gt
  • lt/TABLEgt

48
Expressions
  • An expression is an in-line function(????) that
    writes text to the buffer. Each set of expression
    tags encloses a fragment of Java code that must
    evaluate(???) to a String. Expressions are
    enclosed in either lt gt orltjspexpressiongt
    lt/jspexpressiongt tags.
  • The JSP container will generate compilation
    errors if your expression cannot be converted
    into a String,
  • or if you have placed a semicolon(??) at the end
    of your Java statement.

49
Types of expressions
  • lt-- Using the basic expression script tags--gt
  • lt! String text "Wow!"gt
  • This is some html and an expression lttextgt
    lt/brgt
  • lt-- The same thing using the XML tags--gt
  • ltjspdeclarationgtString text "Wow!"lt/jspdeclar
    ationgt lt/brgt
  • This is some html and an expression
  • ltjspexpressiongttextlt/jspexpressiongt
  • lt-- And finally, using the out object --gt
  • lt! String text "Wow!"gt
  • This is some html and an expression
    ltout.print(text)gt lt/brgt

50
Note
  • The script tags are used most often.
    Nevertheless, there are times
  • when using out.println() or out.print() makes
    sense, particularly
  • when you are in the middle of a scriptlet where
    adding an extra set of
  • lt gt tags would make the code confusing(??).

51
Yesterdays Recap(??) Tag Descriptions
52
Scriptlets
  • A scriptlet(????) is a section of Java code
    embedded(??) in HTML. A scriptlet can include any
    valid(???) Java code.

53
Use
  • Declare(??) new variablesThe variables are
    scriptlet level and cannot be accessed outside
    of the scriptlet.
  • Instantiate(??) external classesYou can access
    JDBC(java?????), RMI(????), JNDI(java???????),
  • or any other package of Java classes from inside
    a scriptlet, provided
  • you have included the package with the correct
    directive(??).
  • Access JavaBeansYou can access the
    properties(??) and methods of a JavaBean inside a
    scriptlet. Another method for using Java-Beans is
    covered(??) in the Forms(??), JavaBeans, and JSP
    topic later in this chapter.

54
Scriptlets
  • Scriptlets are declared using the lt gt script
    tags,or the ltjspscriptletgt lt/jspscriptletgt XML
    equivalents(????).

55
Scriptlets
  • lt-- This is a simple scriptlet --gt
  • lt! String colors "red", "green", "blue"gt
  • ltTABLEgt
  • ltTRgt
  • ltfor (int i 0 i lt colors.length i)
  • out.println("ltTDgt" colorsi "lt/TDgt")
  • gt
  • lt/TRgt
  • lt/TABLEgt

56
Escape Characters (???)
  • Every computer language has reserved characters,
    such as double quote (), single quote (),
    forward slash (/), and the various forms of
    parentheses(???)
  • ().

57
Common escape characters
58
A simple JSP example
  • lt // assume I have an arraylist of products. gt
  • ltTABLEgt
  • ltTRgt
  • ltTHgtProduct lt/THgt
  • ltTHgtProduct Namelt/THgt
  • ltTHgtUnit Pricelt/THgt
  • lt/TRgt
  • lt
  • Iterator it products.iterator()
  • while (it.hasNext())
  • gt
  • ltTRgt
  • lt Product aProduct (Product) it.next()gt
  • ltTDgtlt aProduct.getProductId()gtlt/TDgt
  • ltTDgtlt aProduct.getProductName()gtlt/TDgt
  • ltTDgtlt aProduct.getUnitPrice()gtlt/TDgt
  • lt/TRgt
  • lt gt

59
Debugging JSP
  • Some containers provide probable line numbers
    for compilation errors.
  • Check your container log files.
  • System.out output is redirected to the
    console(???) or to a logfile(????)

60
DESIGN
  • Use method declarations to move code out of the
    main part of your page. Be careful with
    variables.
  • Write the Java code into class objects,
    JavaBeans, and Servlets.
  • Take advantage of the ltjspuseBeangt tags
  • Use include directives

61
Model-View-Controller
  • When developing a user interface(??), it is very
    important to separate(??) common
    responsibilities(??)into separate objects. The
    most common division of responsibility is known
    as Model-View-Controller (MVC) paradigm, more
    accurately termed Presentation(??)-Abstraction-Con
    troller (PAC).

62
Components
  • The Model(??) (Abstraction) represents the
    underlying application objects that access the
    database, represent business logic, etc.
  • These objects are typically JavaBeans, EJBs, or
    regular Java
  • classes.
  • The View (Presentation) is responsible for
    rendering the display.
  • Typically this is a JSP that uses helper objects,
    data objects, and
  • custom tag libraries.
  • The Controller is responsible for controlling
    application flow and
  • Mediating(??) between the abstraction and
    presentation layers. The controller is typically
    a Servlet.

63
Think
  • The client accesses(??) the controller (Servlet)
    as the main page, or as the target action of a
    form submission.
  • The controller in turn accesses the
    underlying(???) business logic and database code
    of the abstraction(??) layer(?) and sets various
    data and helper objects into scoped(??)
    attributes on the Servlet (JavaBeans, EJBs, Java
    classes).
  • Finally, the request is redirected to the
    appropriate view (JSP) using RequestDispatcher.for
    ward().

64
Model-View-Controller
65
MVC Example
66
Putting It All Together
67
Key
  • Struts (Framework) Scalability(????)
  • MVC Maintainability(????)

68
  • Directives and Actions

69
Directives and Actions
  • Directives(??) and actions extend the basic JSP
    syntax. Directives are instructions from the JSP
    to the container that can be used to set the page
    properties, to import(??) Java classes and
    packages, and to include external(???) web pages
    and custom tag libraries.

70
directives
  • PageThe page directive sets the attributes of
    the page and provides the functionality(???) for
    importing Java classes.
  • IncludeThe include directive adds
    modularity(???) to JSP by allowing you to include
    the contents of external pages in your JSP.
  • TaglibThe Taglib directive is used for Custom
    Tag Libraries.

71
Actions
  • Instruct the container to perform specific tasks
    at runtime.
  • These actions range from forwarding control to
    another
  • page to generating a new JavaBean for use in the
    page.

72
Types
  • ForwardThis action transfers(??) control to a
    new web page.
  • IncludeThe include action temporarily(??)
    transfers control to a new page, performs the
    actions on the page, includes the output in the
    original page, and returns control to the
    original page.
  • BeansBean actions allow creation and use of
    JavaBeans inside a JSP. The bean actions are
    explained in the Forms, JavaBeans, and JSP topic.
  • Plug-in(??)The ltjspplugingt action is used for
    working with Java applets.
  • Applets are client-side(???) programs that run on
    a browser.
  • Applets have generally fallen out of favor

73
Page Directive
  • The page directive has eleven different
    attributes(??) that control everything
  • from the scripting language(????) to the classes
    and packages imported into
  • the page.

74
Page directives
  • lt_at_ page attribute1"value1" attribute2"value2"
    ...gt
  • lt-- XML equivalent. Note that the XML equivalent
    uses
  • attributes rather than an open/close tag
    structure. --gt
  • ltjspdirective.page att1"value1" att2"value2"
    .../gt

75
Note
  • Except for import, each attribute(??) can be
    used only once in a page directive.
  • The attribute order is unimportant.

76
Page directive attributes
77
Page directive attributes
78
import
  • Using the import directive is just like using
    import in a Java class file. This is the most
    commonly used page directive.
  • You can import multiple(??) classes and packages
    by separating(??) the names with a comma(??).
  • lt_at_ page import"java.sql." gt
  • lt_at_ page import"java.util.properties,
    java.text."gt

79
contentType
  • The contentType directive is usually left at the
    default, unless you are working with different
    character sets or writing XML content.
  • lt_at_ page contentType"text/XML" gt

80
errorPage
  • The errorPage attribute will redirect(???) the
    client to a new JSP when an unhanded(??)
    exception(??) is thrown. The JSP error page must
    have the isErrorPage directive set to true.
  • lt_at_ page errorPage"/webdev/admin/error.jsp" gt

81
isErrorPage
  • If this attribute is set to true, the page can
    access the exception implicit object.
  • lt_at_ page isErrorPage"true" gt

82
Include Directive
  • The include directive allows you to
    modularize(???) your web pages and include the
    entire contents of one file in another. The
    include directive can be used any number of times
    in a JSP.
  • lt_at_ include file"urltoFile" gt
  • lt-- XML equivalent, once again, uses attributes
    instead of
  • open/close tag --gt
  • ltjspdirective.include file"urlToFile" /gt

83
MultipartJSP pages from common components.
84
Forward Action
  • The forward action permanently(??) transfers
    control to another location
  • using a RequestDispatcher. Unlike directives and
    scripting elements,
  • the forward action does not have a scripting
    syntax. All actions are
  • launched using an XML syntax
  • ltjspforward page"urlToPage" /gt

85
Forward Action
  • The forward action supports runtime definition
    of the page attribute. For
  • example, the following code will forward the
    page to a URL defined as
  • msgs/error401.html if the errCode variable is
    equal to 401
  • ltjspforward page'lt "msgs/error" errCode
    ".html" gt' /gt

86
ltjspforwardgt
  • The ltjspforwardgt action allows the request to be
    forwarded to another JSP, to a Servlet, or to a
    static resource. This is particularly(???) useful
    when you want to separate the application into
    different views, depending on(??) the intercept
    request. The syntax is
  • ltjspforward pageURL /gt
  • or
  • ltjspforward pageURL gt
  • ltjspparam nameparamName valueparamValues
    /gt
  • ..
  • lt/jspforwardgt

87
ltjspforwardgt
  • The resource to which the request is being
    forwarded(??) must be in the same context as the
    JSP dispatching(??) the request.

88
ltjspforwardgt
  • Execution in the current JSP stops when it
    encounters a ltjspforwardgt tag, the buffer is
    cleared, and the request is modified( this is a
    server-side redirect and the response(??) buffer
    is cleared when it is processed) to assimilate
    any additionally specified parameters(??) in the
    same way as described(??) for the ltjspincludegt
    action.

89
Program 2
  • lthtmlgt
  • ltheadgt
  • lttitlegtForward action test pagelt/titlegt
  • lt/headgt
  • ltbodygt
  • lth1gtForward action test pagelt/h1gt
  • ltform method post actionforward. Jspgt
  • ltpgtPlease enter your username
  • ltinput typetext nameusernamegt
  • ltbrgtand password
  • ltinput type password
    namepasswordgt
  • lt/pgt
  • ltpgtltinput type submit valueLog
    ingt
  • lt/formgt
  • lt/bodygt
  • lt/htmlgt

90
Forward.jsp is the first JSP page we have seen
that contains no HTML code
  • lt
  • if((request.getParameter(username).equals(
    Richard))
  • (request.getParameter(password).equals
    (xyzzy)))
  • gt
  • ltjspforward pageforward2.jsp/gt
  • lt else gt
  • lt_at_ include fileforward.htmlgt
  • lt gt

91
  • lthtmlgt
  • ltbodygt
  • ltpgtWelcome ,
  • ltrequest.getParameter(username)gt
  • lt/bodygt
  • lt/htmlgt

92
Include Action
  • Unlike the forward action, the include action
    temporarily transfers control to another page on
    the local server. The output of the second page
    is included in the first page, and control is
    returned as soon as the second page has finished.
  • The include action temporarily transfers(??)
    control to
  • the second web page, which must be a complete
    page. The include directive simply
    incorporates(??) the contents of the second page
    directly into the calling page.

93
Include Action
  • ltjspinclude page"urlToPage" flush"true" /gt
  • This action also supports runtime definition of
    the page attribute.
  • An include action is called using an XML-based
    syntax with two attributes, the page URL and
    flush.
  • The flush parameter is added for future
    Expansion(??) of the specification.

94
ltjspincludegt
  • This action allows a static or dynamic(???)
    resource, specified by a URI, to be included in
    the current JSP at request processing time.
  • An included page has access to only the JspWriter
    object, and it cannot set headers or cookies.
  • A request-time exception will be thrown if this
    is attempted. If the page output is buffered then
    the buffer is flushed(??) prior to the inclusion.

95
ltjspincludegt
  • The include action pays a small penalty(??) in
    efficiency, and precludes(??) the included page
    from containing general JSP code. The syntax of
    the ltjspincludegt action is
  • ltjspinclude pageURL flushtrue /gt
  • or
  • ltjspinclude pageURL flushtrue gt
  • ltjspparam nameparamName valueparamValue
    /gt
  • ..
  • lt/jspincludegt

96
ltjspincludegt
Attribute Description
page The resource to include.
flush In JSP 1.1 this value must always be true, and false is not supported. If the value is true, the buffer in the output stream is flushed before the inclusion is performed.
97
ltjspincludegt
  • A ltjspincludegt action may have one or more
    ltjspparamgt tags in its body, providing
    additional name-value pairs.
  • The included page can access the original(???)
    request object, which will contain both the
    original parameters, and the new parameters(??)
    specified using the ltjspparamgt tag.
  • If the parameter names are the same, the old
    values are kept intact, but the new values take
    precedence(??) over the existing values.

98
Include type Syntax Done when Include content Parsing(??)
directive lt_at_ include filefilename gt Compilation time static Parsed by container
action ltjspinclude pagefilename /gt Request processing time. Static or dynamic Not parsed but included in place
99
Program
  • lthtmlgt
  • ltheadgt
  • lttitlegtInclude Action test pagelt/titlegt
  • lt/headgt
  • ltbodygt
  • lth1gtInclude Action test pagelt/h1gt
  • lth2gt Using the include directivelth2gt
  • lt _at_ include file included2.htmlgt
  • lt_at_ include file include2.jspgt
  • lth2gtUsing the include actionlth2gt
  • ltjsp include page included2.html
    flushtrue/gt
  • ltjspinclude pageincluded2.jsp
    flushtrue/gt
  • lt/bodygt
  • lthtmlgt

100
Passing Parameters
  • When you use either the forward or include
    action, if the receiving page is a JSP, it
    automatically has access to the Request and
    Session implicit
  • objects from the calling page.
  • If you need to pass extra parameters to the
    receiving page, you can insert
  • ltjspparamnameparamname valueparamvalue /gt
    into the action.

101
Passing parameters with forward
  • ltjspforward page"checkout.jsp"gt
  • ltjspparam name"enable" value"true" /gt
  • ltjspparam name"uniqueID" value"ltuniqueIDgt"
    /gt
  • lt/jspforwardgt

102
EXAMPLES
  • ltjspinclude page"/common/Header.jsp"/gt
  • lt String username session.getAttribute("usernam
    e")
  • if (username null)
  • // User is not logged in.
  • gt ltjspforward page"/Login.jsp"/gt lt
  • gt
  • ltjspinclude page"/common/Footer.jsp"/gt

103
DESIGN
  • The import attribute of the page directive is
    your best friend. Use it to move all application
    code into Java classes and off your page.
    Standalone
  • Java classes are much easier to test and debug.
  • build a simple header file with your logo(???)
    and contact information. Include the file in all
    JSP.
  • Any place you have HTML that is repeated between
    pages, you can use an include directive instead.

104
Implicit Objects
  • The JSP container provides access to a set of
    implicit objects. These objects
  • are extensions of common Servlet components and
    provide some
  • of the basic tools necessary to build real
    applications with JSP.

105
Implicit object base classes
106
Implicit Objects
  • The Servlet API includes interfaces(??) that
    provide convenient(???) abstractions(??) to the
    developer such as HttpServletRequest,
    HttpServletResponse, HttpSession, etc. JSP
    provides certain implicit objects, based on the
    Servlet API. These objects are accessed using
    standard variables(??), and are automatically
    available for use in your JSP without writing any
    extra code.

107
Implicit(??) Objects
  • The implicit objects available in JSP are
  • request
  • response
  • out
  • session
  • pageContext
  • application
  • config
  • page

108
The request object
  • The request objects represents(??) the request
    that triggered(???) the service() invocation(??.
    It is the HttpServletRequest that provides access
    to incoming HTTP headers, and request
    parameters(??), among other things.

109
The response object
  • The response object is the HttpServletResponse
    instance(??) that represents the servers
    response to the request.

110
pageContext
  • Provides single point of access to many of the
    page attributes(??)

111
Session(??) object
  • Used to manage the session
  • Note
  • session attribute of the page directive should
    be true

112
application object
  • Access to servlet context

113
out object
  • Buffered(??) version of the PrintWriter
  • Type is JspWriter

114
Config(??) object
  • Object of ServletConfig

115
page
  • Type is object
  • Like the this keyword in a class

116
Overlapping(??) Objects
  • To store attributes in a session object,
  • ltsession.setAttribute("number", new
    Float(42.5))gt
  • To retrieve the parameters from the request
    object,
  • lt_at_ page import"java.util." gt
  • lt Enumeration params request.getParameterNames(
    )gt
  • ltwhile (params.hasMoreElements())
  • out.print(params.nextElement() "/t")
  • gt

117
Features of these objects
  • Attribute accessUse the setAttribute(),
    getAttribute(),
  • and removeAttribute() methods on the session,
    application,
  • and request objects.
  • HTTP parameter accessYou can access the HTTP
    header parameters
  • from the request object, and set them on the
    response
  • object. This includes access to cookies.
  • Page flowYou can use the sendRedirect(),
    encodeURL(), and
  • encodeRedirectURL() methods of the response
    object to redirect
  • the browser(???) to a new page.

118
PageContext (javax.servlet.jsp.PageContext)
  • The PageContext object is an abstract helper
    object intended for use
  • by the container. However, the PageContext can be
    used to store attributes
  • (like session, request, and application) in the
    page scope. The
  • PageContext object can also be used to access the
    other implicit objects
  • (e.g., the getRequest() method returns the
    Request object) and perform
  • dispatch methods (forward and include), which are
    identical(???) to the forward
  • and include actions.

119
setAttribute(), getAttribute(), removeAttribute()
  • lt//sets Session attribute named "Test"
  • pageContext.setAttribute("BookTitle", "J2EE",
  • PageContext.SESSION_SCOPE) gt

120
getAttributeNamesInScope (scope)
  • This method returns a
  • Java.util.Enumeration(??) object with the names
    (keys) of all of
  • the attributes in the specified scope.

121
findAttribute(key)
  • This method searches across all scopes
  • and returns the first instance of the named
    attribute. The scope search order is page,
    request, session (if valid), and application.
  • This is very useful if you have a default(??)
    value (in application
  • scope) that can be overridden by a local
    preference (session scope). If no attribute is
    found, null is returned.

122
getAttributeScope(key)
  • Returns the scope for the named attribute.
  • If the attribute is not found, this returns an
    integer value of 0.

123
Out (javax.servlet.jsp.JspWriter)
  • The response object contains the headers sent to
    the browser, the out object represents the actual
    output stream and body of the response
  • (i.e., the page buffer). The out object extends
    java.io.Writer but incorporates many of the
    methods from java.io.PrintWriter.

124
Writing to the Buffer
  • The out object is an implementation of
    JspWriter, which extends java.io.Writer. Many of
    these methods for writing to the buffer should be
    familiar from standard Java IO access.

125
print()
  • Writes data to the buffer(???), but does not add
    a line separator.

126
println()
  • Writes data to the buffer and adds a line
    separator.

127
clear()
  • Clears the buffer and throws a
    java.io.IOException if
  • data has already been flushed to the client.

128
clearBuffer()
  • This is almost identical to out.clear(), except
  • that it will not throw an exception(??) if data
    has already been flushed.

129
newLine()
  • This method writes a platform-specific line
    separator.
  • Using out.print() followed by out.newLine() is
    equivalent to using out.println().

130
flush()
  • This flushes(??) the output buffer and output
    stream(?), sending all of the queued data to the
    client.

131
close()
  • This closes the output stream(???), flushing any
    contents. If you use out.close(), you will not be
    able to write any more data
  • to the client from this page.

132
Describing the Buffer
  • isAutoFlush()Boolean value indicating whether
    buffer is automatically flushed when it is
    filled.
  • lt_at_ page autoFlush"true" gt

133
getBufferSize()
  • Returns the buffer size in bytes. If
  • autoFlush() is true, it is possible to have a
    buffer size of 0.
  • lt_at_ page bufferSize"12kb" gt

134
getRemaining()
  • Returns the size of the remaining buffer(???) in
    bytes.

135
Exception (java.lang.Throwable)
  • The exception object is available only on pages
    that have the isError- Page attribute (from the
    page directive) set to true. By default, this
    value is false, but you can adjust the setting
  • lt_at_ page isErrorPage"true" gt

136
getMessage()
  • Returns a string with the descriptive(???) error
    message (if there is one).

137
printStackTrace()
  • Prints the execution stack(??) to the specified
    buffer.

138
toString()
  • Returns a string with the specific class name of
    the exception and the message. For example
    IOException File Not
  • Found.
  • lt_at_ page errorPage"util/error.jsp" gt

139
A simple error page
  • lthtmlgt
  • lt_at_ page isErrorPage"true" gt
  • ltbodygt
  • An unexpected exception occurred ltbr/gt
  • ltexception.toString()gt ltbr/gt
  • The stack trace is ltbr/gt
  • ltexception.printStackTrace(new
    java.io.PrintWriter(out))gt
  • lt/bodygt
  • lt/htmlgt

140
Implicit object example
  • ltHTMLgt
  • ltBODYgt
  • lt ProductInformation productInfo
    (ProductInformation)
  • session.getAttribute("productInfo")
  • String requestType (String)
  • request.getAttribute("requestType")
  • Integer hitCount (Integer)
  • application.getAttribute("hitCount")
  • if (requestType null productInfo null)
  • throw new JspException(
  • "Invalid request type, or missing
    information.")
  • else if (requestType.equals("Edit"))
  • // Render HTML form for editing productInfo
  • else if (requestType.equals("Read"))
  • // Render HTML table for displaying productInfo
  • gt
  • This page has been viewed lthitCountgt times
    since the last restart.
  • ltBODYgt
Write a Comment
User Comments (0)
About PowerShow.com