CS4273: Distributed System Technologies and Programming I - PowerPoint PPT Presentation

About This Presentation
Title:

CS4273: Distributed System Technologies and Programming I

Description:

CS4273: Distributed System Technologies and Programming I Lecture 9: Java Servlets – PowerPoint PPT presentation

Number of Views:52
Avg rating:3.0/5.0
Slides: 30
Provided by: PengJ7
Category:

less

Transcript and Presenter's Notes

Title: CS4273: Distributed System Technologies and Programming I


1
CS4273 Distributed System Technologies and
Programming I
  • Lecture 9 Java Servlets

2
CSlab Setting of Java Servlet
  • Servlet Engine searches files in directory
    /usr/local/jt/webapps. To facilitate access to
    each persons files, CSlab has made a link
  • ln -s /home/lec/jia/www/java/js
    /usr/local/jt/webapps/jia
  • /usr/jt/webapps/jia/ ? jia/www/java/js/
  • The servlet engine searches files relative from
    directory /usr/local/jt/webapps/
  • http//jserv.cs.cityu.edu.hk8080/jia/servlet/XXX
    is mapped to
  • jia/www/java/js/ WEB-INF/classes/ XXX,
    because
  • http//jserv.cs.cityu.edu.hk8080/jia ?
    /usr/local/jt/webapps/jia ? jia/www/java/js/
  • servlet ? /WEB-INF/classes
  • All servlet .class files MUST be in directory
  • jia/www/java/js/WEB-INF/classes/
  • The corresponding URL is
  • http//jserv.cs.cityu.edu.hk8080/jia/servlet/Get
    Servlet
  • All .html files MUST be in directory
  • jia/www/java/js/html/
  • The corresponding URL is
  • http//jserv.cs.cityu.edu.hk8080/jia/html/test.h
    tml

3
Your personal directory setting
  • CSlab already made a link from /usr/jt/webapps/501
    234 to your personal directory 501234/www/java/j
    s in CSlab account (501234 is your student
    number).
  • A copy of all sample programs is in
    /public/cs4273.tar (zipped at jia/www). You can
    un-zip all files into your directory
    501234/www/ by UNIX commands
  • cd www // change dir to
  • tar xvf /public/cs4273.tar // un-zip files into
    501234/www/java/js
  • All files are in directories www/java/js/WEB-INF/
    classes/, www/java/js/html/.
  • To run servlet in 501234/www/java/js/WEB-INF/cla
    sses/GetServlet.class, URL is
  • http//jserv.cs.cityu.edu.hk8080/501234/servlet/
    GetServlet
  • To run a servlet by a html file in
    501234/www/java/js/html/test.html, URL is
  • http//jserv.cs.cityu.edu.hk8080/501234/html/tes
    t.html
  • Note 1) servEngine cannot detect any change of
    your program until it restarts. In current
    setting, servEngine auto-restarts every 20 min.
    Wait for about 20 min to refresh a page.
  • 2) For each servlet, you need to add a new item
    in file /js/WEB-INF/web.xml

4
Java Servlet
  • Servlet runs on the web site. To enable servlets,
    it needs to install a servlet engine (e.g.,
    Jserv, or Tomcat), which is a module of a
    web-server and runs inside the web-server
    process.
  • Servlet replaces CGI program to link clients (in
    browser) to back-end servers. Servlet generates
    HTML pages, sent back to browser for display,
    similar to ASP.
  • Servlet can support many protocols of request /
    response type, such as HTTP, URL, FTP, SMTP.
    Thats, any requests coming in the form of these
    protocols can be processed by a servlet (Servlet
    API defines the support of these protocols).
  • The most common protocol that Servlet supports is
    HTTP.

