Introduction to JavaServer Pages - PowerPoint PPT Presentation

1 / 66
About This Presentation
Title:

Introduction to JavaServer Pages

Description:

BODY BGCOLOR='YELLOW' TEXT='RED' LINK='BLACK' VLINK='BLUE' ALINK='YELLOW' ... You can set the ALIGN, BGCOLOR, VALIGN (vertical alignment) ... – PowerPoint PPT presentation

Number of Views:47
Avg rating:3.0/5.0
Slides: 67
Provided by: edmun2
Category:

less

Transcript and Presenter's Notes

Title: Introduction to JavaServer Pages


1
Introduction to JavaServer Pages
  • CMT3332
  • Lecture 3

2
What is JavaServer Page (JSP) and Servlet?
  • JSPs are web pages with embedded Java code
  • The Java code is executed on the server before
    the page is returned to the browser
  • Presentation-oriented
  • Servlets are pure Java classes
  • Servlets allow the programmer to work directly -
    requests are made to a Web Server and responses
    containing the contents are returned to a client
  • Designed to perform lower-level functions that
    work with data or implement business models

3
HTML Basic
  • The constructing blocks of a web page is HTML
    code
  • HTML is HyperText Markup Language
  • The format of the web page is determined by HTML
    tags
  • An HTML tag is embedding in the angled bracket lt
    gt
  • A closing HTML tag will have a stroke following
    the open bracket lt/ gt
  • As JSPs are also web pages, we need to know the
    basis of HTML before coding JSPs
  • To know more about HTML code, you can visit
  • http//www.htmlhelp.com/reference/html40/

4
HTML tags
  • ltHTMLgtlt/HTMLgt
  • Mark the start and end of an HTML file
  • ltHEADgtlt/HEADgt
  • The header of an HTML file. The header may
    contain ltTITLEgt, ltMETAgt, ltSTYLEgt, ltBASEgt and
    other details.
  • ltBODYgtlt/BODYgt
  • The body of an HTML file. We can define the
    following attributes for the body text
  • BACKGROUND background pic
  • BGCOLOR background color
  • TEXT text color
  • LINK link color
  • VLINK visited link color
  • ALINK active link color

5
Example of Basic HTML tags
  • ltHTMLgt
  • ltHEADgt
  • ltTITLEgttest for HTML, HEAD and BODY lt/TITLEgt
  • lt/HEADgt
  • ltBODY BGCOLOR"YELLOW" TEXT"RED" LINK"BLACK"
    VLINK"BLUE" ALINK"YELLOW"gt
  • test for HTML, HEAD and BODY ltBRgt
  • ltA HREF"http//www.yahoo.com"gtFrom here to
    Yahoolt/agt
  • lt/BODYgt
  • lt/HTMLgt

6
Font Tags
  • ltFONTgtlt/FONTgt
  • Attributes
  • SIZE size is based on a seven-point scale. You
    can use absolute value or relative value (e.g. 2
    or 1)
  • COLOR you can use named color or hexadecimal
    value starting with (e.g. FFFFFF represents
    white)
  • FACE the name of the font (case-sensitive)
  • Example
  • ltFONT SIZE5 COLOR"BLUE" FACE"Arial"gtArial
    Textlt/FONTgt

7
Styling Tags
  • Styling Tags
  • ltTTgtlt/TTgt - Monospaced
  • ltIgtlt/Igt - Italic
  • ltBgtlt/Bgt - Bold
  • ltUgtlt/Ugt - Underlined
  • ltSgtlt/Sgt - Strikeout
  • ltBIGgtlt/BIGgt - Larger font size (size 1)
  • ltSMALLgtlt/SMALLgt - Smaller font size (size 1)
  • Heading Tags ltH1gtlt/H1gt till ltH6gtlt/H6gt
  • Standard headings with automatic line feed
  • Attribute ALIGN you can set the alignment to
    LEFT, RIGHT, CENTER and JUSTIFY
  • Example ltH1 ALIGN"CENTER"gtWelcomelt/H1gt

