Internet programming Applets as front ends for Servlets - PowerPoint PPT Presentation

1 / 37
About This Presentation
Title:

Internet programming Applets as front ends for Servlets

Description:

Applets as front ends for Servlets ... Applets as front ends for Servlets. Approach 2: Send data with GET and process the result ... – PowerPoint PPT presentation

Number of Views:59
Avg rating:3.0/5.0
Slides: 38
Provided by: profdringh
Category:

less

Transcript and Presenter's Notes

Title: Internet programming Applets as front ends for Servlets


1
Internet programmingApplets as front ends for
Servlets
  • Prof. Dr.-Ing. Holger Vogelsang
    holger.vogelsang_at_hs-karlsruhe.de

2
Applets as front ends for Servlets Contents
  • Architecture and Protocols
  • Dynamic HTML pages
  • Servlets
  • JavaServer Pages
  • Combination of Servlets and JavaServer Pages
  • Expression language
  • Taglibs
  • Applets as front ends for Servlets
  • An applet imitates an HTML page
  • Send data with GET and process the result
  • Send data with POST and process the result
  • Communication with another server

3
Applets as front ends for Servlets Idea
  • Usage
  • Applets are much more flexible than simple HTML
    pages.
  • Communication scenarios
  • An Applet imitates an HTML page It sends the GET
    request to a Servlet. The resulting page is
    displayed as a normal HTML page in the browser.

Browser
request
Servlet oder JSP
Applet
response
Servlet engine
4
Applets as front ends for Servlets Idea
  • Applets send GET data and perform result
    processing (HTTP tunneling).

Browser
request
Servlet oder JSP
Applet
response
Servlet engine
5
Applets as front ends for Servlets Idea
  • Applets send POST data and perform result
    processing. E.g. Exchanging objects by
    serialization between Servlets and Applets.

Browser
request
Servlet oder JSP
Applet
response
Servlet engine
6
Applets as front ends for Servlets Idea
  • An Applet by-passes the Servlet engine and
    communicates with another server on the Servlet
    engines or the clients machine.

Browser
request
Server Object
Applet
Object
response
Server
Servlet
Servlet engine
7
Applets as front ends for Servlets Contents
  • Architecture and Protocols
  • Dynamic HTML pages
  • Servlets
  • JavaServer Pages
  • Combination of Servlets and JavaServer Pages
  • Expression language
  • Taglibs
  • Applets as front ends for Servlets
  • An applet imitates an HTML page
  • Send data with GET and process the result
  • Send data with POST and process the result
  • Communication with another server

8
Applets as front ends for Servlets Approach 1
An applet imitates an HTML page
  • Basic ideas
  • The Applet context has a method showDocument
  • getAppletContext().showDocument(url)
  • The GET data is appended to the URL
  • http//host/ServletPath?param1value1param2valu
    e2
  • Example
  • try
  • URL programURL new URL(baseURL "?"
    someData)
  • getAppletContext().showDocument(programURL,
    targetFrame)
  • catch (MalformedURLException ex)
  • // ...

9
Applets as front ends for Servlets Approach 1
An applet imitates an HTML page
  • The Browsers encodes sent data
  • ASCII characters 'a' through 'z', 'A' through
    'Z', '0' through '9', and '.', '-', '', '_'
    remain the same.
  • Character ' ' is converted into a plus sign ''.
  • All other characters are converted into the
    3-character string "xy", where xy is the
    two-digit hexadecimal representation of the lower
    8-bits of the character.
  • Applets have to encode their data too.
  • Only parameter names and values have to be
    encoded, not the separators ? It's not possible
    to encode the whole data string in a single step.
  • The class URLEncoder (package java.net) has a
    static method encode which does all required
    work
  • String encString URLEncoder.encode(value)