5
Servlet Life Cycle
  • Servlets run on the web server as part of the
    web-server process. The web-server initializes,
    invokes and destroys servlet instances. It
    invokes servlets via Servlet interface,
    consisting of three methods
  • init(). It is called only once, when the servlet
    is first loaded. It is guaranteed to finish
    before any other calls are made to the servlet.
  • service(). Each request from a client results in
    a single call to this method. It receives (from
    the web server) a ServletRequest object a
    ServletResponse object to get request / send
    reply to clients.
  • destroy(). It is called to allow your servlet to
    clean up any resources. Most of the time, it is
    an empty method.

6
A Simple Servlet
  • http//jserv...hk8080/jia/servlet/GenericServlet
  • import javax.servlet.
  • public class GenericServlet implements
    Servlet
  • private ServletConfig config
  • public void init (ServletConfig config)
  • throws ServletException
  • this.config config
  • public void destroy() // do nothing
  • public ServletConfig getServletConfig()
  • return config
  • public String getServletInfo()
  • return A Simple Servlet
  • public void service (ServletRequest req,
  • ServletResponse res)
  • throws ServletException, IOException
  • res.setContentType( text/html )
  • PrintWriter out res.getWriter()
  • out.println( lthtmlgt )
  • out.println( ltheadgt )
  • out.println( lttitlegtA Simple
    Servletlt/titlegt )
  • out.println( lt/headgt )
  • out.println( ltbodygt )
  • out.println( lth1gtHello
    Servletlt/h1gt )
  • out.close()

7
Http Servlet
  • The servlet package has two abstract classes that
    implement interface Servlet
  • GenericServlet from package javax.servlet
  • HttpServlet from package javax.servlet.http
  • HttpServlet overrides the key method service() by
    adding the code to distinguish HTTP requests and
    invokes corresponding methods
  • doPost()
  • doGet()
  • doHead()
  • doDelete()
  • doOption()
  • doTrace()
  • Most of programs extend class HttpServlet, and
    implement methods doPost() and doGet().