8
Paragraph Styling Tags
  • ltPgtlt/Pgt used to format a paragraph, you can use
    ALIGN attribute to set the alignment
  • ltBRgt jumps to the next line
  • ltNOBRgtlt/NOBRgt makes the embedded text keep in
    the same line
  • ltHRgtlt/HRgt creates a "horizontal rule"
  • You can set ALIGN, SIZE and WIDTH (using absolute
    or percentage value) of the rule
  • ltPREgtlt/PREgt keeps the original spacing in the
    text (other format will treat all whitespaces as
    1 single space)
  • ltCENTERgtlt/CENTERgt keeps the block of text center
    aligned

9
Example for P, BR, and NOBR
  • ltHTMLgt
  • ltHEADgt
  • ltTITLEgtExample of P/BR/HRlt/TITLEgt
  • lt/HEADgt
  • ltBODYgt
  • Line 1
  • ltPgt Line 2 ltBRgt
  • Line 3 lt/Pgt
  • ltHR ALIGNRIGHT WIDTH50 SIZE10gt
  • ltNOBRgt Line 4.
  • Line 5. Line 6. Line 7. lt/NOBRgt
  • lt/BODYgt
  • lt/HTMLgt

10
Image Tag
  • ltIMGgt for holding images (GIF, JPEG)
  • Attributes SRC (source file), ALT (alternative
    text), WIDTH, HEIGHT, BORDER (if set to 0, no
    border is shown)

11
Table Tags
  • ltTABLEgtlt/TABLEgt defines a table
  • You can set the attributes BGCOLOR, BORDER,
    ALIGN, WIDTH, CELLSPACING, CELLPADDING
  • Cell spacing is the spacing between spaces
  • Cell padding is the spacing between the text and
    the border
  • ltCAPTIONgtlt/CAPTIONgt forms a caption to describe
    the table
  • ltCAPTION ALIGNTOPgt Table 1.1 lt/CAPTIONgt
  • Alignment can be TOP, BOTTOM, RIGHT and LEFT
  • Within the table, we can define the header, rows
    and cells

12
Header, Rows and Cells
  • ltTRgtlt/TRgt defines a row
  • You can set the ALIGN, BGCOLOR, VALIGN (vertical
    alignment)
  • ltTDgtlt/TDgt defines a cell within a row
  • You can set the ALIGN, VALIGN, WIDTH, HEIGHT,
    BGCOLOR, NOWRAP and other attributes in the cell
  • ROWSPAN and COLSPAN can set the number of rows
    and columns that the header cell will span
  • ltTHgtlt/THgt defines a header cell within a row
  • A header cell is similar to an ordinary cell, but
    it serves as the header of a column, with bolded
    fonts

13
Example of Table in HTML
  • lthtmlgtltheadgt
  • lttitlegtExample of Tablelt/titlegtlt/headgt
  • ltbodygt
  • lttable Border3 Width50gt
  • ltTRgt ltTH ColSpan5gtStudent Listlt/THgtltTH
    RowSpan3 ValignBottom NoWrapTruegtRemarklt/THgt
    lt/TRgt
  • ltTRgt ltTH RowSpan2 Width50gt Student Nolt/THgtltTH
    RowSPan2 Width50gtNamelt/THgtltTH
    ColSpan3gtHistorylt/THgtlt/TRgt
  • ltTRgtltTHgtPri. Schlt/THgtltTHgtSec.
    Schlt/THgtltTHgtUniversitylt/THgtlt/TRgt
  • ltTRgtltTDgt123456lt/TDgtltTDgtJohn Chanlt/TDgtltTD
    NoWrapTruegt1992lt/TDgtltTD NoWrapTruegt1999lt/TDgt
    ltTD NoWrapTruegt2002lt/TDgtltTDgt lt/TDgtlt/TRgt
  • lt/bodygtlt/htmlgt