10
Applets as front ends for Servlets Approach 1
An applet imitates an HTML page
  • Example
  • String someData
  • name1 "" URLEncoder.encode(value1)
    ""
  • name2 "" URLEncoder.encode(value2)
    ""
  • // ...
  • nameN "" URLEncoder.encode(valueN)
  • try
  • URL programURL new URL(baseURL "?"
    someData)
  • getAppletContext().showDocument(programURL)
  • catch (MalformedURLException ex)
  • // ...

11
Applets as front ends for Servlets Approach 1
An applet imitates an HTML page survey version 5
  • Example An Applet as a frontend for the survey
    servlet (ugly user interface!).

12
Applets as front ends for Servlets Approach 1
An applet imitates an HTML page survey version 5
  • Resulting page after calling the already existing
    servlet Survey4Collect.jsp

13
Applets as front ends for Servlets Approach 1
An applet imitates an HTML page survey version 5
  • Main HTML page (SurveyAppletFrame.jsp)
  • lt!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0
    Transitional//EN"gt
  • lthtmlgt
  • ltheadgt
  • lttitlegtSearch Applet Framelt/titlegt
  • lt/headgt
  • ltbody bgcolor"white"gt
  • ltcentergt
  • ltjspplugin type"applet" code"hska.faki.SurveyA
    pplet.class"
  • codebase"../IP/WEB-INF/classes/"
  • jreversion"1.5"
  • width"600" height"100"gt
  • lt/jspplugingt
  • lt/centergt
  • lt/bodygt
  • lt/htmlgt

14
Applets as front ends for Servlets Approach 1
An applet imitates an HTML page survey version 5
  • Applet code (Survey5Applet.java), incomplete
    (qualityPerfect and difficultyOk are check
    boxes)
  • try
  • String quality qualityPerfect.getState()
    ? "Perfect"

  • "Poor"
  • String difficulty difficultyOk.getState()
    ? "Ok"

  • "TooEasy"
  • // Not necessary...
  • String queryQuality URLEncoder.encode(quality
    , "UTF-8")
  • String queryDifficulty URLEncoder.encode(diff
    iculty, "UTF-8")
  • try
  • URL newURL new URL("http//localhost8080/I
    P/JSP/"
  • "Survey4Collect.jsp?qu
    ality"
  • queryQuality
  • "difficulty"
  • queryDifficulty)
  • getAppletContext().showDocument(newURL)

15
Applets as front ends for Servlets Contents
  • Architecture and Protocols
  • Dynamic HTML pages
  • Servlets
  • JavaServer Pages
  • Combination of Servlets and JavaServer Pages
  • Expression language
  • Taglibs
  • Applets as front ends for Servlets
  • An applet imitates an HTML page
  • Send data with GET and process the result
  • Send data with POST and process the result
  • Communication with another server

16
Applets as front ends for Servlets Approach 2
Send data with GET and process the result
  • An Applet communicates with a servlet by sending
    GET requests and receiving responses.
  • No new HTML pages are transferred.
  • The Applet keeps the complete control over the
    communication.
  • This approach only works with a server-side Java
    program (e.g. a servlet).
  • An Applet can read raw binary data or serialized
    objects from a stream
  • A URLConnection is created and opened.
  • Depending on the data type, one of the following
    streams is opened
  • Raw data A BufferedInputStream is used to read
    data from the server.
  • Serialized objects An ObjectInputStream is used.
  • To send data to the servlet, name/value-pairs are
    appended to the request string.

17
Applets as front ends for Servlets Approach 2
Send data with GET and process the result
  • Reading binary or ASCII data
  • Create a URL object referring to the Applets home
    host.
  • URL currentPage getCodeBase()
  • URL dataURL new URL(currentPage.getProtocol(),
  • currentPage.getHost(),
  • currentPage.getPort(),
  • "/IP/servlet/ServerServlet"
    )
  • Open the connection.
  • URLConnection connection dataURL.openConnection
    ()
  • Prevent the browser from data caching.
  • connection.setUseCaches(false)
  • Optional Setting HTTP headers.
  • connection.setRequestProperty("header-name",
    "header-value")
  • Open an input stream to read the servlets
    response.
  • BufferedReader in new BufferedReader(
  • new InputStreamReader(connection.getInp
    utStream()))