8
Example of an HTTP servlet
  • // create and send HTML page to client
  • output.println( "ltHTMLgtltHEADgtltTITLEgt" )
  • output.println( "A Simple Servlet Example"
    )
  • output.println( "lt/TITLEgtlt/HEADgtltBODYgt" )
  • output.println( "ltH1gtWelcome to
    Servletslt/H1gt" )
  • output.println( "Dear " name "ltbrgt")
  • output.println( "How are you at " addr
    "?ltbrgt" )
  • output.println( "lt/BODYgtlt/HTMLgt" )
  • output.close() // close PrintWriter
    stream
  • import javax.servlet.
  • import javax.servlet.http.
  • public class GetServlet extends HttpServlet
  • public void doGet(HttpServletRequest request,
  • HttpServletResponse
    response )
  • throws ServletException, IOException
  • PrintWriter output
  • // content type
  • response.setContentType( "text/html" )
  • output response.getWriter()
  • String name request.getParameter( "customer"
    )
  • String addr
  • request.getParameter( "address" )

9
HttpServletRequest / HttpServletResponse
  • Interfaces HttpServletRequest and
    HttpServletResponse extend interfaces
    ServletRequest and ServletResponse.
  • The methods of HttpServlet receives two
    parameters a HttpServletRequest object, which
    contains the request from the client, and a
    HttpServletResponse object, which contains the
    response to the client.
  • When a client makes a HttpServlet call, the web
    server creates a HttpServletRequest and a
    HttpServletResponse object, and passes them to
    doGet() or doPost() methods.

10
HttpServletRequest
  • Some important methods of HttpServletRequest
  • String getParameter (String name)
  • returns the value of the named parameter
  • Enumeration getParameterNames()
  • returns names of all the parameters sent to
    servlet
  • String getParameterValues( String name)
  • returns an array of values of the named
    parameter
  • Cookie getCookies()
  • HttpSession getSession(Boolean create)

11
HttpServletResponse
  • Some important methods of HttpServletResponse
  • void setContentType (String type)
  • specifies the MIME type of the response to the
  • browser, e.g., text/html.
  • PrintWriter getWriter()
  • obtains a character-based output stream.
  • ServletOutputStream getOutputStream()
  • obtains a byte-based output stream.
  • void addCookie (Cookie cookie)

12
HTML file for doGet Servlet
  • N.B. URL http//jserv.cs.cityu.edu.hk8080/jia/ht
    ml/GetServlet.html
  • lt!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0
    Transitional//EN"gt
  • ltHTMLgt
  • lt!-- Fig. 29.6 HTTPGetServlet.html --gt
  • ltHEADgt
  • ltTITLEgtServlet HTTP GET Examplelt/TITLEgt
  • lt/HEADgt
  • ltBODYgt
  • ltFORM ACTION"http//jserv.cs.cityu.edu.hk8080/ji
    a/servlet/GetServlet" METHOD"GET"gt
  • Name ltinput name"customer" size47gt ltpgt
  • Working Address ltinput name"address"
    size40gt ltpgt
  • ltPgtClick the button to connect the
    servletlt/Pgt
  • ltINPUT TYPE"submit" VALUE"Get HTML
    Document"gt
  • lt/FORMgt
  • lt/BODYgt
  • lt/HTMLgt

13
DoGet
  • // create and send HTML page to client
  • output.println( "ltHTMLgtltHEADgtltTITLEgt" )
  • output.println( "A Simple Servlet Example"
    )
  • output.println( "lt/TITLEgtlt/HEADgtltBODYgt" )
  • output.println( "ltH1gtWelcome to
    Servletslt/H1gt" )
  • output.println( "Dear " name "ltbrgt")
  • output.println( "How are you at " addr
    "?ltbrgt" )
  • output.println( "lt/BODYgtlt/HTMLgt" )
  • output.close() // close PrintWriter
    stream
  • import javax.servlet.
  • import javax.servlet.http.
  • public class GetServlet extends HttpServlet
  • public void doGet(HttpServletRequest request,
  • HttpServletResponse
    response )
  • throws ServletException, IOException
  • PrintWriter output
  • // content type
  • response.setContentType( "text/html" )
  • output response.getWriter()
  • String name request.getParameter( "customer"
    )
  • String addr
  • request.getParameter( "address" )

14
HTML file for doPost Servlet
  • lt!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0
    Transitional//EN"gt
  • ltHTMLgt
  • lt!-- Fig. 29.8 HTTPPostServlet.html --gt
  • ltHEADgt ltTITLEgtServlet HTTP Post Examplelt/TITLEgt
    lt/HEADgt
  • ltBODYgt
  • ltFORM ACTION"http//jserv.cs.cityu.edu.hk8080/ji
    a/servlet/PostServlet" METHOD"POST"gt
  • What is your favorite pet?ltBRgtltBRgt
  • ltINPUT TYPE"radio" NAME"animal"
    VALUE"dog"gtDogltBRgt
  • ltINPUT TYPE"radio" NAME"animal"
    VALUE"cat"gtCatltBRgt
  • ltINPUT TYPE"radio" NAME"animal"
    VALUE"bird"gtBirdltBRgt
  • ltINPUT TYPE"radio" NAME"animal"
    VALUE"snake"gtSnakeltBRgt
  • ltINPUT TYPE"radio" NAME"animal" VALUE"none"
    CHECKEDgtNone
  • ltBRgtltBRgtltINPUT TYPE"submit" VALUE"Submit"gt
  • ltINPUT TYPE"reset"gt
  • lt/FORMgt
  • lt/BODYgtlt/HTMLgt

15
DoPost
  • public class PostServlet extends HttpServlet
  • private String animalNames "dog", "cat",
    "bird",
  • public void doPost( HttpServletRequest
    request,
  • HttpServletResponse
    response )
  • throws ServletException,
    IOException
  • int animals null, total 0
  • //read in initial data of animals from
    a file
  • // .......
  • value request.getParameter( "animal" )
  • // update survey data in animals
  • for ( int i 0 i lt animalNames.length
    i )
  • if ( value.equals( animalNames i ) )
  • animals i
  • // write animals to file calculate
  • // send a message survey results to
    client
  • response.setContentType( "text/html" )
  • PrintWriter output response.getWriter()
  • output.println( "lthtmlgt" )
  • output.println( "lttitlegtThank you!lt/titlegt"
    )
  • output.println( "Thank you for
    participating." )
  • output.println( "ltBRgtResultsltPREgt" )
  • // ....... println results.
  • output.println( "lt/PREgtlt/htmlgt")
  • output.close()

16
Servlet Database Connection
  • A servlet can connect to a DB server using JDBC
    in the same way as CGI programs.
  • A servlet can be started directly from browser,
    e.g., http//jserv.cs.cityu.edu.hk8080/jia/servle
    t/Coffee, if this servlet implements doGet
    method.
  • The servlet generates output in
  • HTML format and passes them back
  • to the browser for display.

17
A Servlet JDBC Paired with HTML
  • public class Coffee extends HttpServlet
  • public void doGet (HttpServletRequest
    request,
  • HttpServletResponse
    response)
  • throws ServletException, IOException
  • String url jdbcmysql//jserv.cs.cityu.e
    du.hk
  • 3306/db_jdemo"
  • String query "select COF_NAME, PRICE
  • from COFFEES"
  • response.setContentType("text/html")
  • PrintWriter out response.getWriter()
  • Class.forName("com.mysql.jdbc.Driver")
  • con DriverManager.getConnection(url,
    "jdemo", "apple1")
  • Statement stmt con.createStatement()
  • ResultSet rs stmt.executeQuery(query)
  • out.println("ltHTMLgtltHEADgtltTITLEgt")
  • out.println("lt/TITLEgtlt/HEADgt")
  • .. HTML format
  • out.println("lttable border1gt")
  • out.println("lttrgtltthgtNameltthgtPrice")
  • while (rs.next())
  • String s rs.getString("COF_NAME")
  • float f rs.getFloat("PRICE")
  • String text "lttrgtlttdgt" s
    "lttdgt" f
  • out.println(text)
  • stmt.close() con.close()
  • out.println("lt/tablegt")
  • out.println("lt/BODYgtlt/HTMLgt")
  • out.close()

18
Applet and Servlet
  • Servlet can be used with Applet as a replacement
    of CGI programs. Applet starts a servlet by POST
    (or GET), same way as starting a CGI program.
  • Applet passes parameters to servlet in the same
    format as HTML form, e.g., nameXJiaaddrCityU
    ID5012344. Servlet can use getParameter to get
    parameter values.
  • The Applet processes the results from the servlet
    in the same way as from a CGI program (suppose
    servlet sends results back in the same format as
    CGI).
  • HTTP server must be in version 1.1 or above.
  • It uses protocol
  • POST /jia/servlet/CoffeeServlet HTTP/1.1

19
An Applet connecting to a Servlet
  • // java/js/WEB-INF/classes/CoffeeApplet.java
  • // http//jserv.cs.cityu.edu.hk8080/jia/html/test
    .html
  • public class CoffeeApplet extends Applet
  • implements Runnable
  • public synchronized void start()
  • if (worker null)
  • Thread worker new Thread(this)
  • worker.start()
  • public void run()
  • Socket s
  • String sdata typeselect_COFFEES
  • DataInputStream in PrintStream out
  • s new Socket("jserv.cs.cityu.edu.hk",8080
    )
  • in new DataInputStream(s.getInputStream()
    )
  • out new PrintStream(s.getOutputStream())
  • out.println("POST /jia/servlet/CoffeeServlet
    HTTP/1.1")
  • out.println("Host jserv.cs.cityu.edu.hk")
  • out.println("Content-type
  • application/x-www-form-urlencoded")
  • out.println("Content-length "
    sdata.length())
  • out.println("")
  • out.println(sdata)
  • String line in.readLine()
  • while (! line.equals("START_DATA"))
  • line in.readLine()
  • while (! line.equals("END"))
  • results.addElement(line)
  • line in.readLine()
  • out.close() in.close()

20
The Servlet Paired with Applet in JDBC
  • The servlet working with an applet is similar to
    the CGI program in the 3-tier structure of JDBC.
  • The servlet gets requests from applet via
    getParameter on request object. Note the
    string posted from applet must have the parameter
    in the correct format!
  • The servlet sends reply back to applet via
    println on response object. The servlet
    prepares reply to applet in a sequence of string
    lines, same as the CGI in 3-tier. Note applet
    cannot process HTML statements easily.
  • The applet working with the servlet is almost the
    same as the applet in the 3-tier structure of
    JDBC (except the format of request).

21
Servlet paired with the Applet
  • static String ReqSql()
  • String url "jdbcmysql//jserv.cs.cityu.ed
    u.hk
  • 3306/db_jdemo"
  • String query
  • "select COF_NAME, PRICE from COFFEES"
  • // make JDBC connection and executeQuery
  • ..
  • // process ResultSet to a line of string
    "results
  • ..
  • return(results.toString())
  • public class CoffeeServlet extends HttpServlet
  • public void doPost( HttpServletRequest
    request,
  • HttpServletResponse
    response )
  • throws ServletException, IOException
  • response.setContentType("text/html")
  • PrintWriter out response.getWriter()
  • a_req request.getParameter("type")
  • if (a_req.equals("select_COFFEES"))
  • line ReqSql()
  • out.println("START_DATA")
  • out.println(line)
  • out.println(END)

22
Servlet Cookies
  • HTTP server is stateless, i.e., it does not keep
    any info about the clients. Some applications
    require the response to client requests depends
    on the info from the client earlier. Cookie is
    for this purpose.
  • Cookies are extracted from the clients data sent
    to the servlet. They are sent back to the client
    to store at the client side.
  • A cookie is associated with an age. When the age
    expires, it will be removed.
  • The cookies are included in the header of request
    and sent to the servlet together with request
    (new cookies are sent back browser via response.
    The servlet can analyse cookies and reponse to
    the requests accordingly.
  • HTTPSession is a similar technology as the Cookie
    for the same purpose.

23
Methods on Cookies
  • Cookies are strings, defined in
    javax.servlet.http.Cookie.
  • Construct a Cookie Cookie cookie new Cookie(
    name, value)
  • Set an age for a cookie cookie.setMaxAge
    (seconds)
  • Add a cookie to a response to the client
    response.addCookie (cookie)
  • Get cookies from a clients request
  • Cookie cookies
  • cookies request.getCookies()
  • Get cookie attributes
  • cookiesi.getname()
  • cookiesi.getValue()
  • Analyse cookies one by one
  • for (i 0 i lt cookies.length i)
  • cookiesi.getname()
  • cookiesi.getValue()

24
An example of using Cookies
  • // must precede getWriter
  • response.addCookie( c )
  • response.setContentType( "text/html" )
  • PrintWriter output response.getWriter()
  • utput.println( "ltHTMLgtltHEADgtltTITLEgt" )
  • output.println( "Cookies" )
  • output.println( "lt/TITLEgtlt/HEADgtltBODYgt" )
  • output.println( "ltPgtWelcome to Cookies!ltBRgt"
    )
  • output.println( "ltPgt"lang" is a great
    language." )
  • output.println( "lt/BODYgtlt/HTMLgt" )
  • output.close() // close stream
  • public class CookieServlet extends HttpServlet
  • private final static String names
  • "C", "C", "Java", "Visual Basic 6"
  • private final static String isbn
    "0-13-226119-7", "0-13-5289-6", "0-13-0125-5",
    "0-13-45695-5"
  • public void doPost( HttpServletRequest
    request,
  • HttpServletResponse
    response )
  • throws ServletException, IOException
  • String language request.getParameter( "lang"
    )
  • Cookie c new Cookie( language, getISBN(
    language ) )
  • c.setMaxAge( 120 ) // cookie expires

25
An example of using Cookies (Cont.)
  • public void doGet( HttpServletRequest request,
  • HttpServletResponse
    response )
  • throws ServletException,
    IOException
  • Cookie cookies request.getCookies()
  • response.setContentType( "text/html" )
  • PrintWriter output response.getWriter()
  • output.println( "ltHTMLgtltHEADgtltTITLEgt" )
  • output.println( "Cookies II" )
  • output.println( "lt/TITLEgtlt/HEADgtltBODYgt" )
  • if ( cookies ! null cookies.length ! 0
    )
  • output.println( "ltH1gtRecommendationslt/H1gt
    " )
  • for ( int i 0 i lt cookies.length i
    )
  • output.println(cookies i .getName()
  • " Programming," " ISBN "
  • cookies i .getValue() "ltBRgt" )
  • else
  • output.println( "ltH1gtNo Recommendationslt/H1
    gt" )
  • output.println( "The cookies have
    expired." )
  • output.println( "lt/BODYgtlt/HTMLgt" )
  • output.close() // close stream
  • private String getISBN( String lang )
  • for ( int i 0 i lt names.length i )
  • if (lang.equals(namesi)) return
    isbni

26
HttpSession and Session Tracking
  • When customers at an on-line store add items to
    their shopping carts, how does the server know
    what are already in the carts?
  • When customers proceed to checkout, how can the
    server determine which previously created carts
    are theirs?
  • HTTP is stateless. HttpSession is the solution to
    provide session tracking for clients.
  • HttpSession is built on top of Cookies. It
    generates maintains session IDs transparently.

27
Steps and APIs for Session Tracking
  • Access the session embedded in Http request
    object
  • HttpSession session request.getSession(true/fal
    se)
  • Set attribute value in the session
  • session.setAttribute(key, value)
  • Get attribute value of the session
  • xxxclass value session.getAttribute(xxxkey)
  • Get other information of the session
  • session.getId() getCreationTime(),
    getLastAccessedTime(), .
  • Boolean session.isNew()
  • Remove session data
  • removeAttribute("key")

28
Rewrite the Example of Cookies by Sessions
  • public class SessionTracking extends HttpServlet
  • public void doPost( HttpServletRequest request,
  • HttpServletResponse
    response )
  • throws ServletException, IOException
  • String lang request.getParameter( "lang" )
  • HttpSession session request.getSession(
    true )
  • //setAttribute passes session to browser via
    output
  • session.setAttribute( lang, getISBN( lang))
  • output.println( session.isNew()?...)
  • output.println( session.getID()...)
  • output.println( session.getCreationTime()...)
  • output.println( session.getLastAccessedTime())
  • ..

public void doGet( HttpServletRequest request,
HttpServletResponse
response ) throws
ServletException, IOException HttpSession
session request.getSession( false ) if (
session ! null ) valueNames
session.getAttributeNames() else
valueNames null if ( valueNames ! null)
output.println( "ltH1gtList of your
purchaselt/H1gt" ) . while (
valueNames.hasMoreElements() )
name valueNames.nextElement().toString()
value session.getAttribute( name
).toString() output.println( name
value "ltBRgt" )
else output.println( No purchase" )
29
Comparisons of Cookies and Sessions
  • Cookies is persistent beyond closedown of browser
    (info is stored on disk) while Session is only
    valid for one browsing-session (stored in
    browsers memory).
  • Cookies have limited size (around 300 cookies for
    a server, 20 cookies per client and 4K bytes of
    data per cookie) while session data has no limit
    of size.
  • Due to security reason, some browsers dont
    support cookies (or they can be turned off).
Write a Comment
User Comments (0)
About PowerShow.com