14
The Anchor Tag
  • ltAgtlt/Agt Anchor Tag may be the most important tag
    in HTML, represents a hyperlink of the
    destination of a link
  • HREF attribute shows the URL of the hyperlink
  • TARGET attribute defines in which frame the
    contents of the link should appear value can be
    _blank (new window), _self (current frame),
    _parent and _top
  • NAME attributes represents a destination of a
    link, or a bookmark
  • You can add XXX to you URL to make the browser
    to go to a specific bookmark in a page (if the
    bookmark exists)

15
JSP behind the Scene
  • When the browser asks the Web server for a JSP,
    the Web server passes control to a JSP container
  • The container provides the runtime environment
    and other services the JSP needed
  • At the first time a JSP is invoked, the JSP
    container will convert it into a servlet
    (HttpJspPage) as an executable unit
  • The container will normally check if a servlet
    for that JSP already exists and updated
  • The contents of the JSP file will eventually
    convert to codes in a method _jspService (unless
    otherwise specified in the code) in the servlet
  • In Tomcat, the servlet files are stored deep in
    the work folder in your Tomcat path.

16
Basic JSP Tags
  • lt gt tags (scriptlet tag) in a JSP file
    indicates the presence of Java code within the
    HTML
  • Codes inside the scriptlet is sent verbatim
  • HTML codes will be encoded to be the printout of
    a Java output statement
  • Both scriptlet codes and HTML codes will be
    placed in the _jspService method
  • lt gt tag (expression tag) displays a value
    directly to the HTTP client
  • It actually calls a out.write command to print
    out the text, i.e., it will be also placed in the
    _jspService method
  • Be careful! There is no space between lt and

17
Inserting Comments to a JSP
  • lt!-- It is a HTML comment --gt
  • The comment will appear in the HTML code, but not
    in the browser
  • lt-- It is a JSP comment --gt
  • The comment will not appear in the servlet code
    generated.
  • It is useful to remove a section of code from a
    JSP
  • You can always use Java comments as in an
    ordinary Java code
  • Example lt // This is a Java comment gtlt /
    gt This will be commented out. lt / gt

18
Declaring Methods and Variables
  • You cannot use lt gt tag to declare a method
  • The contents inside lt gt tag will be put in the
    method _jspService
  • We can't declare a method within another method
  • lt! gt tag (declaration tag) is used to declare a
    method that appears at the top of the resulting
    servlet class
  • You may also declare an instance variable that
    may be accessed by all methods using lt! gt tag
  • out is an implicit output object (JspWriter)
    defined by JSP specification however, it is
    defined within the _jspService method and cannot
    be used in any method

19
Built-in JSP Objects
  • JSP API provides a series of built-in objects
    (implicit objects) to access the information
    provided by the Servlet objects of different
    classes
  • They are created at the beginning of a page (in
    the _jspService method) and directly reference
    objects in the underlying servlet
  • They are only available to scriptlets and
    expressions
  • These JSP objects will be further discussed in
    the coming lecture.

20
Built-in JSP Objects and the Corresponding
Servlet Classes
21
Servlet Basis
  • Every servlet must implement the
    javax.servlet.Servlet interface
  • Most servlets implement the interface by
    extending javax.servlet.http.HttpServlet
  • An HTTP servlet overrides the doPost( ) and/or
    doGet( ) method.
  • It is an usual practice that we implements one of
    the above methods and call the method within the
    other one. E.g., doPost will only call doGet
    which have all the implementation

22
A Sample Java Servlet
  • import java.io.
  • import java.text.
  • import java.util.
  • import javax.servlet.
  • import javax.servlet.http.
  • public class MyServlet extends HttpServlet
  • public void doGet (HttpServletRequest request,
    HttpServletResponse response) throws
    ServletException, IOException
  • PrintWriter out
  • String title "MyServlet Output"
  • response.setContentType("text/html")
  • out.println("ltHTMLgtltHEADgtltTITLEgt")
  • out.println(title)
  • out.println("lt/TITLEgtlt/HEADgtlt/HTMLgt")
  • out.println("ltH1gt" title "lt/H1gt")
  • out.println("ltPgtHello World!")
  • out.println("lt/BODYgtlt/HTMLgt")
  • out.close()