18
Applets as front ends for Servlets Approach 2
Send data with GET and process the result
  • Read the input data line by line (ASCII data) or
    byte by byte (raw data). The server closes the
    connection ? readLine returns null.
  • String line
  • while ((line in.readLine()) ! null)
  • doSomethingWith(line)
  • Close the stream.
  • in.close()
  • Note All steps above must be encapsulated in the
    following try-catch-block
  • try
  • // Steps 1 - 7
  • catch (IOException ex)

19
Applets as front ends for Servlets Approach 2
Send data with GET and process the result
  • Reading serialized objects
  • Only steps 5 and 6 differ.
  • Open an ObjectInputStream to read the servlets
    response.
  • ObjectInputStream in
  • new ObjectInputStream(connection.getInputS
    tream())
  • Read the object(s).
  • SomeClass value (SomeClass)in.readObject()
  • doSomethingWith(value)

Browser
request (GET)
Servlet oder JSP
Applet
response (object)
Servlet engine
20
Applets as front ends for Servlets Approach 2
Send data with GET and process the result
  • Server-side requirements
  • The servlet has to perform the following four
    steps to send objects
  • Specify a binary response (MIME-type
    application/x-java-serialized-object) ? not
    important, since the Applet ignores this.
  • response.setContentType("application/x-java-seria
    lized-object")
  • Create an ObjectOutputStream.
  • ObjectOutputStream out
  • new ObjectOutputStream(response.getO
    utputStream())
  • Write the object(s).
  • SomeClass value new SomeClass( ... )
  • out.writeObject(value)
  • Empty the stream to ensure, that all data is
    written.
  • out.flush()
  • The stream is automatically closed by the servlet.

21
Applets as front ends for Servlets Approach 2
Send data with GET and process the result
example
  • Example application For every request, the
    servlet returns a Vector of random numbers. The
    Applet specifies the amount of numbers as a
    request parameter (HTML page RandomNumberAppletFr
    ame.html).

22
Applets as front ends for Servlets Approach 2
Send data with GET and process the result
example
  • Applet (RandomNumberGetApplet.java)
  • // An applet that reads a value from a
    TextField,
  • // then uses it to request random numbers.
  • public class RandomNumberGetApplet extends
    Applet
  • implements
    ActionListener
  • private TextField countField
  • private TextArea numberArea
  • private Button submitButton
  • public void init()
  • // Build user interface

23
Applets as front ends for Servlets Approach 2
Send data with GET and process the result
example
  • /
  • Submit data when button is pressed
    ltBgtorlt/Bgt
  • user presses Return in the TextField.
  • /
  • public void actionPerformed(ActionEvent
    event)
  • try
  • String value URLEncoder.encode(countField
    .getText(),
  • "UTF-8")
  • URL currentURL getCodeBase()
  • URL requestURL new URL(currentURL.getProt
    ocol(),

  • currentURL.getHost(),

  • currentURL.getPort(),

  • "/IP/servlet/hska.faki."

  • "RandomNumberObjectGetServlet"
  • "?count"
  • value)
  • URLConnection connection
    requestURL.openConnection()
  • connection.setUseCaches(false)

24
Applets as front ends for Servlets Approach 2
Send data with GET and process the result
example
  • Vector values (Vector) in.readObject()
  • in.close()
  • // Dump random numbers
  • StringBuffer text new StringBuffer()
  • for (Enumeration enum values.elements()

  • enum.hasMoreElements())
  • text.append(enum.nextElement())
  • text.append("\n")
  • numberArea.setText(text.toString())
  • catch (IOException ex1)
  • catch (ClassNotFoundException ex2)

25
Applets as front ends for Servlets Approach 2
Send data with GET and process the result
example
  • Servlet (RandomNumberObjectGetServlet.java)
  • public class RandomNumberObjectGetServlet
    extends HttpServlet
  • public void doGet(HttpServletRequest request,
  • HttpServletResponse
    response)
  • throws
    ServletException, IOException
  • response.setContentType("text/x-java-serializ
    ed-object")
  • int count 5
  • try
  • count Integer.parseInt(request.getParamet
    er("count"))
  • catch (Exception ex)
  • if (count lt 0)
  • count 5

26
Applets as front ends for Servlets Approach 2
Send data with GET and process the result
example
  • // Generate random numbers
  • Vector values new Vector(count)
  • for (int i 0 i lt count i)
  • values.addElement(new Integer((int)
    (Math.random()100)))
  • ObjectOutputStream out
  • new ObjectOutputStream(response.getO
    utputStream())
  • out.writeObject(values)
  • out.flush()
  • Notes
  • The HTML page (RandomNumberAppletFrame.html) must
    be accessed by the server.
  • If the page is loaded from the local file system,
    the Applet is not allowed to access the Servlet!
  • Also, the HTML page must be somewhere in the path
    to the Servlet on the server-side.

27
Applets as front ends for Servlets Contents
  • Architecture and Protocols
  • Dynamic HTML pages
  • Servlets
  • JavaServer Pages
  • Combination of Servlets and JavaServer Pages
  • Expression language
  • Taglibs
  • Applets as front ends for Servlets
  • An applet imitates an HTML page
  • Send data with GET and process the result
  • Send data with POST and process the result
  • Communication with another server

28
Applets as front ends for Servlets Approach 3
Send data with POST and process the result
  • Advantages over approach 2
  • The Applet can also send Java objects to the
    servlet. This is not possible using the GET
    method.
  • Real HTTP tunneling through a firewall is
    possible.
  • Disadvantage
  • 13 Steps are required to communicate with the
    Servlet.

29
Applets as front ends for Servlets Approach 3
Send data with POST and process the result
  • Reading and sending binary or ASCII data
  • Create a URL object referring to the Applets home
    host.
  • URL currentPage getCodeBase()
  • URL dataURL new URL(currentPage.getProtocol(),
  • currentPage.getHost(),
  • currentPage.getPort(),
  • "/IP/servlet/ServerServlet"
    )
  • Open the connection.
  • URLConnection connection dataURL.openConnection
    ()
  • Prevent the browser from data caching.
  • connection.setUseCaches(false)
  • Instruct the connection, that data will sent.
  • connection.setDoOutput(true)

30
Applets as front ends for Servlets Approach 3
Send data with POST and process the result
  • Create a ByteArrayOutputStream, which buffers the
    data before sending. This is necessary to
    calculate the size of the data. The initial size
    is not important.
  • ByteArrayOutputStream byteOut new
    ByteArrayOutputStream(512)
  • Create a PrintWriter for easier output
    generation.
  • PrintWriter out new PrintWriter(byteOut)
  • Write the data to the output stream.
  • String data "param1" URLEncoder.encode(so
    meValue1)
  • "param2" URLEncoder.encode(so
    meValue2)
  • out.print(data) // Not println!
  • out.flush()
  • Set the Content-Length-header.
  • connection.setRequestProperty("Content-Length",
  • String.valueOf(byte
    Out.size())
  • Set the Content-Type-header.
  • connection.setRequestProperty("Content-Type",
  • "application/x-www-fo
    rm-urlencoded")

31
Applets as front ends for Servlets Approach 3
Send data with POST and process the result
  • Send the data.
  • byteOut.writeTo(connection.getOutputStream())
  • Open an input stream to read the Servlets
    response.
  • BufferedReader in new BufferedReader(
  • new InputStreamReader(connection.getInp
    utStream()))
  • Read the input data line by line (ASCII data) or
    byte by byte (raw data). The server closes the
    connection ? readLine returns null.
  • String line
  • while ((line in.readLine()) ! null)
  • doSomethingWith(line)
  • Close the stream.
  • in.close()
  • Note All steps above must be encapsulated in a
    try-catch-block.
  • The Servlet code is the same as in approach 2.

32
Applets as front ends for Servlets Approach 3
Send data with POST and process the result
  • Reading and writing serialized objects
  • Only steps 6, 7 and 11, 12 differ.
  • Open an ObjectOutputStream to write the
    serialized objects.
  • ObjectOutputStream in new ObjectOutputStream(by
    teOut)
  • Write the object(s) to the buffer.
  • SomeClass value new SomeClass(...)
  • out.writeObject(value)
  • Open an ObjectInputStream to read the Servlets
    response.
  • ObjectInputStream in
  • new ObjectInputStream(connection.getInputS
    tream())
  • Read the object(s).
  • SomeClass value (SomeClass)in.readObject()
  • doSomethingWith(value)
  • Steps 11 and 12 are the same as in approach 2.
  • On the Servlet side, the serialized objects can
    be accessed using getInputStream() method of the
    request object.

33
Applets as front ends for Servlets Approach 3
Send data with POST and process the result
example
  • Example of approach 3, modified to send the
    amount of random numbers as an object to the
    server. Only the differences are shown
    (RandomNumberPostApplet.java)
  • // ...
  • public class RandomNumberPostApplet extends
    Applet
  • implements
    ActionListener
  • // ...
  • public void actionPerformed(ActionEvent event)
  • String value URLEncoder.encode(countField.g
    etText())
  • try
  • URL currentURL getCodeBase()
  • URL requestURL new URL(currentURL.getPr
    otocol(),

  • currentURL.getHost(),

  • currentURL.getPort(),

  • "/IP/servlet/hska.faki."

  • "RandomNumberObjectPostServlet")
  • URLConnection connection
    requestURL.openConnection()
  • connection.setUseCaches(false)
  • connection.setDoOutput(true)

34
Applets as front ends for Servlets Approach 3
Send data with POST and process the result
example
  • ByteArrayOutputStream byteOut
  • new
    ByteArrayOutputStream(10)
  • ObjectOutputStream out
  • new
    ObjectOutputStream(byteOut)
  • // Read count
  • Integer count new Integer(5)
  • try
  • count Integer.valueOf(countField.getT
    ext())
  • catch (NumberFormatException ex)
  • count 5
  • out.writeObject(count)
  • out.flush()
  • connection.setRequestProperty("Content-Le
    ngth",

  • String.valueOf(byteOut.size()))

35
Applets as front ends for Servlets Approach 3
Send data with POST and process the result
example
  • The Servlet is modified to read the request from
    an input stream and not as a request parameter.
    Only the modified parts are shown
    (RandomNumberObjectPostServlet.java)
  • // ...
  • public class RandomNumberObjectPostServlet
    extends HttpServlet
  • public void doPost(HttpServletRequest request,
  • HttpServletResponse
    response)
  • throws
    ServletException, IOException
  • // Try to read the count object
  • ObjectInputStream in
  • new ObjectInputStream(request.get
    InputStream())
  • int count 5
  • try
  • count ((Integer) in.readObject()).intValu
    e()
  • catch(ClassNotFoundException ex)
  • // Rest of the file is not modified
    (generating the response).

36
Applets as front ends for Servlets Contents
  • Architecture and Protocols
  • Dynamic HTML pages
  • Servlets
  • JavaServer Pages
  • Combination of Servlets and JavaServer Pages
  • Expression language
  • Taglibs
  • Applets as front ends for Servlets
  • An applet imitates an HTML page
  • Send data with GET and process the result
  • Send data with POST and process the result
  • Communication with another server

37
Applets as front ends for Servlets Approach 4
Communication with another server
  • Access is only allowed to the Applets source
    server.
  • Very flexible RMI, sockets, CORBA, SOAP, ...
  • Not discussed here...
Write a Comment
User Comments (0)
About PowerShow.com