23
Compiling the Servlet
  • Make sure the servlet classes are in your
    classpath
  • In Tomcat, you use servlet-api.jar in the
    common\lib folder
  • Set it into the classpath environment variable or
    use classpath option while compiling
  • Compile the servlet using the following command
  • java d . XYZServlet.java
  • -d option specifies the destination folder

24
Using invoker to Run a Servlet
  • By default, Tomcat does not enable the invoker
    servlet
  • It is not enable in default because it is
    insecure. A person can force your container to
    load a class that may harm your server
  • You need to uncomment some parts in the
    configuration file web.xml in the conf folder in
    order to use invoker
  • Uncomment the servlet declaration starts
    withltservletgt ltservlet-namegt invoker
    lt/servlet-namegt
  • Uncomment the servlet mapping for the
    invokerltservlet-mappinggtltservlet-namegtinvokerlt/s
    ervlet-namegt
  • Place the compiled servlet class file to a path
    defined
  • The Servlet can then be invoked through the URL
  • http//localhost8080/servlet/XYZServlet

25
doGet and doPost in HttpServlet
  • HttpServlet is specially designed with request
    and response object geared towards HTTP
  • HttpServlet provides separate methods for
    handling different type of HTTP requests
  • doGet(HttpRequest request, HttpResponse response)
  • doPost(HttpRequest request, HttpResponse
    response)
  • Servlet can send back a response of all types
    (even JPG is possible)
  • Set the content type before calling getWriter
  • Usually, we use PrintWriter for the output of the
    servlet

26
Deploy a Servlet through a Web Application
  • One safer way to invoke Servlet is to pack it
    with related classes, JSPs, JARS and other files
    in a single folder and deploy it into the
    container with a deployment descriptor
  • The deployment can be done manually or using
    Tomat's administration tool
  • The whole process is called a Web Application
    Deployment
  • A web application can also be wrapped inside a
    WAR file.

27
JSP and Servlet API Specification
  • You can browse the following pages to explore the
    detail API of both JSP and servlet
  • Servlet API JavaDoc http//tomcat.apache.org/tomc
    at-5.5-doc/servletapi/index.html
  • JSP API JavaDoc http//tomcat.apache.org/tomcat-5
    .5-doc/jspapi/index.html

28
JSP Lifecycle
  • Phases of a JSP lifecycle
  • Compilation
  • Loading
  • Initialization
  • Execution
  • Cleanup

29
JSP Lifecycle - Compilation
  • When the browser asks the Web server for a JSP,
    the Web server passes control to a JSP container
    (or a servlet container)
  • The container provides the runtime environment
    and other services the JSP needed
  • At the first time a JSP is invoked, the JSP
    container will convert it into a servlet as an
    executable unit
  • The container will normally check if a servlet
    for that JSP already exists and updated
  • The compilation process involves first parsing
    the JSP, turning the JSP into a servlet and then
    compiling the servlet

30
JSP Lifecycle - Loading
  • A JSP/servlet can be loaded at three different
    times
  • when the server starts up
  • when the system admin asks the server to load the
    servlet
  • when a browser tries to access the servlet
  • You may need to make a change to web.xml in the
    conf folder of Tomcat to make the servlet load at
    start up
  • In case of a JSP, when the JSP file is request,
    it will automatically map the resource part of
    the URL to the compiled servlet stored in the
    servlet container

31
JSP Lifecycle - Initialization
  • To perform JSP-specific initialization, you need
    to override the jspInit method
  • public void jspInit()
  • For example, you can initialize database
    connection, open files and etc. in the jspInit
    method
  • You may also use the implict config and
    application object to configure your JSP

32
JSP Lifecycle Initialization
  • Another method to initialize the JSP file in a
    deployment descriptor
  • You can add a "servlet" descriptor for your JSP
    in your deployment descriptor and add your
    init-param elements
  • ltservletgt ltservlet-namegt HelloWorldJSP
    lt/servlet-namegt ltjsp-filegt /HellowWorld.jsp
    lt/jsp-filegt ...lt/servletgt

33
JSP Lifecycle Execution Cleanup
  • When a browser request a JSP, the JSP invokes the
    jspService method in the servlet representing the
    JSP.
  • JSP takes an HttpServletRequest and
    HttpServletResponse as its parameters
  • Cleanup is necessary only if the JSP is needed to
    be unloaded from the container
  • Override jspDestroy method to perform any
    cleanup, such as releasing database connections
    and close the files public void jspDestroy()

34
The HyperText Transfer Protocol (HTTP)
  • HTTP allows the transfering of web contents of
    virtually unlimited types.
  • The first version of HTTP, HTTP/0.9, was a simple
    protocol for raw data transfer.
  • The most widely used HTTP version is HTTP/1.0
  • Since then, an improved protocol, known as
    HTTP/1.1, has been developed and often adopted.
  • HTTP/1.1 is a far more extensive protocol than
    HTTP/1.0.
  • However, the basics of the protocol is well
    represented in the simpler HTTP/1.0.

35
HTTP Server and Client
  • HTTP is a connection-oriented, stateless,
    request-response protocol.
  • An HTTP server, or web server, runs on TCP port
    80 by default. (Tomcat uses port 8080 by default)
  • HTTP clients (web browsers) are processes which
    implements HTTP to interacts with a web server to
    retrieve documents in HTML.

36
HTTP Request and Response
  • HTTP is text-based the request and responses are
    character strings
  • Each request and response is composed of these
    parts, in order
  • The request/response line
  • A header section
  • A blank line
  • The body

37
The HTTP request
  • A client request is sent to the server after the
    client has established a connection to the
    server.
  • A request line is of the following form
  • ltHTTP methodgtltRequest-URIgtltprotocol
    specificationgt\r\n
  • where
  • ltHTTP methodgt is the name of a method defined for
    the protocol,
  • ltRequest-URIgt is the URI of a web document, or,
    more generally, a web object,
  • ltprotocol specificationgt is a specification of
    the protocol observed by the client, and
  • An example client request is as follows
  • GET /index.html HTTP/1.0

38
HTTP Methods in a client request
  • The HTTP method in a client request is a reserved
    word (in uppercase) which specifies an operation
    of the server that the client desires.
  • Some of the key client request methods are
    listed below
  • GET for retrieving the contents of web object
    referenced by the specified URI
  • HEAD for retrieving a header from the server
    only, not the object itself.
  • POST used to send data to a process on the
    server host.
  • PUT used to request the server to store the
    contents enclosed with the request to the server
    machine in the file location specified by the URI.

39
GET vs. POST
  • When you use GET, you are taking advantage of a
    performance hack
  • Server needs a little more work to process posted
    data
  • However, there is a limit to the length of
    pathname for a GET request (4KB)
  • If your form contains sensitive data, use POST
    rather than GET
  • A more secure way to send a sensitive data is to
    use HTTPS instead of HTTP

40
Request Header
  • The request header fields allow the client to
    pass additional information about the request,
    and about the client itself, to the server.
  • These fields act as request modifiers, with
    semantics equivalent to the parameters on a
    programming language method (procedure)
    invocation
  • A header is composed of one or more lines, each
    line in the form of
  • ltkeywordgt ltvaluegt\r\n

41
Request Header
  • Some of the keywords and values that may appear
    in a request header are
  • Accept content types acceptable by the client
  • User-Agent specifies the type of browser
  • Connection Keep-Alive can be specified so that
    the server does not immediately close a
    connection after sending a response.
  • Host host name of the server
  • An example request header is as follows
  • Accept /
  • Connection Keep-Alive
  • Host www.someU.edu
  • User-Agent Generic

42
Accessing Request Header
  • Using request.getHeader(HEADER-TYPE) in your
    JSP, you can create a different content according
    to the request header
  • Example
  • if (request.getHeader(USER-AGENT).indexOf( M
    SIE) gt 0)
  • // do IE specific stuff here
  • else
  • // do Netscape specific stuff here

43
Request Body
  • A request optionally ends with a request body,
    which contains data that needs to be transferred
    to the server in association with the request.
  • For example, if the POST method is specified in
    the request line, then the body contains data to
    be passed to the target process.

44
Example of HTTP Client Request
  • Example1
  • GET / HTTP/1.1
  • ltblank linegt
  • Example2
  • HEAD / HTTP/1.1
  • Accept /
  • Connection Keep-Alive
  • Host somehost.com
  • User-Agent Generic
  • ltblank linegt
  • Example3
  • POST /servlet/myServer.servlet HTTP/1.0
  • Accept /
  • Connection Keep-Alive
  • Host somehost.com
  • User-Agent Generic
  • ltblank linegt
  • Namedonaldemaildonald_at_someU.edu

45
The HTTP Server Response
  • In response to a request received from a client,
    the HTTP server sends it a response.
  • Like the request, an HTTP response is composed of
    these parts, in order
  • The response or status line
  • A header section
  • A blank line
  • The body

46
The Response Status Line
  • The status line is in the form of
  • ltprotocolgtltspgtltstatus-codegtltspgtltdescriptiongt\r\n
  • The status code designations are as follows
  • 100-199 Informational
  • 200-299 Client request successful
  • 300-399 Client request redirected
  • 400-499 Client request incomplete
  • 500-599 Server errors
  • Example 1 HTTP/1.0 200 OK
  • Example 2 HTTP/1.1 404 NOT FOUND
  •  

47
HTTP Response Header
  • The status line is followed by a response header.
    A response header is composed of one or more
    lines, each line in the form of
  • ltkeywordgt ltvaluegt\r\n
  • There are two types of response header lines
  • Response header lines
  • Entity header lines

48
Response and Entity Header Lines
  • Response header lines these header lines return
    information about the response, the server, and
    further access to the resource requested
  • Age seconds
  • Location URI
  • Retry-After dateseconds
  • Server string
  • WWW-Authenticate scheme realm
  • Entity header lines these header lines contain
    information about the contents of the object
    requested by the client, as follows
  • Content-Encoding
  • Content-Length
  • Content-Type type/subtype
  • Expires date
  • Last-Modified date
  • Cache-Control maxageseconds

49
HTTP Response Header
  • An Example response header is as follows
  • Date Mon, 30 Oct 2000 185208 GMT
  • Server Apache/1.3.9 (Unix) ApacheJServ/1.0
  • Last-modified Mon, 17 June 2001 164513 GMT
  • Content-Length 1255
  • Connection close
  • Content-Type text/html
  • The Content-Type specifies the type of the data,
    using the contents type designation of the MIME
    protocol.
  • The Content-Encoding specifies the encoding
    scheme (such as uuencode or base64) of the data,
    usually for the purpose of data compression.
  • The expiration date gives the date/time
    (specified in a format defined with HTTP)after
    which the web object should be considered stale
  • The Last-Modifed date specifies the date that the
    object was last modified.

50
HTTP Response Body
  • The body of the response follows the header and a
    blank line, and contains the contents of the web
    object requested.
  • HTTP/1.1 200 OK
  • Date Sat, 15 Sep 2001 065530 GMT
  • Server Apache/1.3.9 (Unix) ApacheJServ/1.0
  • Last-Modified Mon, 30 Apr 2001 230236 GMT
  • ETag "5b381-ec-3aedef0c"
  • Accept-Ranges bytes
  • Content-Length 236
  • Connection close
  • Content-Type text/html
  • lthtmlgt
  • ltheadgt
  • lttitlegtMy web page lt/titlegt
  • lt/headgt
  • ltbodygt
  • Hello world!
  • lt/BODYgtlt/HTMLgt

51
HTML Forms
  • You create forms to send data from the browser to
    the server
  • When the form is used with JSP / servlets, your
    JSP can process the data in the form and return
    the result
  • HTML forms are created using ltFORMgtlt/FORMgt tag
  • Attributes ACTION, METHOD and TARGET
  • ACTION defines the URL of the form handler
    which will be a JSP/Servlet here
  • METHOD defines the method that uses to send the
    data to server, GET will append the query string
    to the URL but POST allows non-ASCII character
    and query strings without any length restriction

52
Input for the Form
  • Using the ltINPUTgt tag, you can create different
    input components by setting the TYPE attribute to
    different value
  • TEXT text box
  • PASSWORD text box masked with
  • HIDDEN input value which are not shown in
    browser
  • CHECKBOX a check box
  • RADIO radio buttons, group is determined by the
    NAME attribute
  • SUBMIT submit button, submit the form
  • RESET cancel button, clear the form
  • VALUE attribute can be set to give a default value

53
A Simple HTML Form
  • lthtmlgt ltbodygt
  • lth1gtPlease tell me about yourselflt/h1gt
  • ltform action"SimpleFormHandler.jsp"
    method"get"gt
  • Name ltinput type"text" name"firstName"gtltinput
    type"text" name"lastName"gt ltbrgt
  • Sex ltinput type"radio" checked name"sex"
    value"male"gtMaleltinput type"radio" name"sex"
    value"female"gtFemale
  • ltPgt What Java primitive type best describes your
    personality
  • ltselect name"javaType"gt
  • ltoption value"boolean"gtbooleanlt/optiongt
  • ltoption value"byte"gtbytelt/optiongt
  • ltoption value"char" selectedgtcharlt/optiongt
  • ltoption value"double"gtdoublelt/optiongt
  • ltoption value"float"gtfloatlt/optiongt
  • ltoption value"int"gtintlt/optiongt
  • ltoption value"long"gtlonglt/optiongt
  • lt/selectgtltbrgt
  • ltinput type"submit"gt lt/formgt
  • lt/bodygt lt/htmlgt

54
Simple Form in Browser
55
JSP Handling the Simple Form
  • lthtmlgt ltbodygt
  • lt // Grab the variables from the form
  • String firstName request.getParameter("firstNam
    e")
  • String lastName request.getParameter("lastName"
    )
  • String sex request.getParameter("sex")
  • String javaType request.getParameter("javaType"
    )
  • gt
  • lt-- Print out the variables --gt
  • lth1gtHello, ltfirstNamegt ltlastNamegt!lt/h1gt
  • I see that you are ltsexgt.
  • You know, you remind me of a ltjavaTypegt
    variable
  • I once knew.
  • lt/bodygtlt/htmlgt

56
Build-in Object request in a JSP
  • request object is an instance of
    HttpServletRequest
  • You can use the getParameter method to retrieve
    the values from the form variables
  • Example String firstName request.getParameter(
    firstName)
  • The variable names are case-sensitive
  • If the form variable in a text box is left empty,
    the value "" (empty string) will be assigned
  • If the form variable does not exist, the value
    null will be returned
  • In fact, the parameters and their values can be
    appended directly to the URL of the JSP

57
Handling Multiple Form Values
  • When we have multiple values for the same form
    variable, you can get all values store in a
    String array by calling getParameterValues method
  • getParameterValues return null if the form
    variable does not exist
  • An array of size 1 will be returned if only one
    value exists for a parameter
  • You can also retrieve the names of all available
    parameters using getParameterNames method, which
    will return you an Enumeration object
  • hasMoreElement method in an Enumeration object
    can check if there is any element left in the
    enumeration
  • nextElement method is used to retrieve the next
    element in the enumeration

58
Form with Multiple Values
  • lthtmlgtltbodygt
  • lth1gtPlease enter a list of nameslt/h1gt
  • ltform action"MultiFormHandler.jsp" method"get"gt
  • ltinput type"text" name"names"gtltbrgt
  • ltinput type"text" name"names"gtltbrgt
  • ltinput type"text" name"names"gtltbrgt
  • ltinput type"text" name"names"gtltbrgt
  • ltinput type"text" name"names"gtltbrgt
  • ltinput type"submit"gt
  • lt/formgt
  • lt/bodygt lt/htmlgt

59
JSP Handling the Multiple Values
  • lthtmlgt ltbodygt
  • The names you entered are
  • ltpregt
  • lt // Fetch the name values
  • String names request.getParameterValues("nam
    es")
  • for (int i0 i lt names.length i)
  • out.println(namesi)
  • gt
  • lt/pregt
  • lt/bodygt lt/htmlgt

60
Getting Parameter Names and Values
  • lthtmlgt ltbodygt You passed me the following
    parameters
  • ltpregt
  • lt // Find out the names of all the parameters
  • java.util.Enumeration params
    request.getParameterNames()
  • while (params.hasMoreElements())
  • // Get the next parameter name
  • String paramName (String) params.nextElement()
  • // Use getParameterValues in case of multiple
    values
  • String paramValues request.getParameterVa
    lues(paramName)
  • // If there is only one value, print it out
  • if (paramValues.length 1)
  • out.println(paramName""paramValues0)
  • else
  • // For multiple values, loop through them
  • out.print(paramName"")
  • for (int i0 i lt paramValues.length i)
  • // If this isn't the first value, //
    print a comma to separate values
  • if (i gt 0) out.print(',')
  • out.print(paramValuesi)

61
Different Ways to Call a Form
  • Three most common arrangements of forms and JSP
    handler
  • Static HTML input form calling a JSP form handler
  • A JSP input form calling another JSP form handler
  • A single JSP page displaying the form and handles
    the input
  • You can also mix servlets with JSP in a web
    application, especially when you are developing a
    multi-tier web application

62
Using the Same JSP for Input Form and Form
Handler
  • When the first time the user hits the page, you
    can detect that there is no form data to process
    and show the initial input form
  • After that, you need a trick to detect the form
    data
  • Look for the presence of form variables
  • Pass a special variable indicating that this is a
    form submission
  • E.g., ltinput typehidden nameisSubmitted
    valueyesgt
  • Submit the form using POST method and examine the
    request method
  • To examine the request method, you can use the
    followingif (request.getMethod().equals(POST))

63
Multiple Threads in JSP
  • When you got instance variables declared in
    declaration tags (lt! gt), you might run into
    threading issues
  • Typically, only one instance of the servlet (JSP)
    is loaded at one time
  • When a browser requests a JSP, the web server
    spawns another thread to handle the request
  • Thus, there may be multiple threads executing the
    same servlet
  • When the different threads access and modify the
    same instance variable, your client may display
    some data of another client!! (see Address.jsp
    for example)

64
Solving the Threading Issues
  • One solution for the problem is to synchronize
    the variable assignments and method call
  • synchronized (this)
  • firstName request.getParameter(firstName)
  • middleName request.getParameter(middleName)
  • formatNameAndAddress(out) // call formatting
    routine
  • Solve the solution at the cost of performance
  • Only one thread can access the data at one time
  • Create a bottleneck for the server
  • A better method is to pass the data as method
    parameters rather than using the instance
    variables (see AddressGood.jsp)

65
Advantages and Disadvantages of JSPs
  • Advantages
  • Looks like HTML
  • Easy for web page authors and software developers
    to do their jobs "separately"
  • JSP will eventually turn to a servlet and
    automatically load into the servlet container
    and automatically update if the JSP is modified
  • Disadvantages
  • Due to its capability of mixing Java codes with
    HTML and JavaScript, it is very hard to debug if
    there is any error in the page

66
Advantages and Disadvantages of Servlets
  • As Servlets are Java classes, you will not have
    Java, HTML and JavaScript mixed up
  • But it ends up with many out.print and
    out.println statements
  • When you need to deploy a large web application,
    it will be easier to manage the deployment file
    (web.xml) are oriented to servlet
  • Thus, as stated before, servlets are usually used
    to deal with business logic (e.g. database
    fetching, doing computation and etc.)
  • JSPs are used to render the output.
Write a Comment
User Comments (0)
About PowerShow.com