38
Programming for WWW Programming for WWW (ICE 1338) (ICE 1338) Lecture #10 Lecture #10 July 28, 2004 In-Young Ko iko .AT. i cu . ac.kr Information and Communications University (ICU)

Programming for WWW (ICE 1338) Lecture #10 Lecture #10 July 28, 2004 In-Young Ko iko.AT. icu.ac.kr Information and Communications University (ICU) iko.AT

Embed Size (px)

Citation preview

Page 1: Programming for WWW (ICE 1338) Lecture #10 Lecture #10 July 28, 2004 In-Young Ko iko.AT. icu.ac.kr Information and Communications University (ICU) iko.AT

Programming for WWWProgramming for WWW(ICE 1338)(ICE 1338)

Lecture #10Lecture #10 July 28, 2004

In-Young Koiko .AT. icu.ac.kr

Information and Communications University (ICU)

Page 2: Programming for WWW (ICE 1338) Lecture #10 Lecture #10 July 28, 2004 In-Young Ko iko.AT. icu.ac.kr Information and Communications University (ICU) iko.AT

July 28, 2004 2 Programming for WWW (Lecture#10) In-Young Ko, Information Communications University

AnnouncementsAnnouncements

Class hours on Friday July 30Class hours on Friday July 30thth will be moved will be moved to to 3:00PM~5:30PM3:00PM~5:30PM

Homework #3Homework #3 is due by August 4 is due by August 4thth

Page 3: Programming for WWW (ICE 1338) Lecture #10 Lecture #10 July 28, 2004 In-Young Ko iko.AT. icu.ac.kr Information and Communications University (ICU) iko.AT

July 28, 2004 3 Programming for WWW (Lecture#10) In-Young Ko, Information Communications University

Term ProjectTerm Project Due date: Due date: August 11, 2004August 11, 2004 Based on your project proposal, develop a Web-based Based on your project proposal, develop a Web-based

information integration applicationinformation integration application Implement the major Implement the major information mediation functionsinformation mediation functions: :

Transformation, gathering, accessing & merging, abstraction, and Transformation, gathering, accessing & merging, abstraction, and maintenancemaintenance

Present the result in a GUI or in HTMLPresent the result in a GUI or in HTML SubmissionSubmission

A A project reportproject report that includes the followings: that includes the followings: Objectives of the projectObjectives of the project Web-based information integration scenarioWeb-based information integration scenario System architectureSystem architecture Operational stepsOperational steps

Program source (electronic submission)Program source (electronic submission) Project demos and presentationsProject demos and presentations on August 11 on August 11thth

20 minutes for each tem20 minutes for each tem

Page 4: Programming for WWW (ICE 1338) Lecture #10 Lecture #10 July 28, 2004 In-Young Ko iko.AT. icu.ac.kr Information and Communications University (ICU) iko.AT

July 28, 2004 4 Programming for WWW (Lecture#10) In-Young Ko, Information Communications University

Review of the Previous LectureReview of the Previous Lecture

Perl modulesPerl modules CookiesCookies Introduction to PHPIntroduction to PHP XML and XML ProcessingXML and XML Processing

Page 5: Programming for WWW (ICE 1338) Lecture #10 Lecture #10 July 28, 2004 In-Young Ko iko.AT. icu.ac.kr Information and Communications University (ICU) iko.AT

July 28, 2004 5 Programming for WWW (Lecture#10) In-Young Ko, Information Communications University

Contents of Today’s LectureContents of Today’s Lecture

XML-Based LanguagesXML-Based Languages SVG (Scalable Vector Graphics)SVG (Scalable Vector Graphics) Web ServersWeb Servers ServletsServlets

Page 6: Programming for WWW (ICE 1338) Lecture #10 Lecture #10 July 28, 2004 In-Young Ko iko.AT. icu.ac.kr Information and Communications University (ICU) iko.AT

July 28, 2004 6 Programming for WWW (Lecture#10) In-Young Ko, Information Communications University

Creating a DOM Hierarchy in JavaCreating a DOM Hierarchy in Java

import javax.xml.transform.stream.*;import javax.xml.transform.stream.*;import org.w3c.dom.*;import org.w3c.dom.*;import java.io.*;import java.io.*;

DocumentBuilderFactory docBuilderFactory =DocumentBuilderFactory docBuilderFactory = DDocumentBuilderFactory.newInstance();ocumentBuilderFactory.newInstance();

DocumentBuilder docBuilder= docBuilderFactory.newDocumentBuilder();DocumentBuilder docBuilder= docBuilderFactory.newDocumentBuilder();

// creates an XML document (in DOM)// creates an XML document (in DOM)Document doc = docBuilder.Document doc = docBuilder.newDocument()newDocument();;

// creates the root element and add to the document// creates the root element and add to the documentElement rootEle = doc.Element rootEle = doc.createElement("class")createElement("class");;doc.doc.appendChild(rootEle)appendChild(rootEle);;

// creates a sub-element and add to the root// creates a sub-element and add to the rootElement ele = doc.createElement("name");Element ele = doc.createElement("name");Text val = doc.Text val = doc.createTextNode("Prog. for WWW")createTextNode("Prog. for WWW");;ele.ele.appendChild(val)appendChild(val);;

rootEle.rootEle.appendChild(ele)appendChild(ele);;

Page 7: Programming for WWW (ICE 1338) Lecture #10 Lecture #10 July 28, 2004 In-Young Ko iko.AT. icu.ac.kr Information and Communications University (ICU) iko.AT

July 28, 2004 7 Programming for WWW (Lecture#10) In-Young Ko, Information Communications University

Creating an XML File from DOMCreating an XML File from DOM

// Creates a holder for a transformation Source tree // Creates a holder for a transformation Source tree DOMSource domSrc = DOMSource domSrc = new DOMSource(doc)new DOMSource(doc);;

// Creates an XML stream for the output// Creates an XML stream for the outputStreamResult xmlStream =StreamResult xmlStream =

new StreamResult(newnew StreamResult(new File(File("sample.xml""sample.xml"))));;TransformerFactory tFactory =TransformerFactory tFactory =

TransformerFactory.newInstance()TransformerFactory.newInstance();;Transformer transformer =Transformer transformer = tFactory.tFactory.newTransformer()newTransformer();;

// Transforms the DOM source into an XML stream// Transforms the DOM source into an XML streamtransformer.transformer.transform(domSrc, xmlStream)transform(domSrc, xmlStream);;

Page 8: Programming for WWW (ICE 1338) Lecture #10 Lecture #10 July 28, 2004 In-Young Ko iko.AT. icu.ac.kr Information and Communications University (ICU) iko.AT

July 28, 2004 8 Programming for WWW (Lecture#10) In-Young Ko, Information Communications University

XML-based LanguagesXML-based Languages

SVG (Scalable Vector Graphics)SVG (Scalable Vector Graphics): A language for : A language for describing two-dimensional graphics and describing two-dimensional graphics and graphical applications in XML graphical applications in XML ((http://www.w3.org/TR/SVG/http://www.w3.org/TR/SVG/))

MathML (Mathematical Markup Language)MathML (Mathematical Markup Language): A : A low-level specification for describing mathematics low-level specification for describing mathematics as a basis for machine to machine communication as a basis for machine to machine communication ((http://www.w3.org/Math/http://www.w3.org/Math/))

SMIL (SMIL (Synchronized Multimedia Integration Synchronized Multimedia Integration LanguageLanguage)): A language to enable simple : A language to enable simple authoring of interactive audiovisual presentations authoring of interactive audiovisual presentations ((http://www.w3.org/TR/smil20/http://www.w3.org/TR/smil20/))

RDF, SOAP, WSDL, …RDF, SOAP, WSDL, …

Page 9: Programming for WWW (ICE 1338) Lecture #10 Lecture #10 July 28, 2004 In-Young Ko iko.AT. icu.ac.kr Information and Communications University (ICU) iko.AT

July 28, 2004 9 Programming for WWW (Lecture#10) In-Young Ko, Information Communications University

SVG (SVG (Scalable Vector GraphicsScalable Vector Graphics))

SVG is a language for describing SVG is a language for describing two-dimensional two-dimensional graphicsgraphics in XML in XML

TThree types of graphic objects:hree types of graphic objects: VVector graphicector graphic shapesshapes, , IImagesmages, and , and TTextext

Graphical objects can be Graphical objects can be grouped, styled, grouped, styled, transformed and compositedtransformed and composited into previously into previously rendered objectsrendered objects

SVG drawings can be dynamic SVG drawings can be dynamic and and interactiveinteractive AnimationAnimation Zoom and panZoom and pan Activation of animation or scriptActivation of animation or script http://www.w3.org/TR/SVG/

Page 10: Programming for WWW (ICE 1338) Lecture #10 Lecture #10 July 28, 2004 In-Young Ko iko.AT. icu.ac.kr Information and Communications University (ICU) iko.AT

July 28, 2004 10 Programming for WWW (Lecture#10) In-Young Ko, Information Communications University

SVG ElementsSVG Elements Basic ShapesBasic Shapes

RRectangles (including ectangles (including optional rounded corners) optional rounded corners)

CCircles ircles EEllipses llipses LLines ines PPolylines olylines PPolygonsolygons

PathsPaths TextText AnimationAnimation Scripting (JavaScript)Scripting (JavaScript)

Page 11: Programming for WWW (ICE 1338) Lecture #10 Lecture #10 July 28, 2004 In-Young Ko iko.AT. icu.ac.kr Information and Communications University (ICU) iko.AT

July 28, 2004 11 Programming for WWW (Lecture#10) In-Young Ko, Information Communications University

A SVG ExampleA SVG Example

……<h3 id="students">Students</h3><h3 id="students">Students</h3>Here are the pictures of the Here are the pictures of the students:<br/>students:<br/><embed <embed src="src="svg_student_picture.svgsvg_student_picture.svg" " type="image/svg-xmltype="image/svg-xml"" width="500" height="360" width="500" height="360" name="studentsname="students"" border="0">border="0">……

Page 12: Programming for WWW (ICE 1338) Lecture #10 Lecture #10 July 28, 2004 In-Young Ko iko.AT. icu.ac.kr Information and Communications University (ICU) iko.AT

July 28, 2004 12 Programming for WWW (Lecture#10) In-Young Ko, Information Communications University

A SVG Example – 2D GraphicsA SVG Example – 2D Graphics<?xml version="1.0" standalone="no"?><?xml version="1.0" standalone="no"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.0//EN"<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.0//EN" ""http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtdhttp://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd">">

<svg width="500px" height="360px<svg width="500px" height="360px"" xmlns="http://www.w3.org/2000/svg"xmlns="http://www.w3.org/2000/svg">><<imageimage x="0" y="0" width="100%" height="100% x="0" y="0" width="100%" height="100%" "

xlink:href="ice1338_students1.JPG" />xlink:href="ice1338_students1.JPG" /><<gg id="students" font-size="16"> id="students" font-size="16"><<rectrect x="75" y="120" width="90" height="18" fill="white"/> x="75" y="120" width="90" height="18" fill="white"/><a xlink:href="http://vega.icu.ac.kr/~bswc28/"><a xlink:href="http://vega.icu.ac.kr/~bswc28/"><<texttext x="78" y="135" fill="blue">Moses Kim</text></a> x="78" y="135" fill="blue">Moses Kim</text></a><<rectrect x="120" y="40" width="140" height="18" fill="white"/> x="120" y="40" width="140" height="18" fill="white"/><<texttext x="123" y="55" fill="blue">Byung-woo Kang</text> x="123" y="55" fill="blue">Byung-woo Kang</text><<lineline x1="260" y1="58" x2="290" y2="120" stroke="white" stroke-width="2" /> x1="260" y1="58" x2="290" y2="120" stroke="white" stroke-width="2" /><<pathpath dd="="MM 290 120 290 120 LL 280 110 280 110 LL 288 106 288 106 zz" fill="white" " fill="white"

stroke="white" stroke-width="2" />stroke="white" stroke-width="2" />……</g></g>

svg_student_picture.svgsvg_student_picture.svg

Page 13: Programming for WWW (ICE 1338) Lecture #10 Lecture #10 July 28, 2004 In-Young Ko iko.AT. icu.ac.kr Information and Communications University (ICU) iko.AT

July 28, 2004 13 Programming for WWW (Lecture#10) In-Young Ko, Information Communications University

A SVG Example – AnimationA SVG Example – Animation……<<texttext id="TextElement" x="0" y="0 id="TextElement" x="0" y="0"" font-family="Arial" font-size="30" visibility="hidden"> font-family="Arial" font-size="30" visibility="hidden"> Go ICU !!Go ICU !! <<setset attributeName="visibility" attributeType="CSS" attributeName="visibility" attributeType="CSS"

to="visible" begin="1s" dur="6s" fill="freeze" />to="visible" begin="1s" dur="6s" fill="freeze" /> <<animateMotionanimateMotion path=" path="MM 200 50 200 50 LL 100 350 100 350""

begin="1s" dur="6s" fill="freeze" />begin="1s" dur="6s" fill="freeze" /> <<animateColoranimateColor attributeName="fill" attributeType="CSS" attributeName="fill" attributeType="CSS"

from="rgb(from="rgb(255255,,255255,0)" to="rgb(0,0,255),0)" to="rgb(0,0,255)""begin="1s" dur="6s" fill="freeze" />begin="1s" dur="6s" fill="freeze" />

<<animateTransformanimateTransform attributeName="transform" attributeName="transform" attributeType="XML" type="scale" from="1" to="2" attributeType="XML" type="scale" from="1" to="2" additive="sum" begin="1s" dur="6s" fill="freeze" />additive="sum" begin="1s" dur="6s" fill="freeze" />

</text></text>……</svg></svg> svg_student_picture.svgsvg_student_picture.svg

Page 14: Programming for WWW (ICE 1338) Lecture #10 Lecture #10 July 28, 2004 In-Young Ko iko.AT. icu.ac.kr Information and Communications University (ICU) iko.AT

July 28, 2004 14 Programming for WWW (Lecture#10) In-Young Ko, Information Communications University

SVG ReferencesSVG References

W3C SVG Page: W3C SVG Page: http://www.w3.org/Graphics/SVG/http://www.w3.org/Graphics/SVG/

Adobe SVG Zone: Adobe SVG Zone: http://www.adobe.com/svg/http://www.adobe.com/svg/

Mozilla SVG ProjMozilla SVG Project: ect: http://www.mozilla.org/projects/svg/http://www.mozilla.org/projects/svg/

Page 15: Programming for WWW (ICE 1338) Lecture #10 Lecture #10 July 28, 2004 In-Young Ko iko.AT. icu.ac.kr Information and Communications University (ICU) iko.AT

July 28, 2004 15 Programming for WWW (Lecture#10) In-Young Ko, Information Communications University

Web ServersWeb Servers

Client-server systemsClient-server systems – T – Thehe client initiates the client initiates the communication, which the server acceptscommunication, which the server accepts

All commAll communicationsunications between Web clients and between Web clients and servers use servers use HTTPHTTP

When a Web server starts, it tell its OS it is ready When a Web server starts, it tell its OS it is ready toto accept communications through a accept communications through a specific portspecific port,, usually 80usually 80

All current Web servers are descendents of the All current Web servers are descendents of the first two (CERN and NCSA)first two (CERN and NCSA) Most Most popular Web server:popular Web server: ApacheApache running under UNIX running under UNIX Microsoft IISMicrosoft IIS (Internet Information Server) is widely (Internet Information Server) is widely

used under Windowsused under WindowsAW lecture notes

Page 16: Programming for WWW (ICE 1338) Lecture #10 Lecture #10 July 28, 2004 In-Young Ko iko.AT. icu.ac.kr Information and Communications University (ICU) iko.AT

July 28, 2004 16 Programming for WWW (Lecture#10) In-Young Ko, Information Communications University

Web Server DirectoriesWeb Server Directories

DDocument ocument RRootoot:: the root directory of all the root directory of all servable documentsservable documents

e.g. e.g. /usr/local/etc/httpd/htdocs/usr/local/etc/httpd/htdocs If a request URL isIf a request URL is http://http://vega.isi.eduvega.isi.edu/bulbs/tulips.html/bulbs/tulips.html The server will search for the file with the given pathThe server will search for the file with the given path

//usr/local/etc/httpd/htdocsusr/local/etc/httpd/htdocs/bulbs/tulips.html/bulbs/tulips.html The server can have virtual document treesThe server can have virtual document trees Sometimes a different disk, possibly on a different Sometimes a different disk, possibly on a different

machine, is usedmachine, is used

AW lecture notes

Page 17: Programming for WWW (ICE 1338) Lecture #10 Lecture #10 July 28, 2004 In-Young Ko iko.AT. icu.ac.kr Information and Communications University (ICU) iko.AT

July 28, 2004 17 Programming for WWW (Lecture#10) In-Young Ko, Information Communications University

Web Server Directories Web Server Directories (cont.)(cont.)

SServer erver RRootoot:: the root directory for all of the the root directory for all of the code that implements the servercode that implements the serverThe server root usually has four filesThe server root usually has four files (dirs): (dirs): httpdhttpd: t: the code for the server itselfhe code for the server itself confconf: directory: directory for configuration information for configuration information llogsogs: directory: directory to store what has happened to store what has happened cgi-bincgi-bin: directory : directory for executable scriptsfor executable scripts

User DirectoryUser Directory: : The name of the directory The name of the directory which is appended onto a user's homewhich is appended onto a user's home directory if a directory if a ~user~user request is received request is received

e.g., e.g., public_htmlpublic_htmlAW lecture notes

Page 18: Programming for WWW (ICE 1338) Lecture #10 Lecture #10 July 28, 2004 In-Young Ko iko.AT. icu.ac.kr Information and Communications University (ICU) iko.AT

July 28, 2004 18 Programming for WWW (Lecture#10) In-Young Ko, Information Communications University

Web Server ServicesWeb Server Services

Virtual hostsVirtual hosts –– multiple multiple sites on the same sites on the same systemsystem

Proxy serversProxy servers –– to to serve documents from serve documents from thethe document roots of other sitesdocument roots of other sites

Besides HTTP, support for FTP, Gopher, Besides HTTP, support for FTP, Gopher, News, emailNews, email

Support for Support for database accessdatabase access

AW lecture notes

Page 19: Programming for WWW (ICE 1338) Lecture #10 Lecture #10 July 28, 2004 In-Young Ko iko.AT. icu.ac.kr Information and Communications University (ICU) iko.AT

July 28, 2004 19 Programming for WWW (Lecture#10) In-Young Ko, Information Communications University

Java ServletsJava Servlets

A servlet is a A servlet is a server-side version of appletserver-side version of applet Servlets are called from HTMLServlets are called from HTML

Servlet Advantages:Servlet Advantages: Can be Can be fasterfaster than CGI, because they are run than CGI, because they are run

in the server processin the server process Have Have direct access to Java direct access to Java & JDBC & JDBC APIsAPIs Because they Because they continue to runcontinue to run (unlike CGI (unlike CGI

programs), they can save programs), they can save state informationstate information Have the usual Have the usual benefits of being written in Javabenefits of being written in Java

(platform independence, ease of programming)(platform independence, ease of programming)AW lecture notes

Page 20: Programming for WWW (ICE 1338) Lecture #10 Lecture #10 July 28, 2004 In-Young Ko iko.AT. icu.ac.kr Information and Communications University (ICU) iko.AT

July 28, 2004 20 Programming for WWW (Lecture#10) In-Young Ko, Information Communications University

Servlet ContainersServlet Containers A servlet container (servlet engine) A servlet container (servlet engine) manages manages

servlets by providing the following operations:servlets by providing the following operations: Handling requestsHandling requests Passing that request to the ServletPassing that request to the Servlet Returning the response to the clientReturning the response to the client

A servlet container A servlet container interacts with a Web serverinteracts with a Web server When an HTTP request requires a servlet, the Web When an HTTP request requires a servlet, the Web

server passes the request to the servlet containerserver passes the request to the servlet container The container determines which servlet to runThe container determines which servlet to run

Servlet container implementations:Servlet container implementations: TomcatTomcat: : a widely used, freeware servlet containera widely used, freeware servlet container, ,

developed by the Apachedeveloped by the Apache Software FoundationSoftware Foundation BEA WebLogic ServerBEA WebLogic Server: one of the popular commercial : one of the popular commercial

servlet containersservlet containers

Page 21: Programming for WWW (ICE 1338) Lecture #10 Lecture #10 July 28, 2004 In-Young Ko iko.AT. icu.ac.kr Information and Communications University (ICU) iko.AT

July 28, 2004 21 Programming for WWW (Lecture#10) In-Young Ko, Information Communications University

Servlet InterfaceServlet Interface All servlets are classes that either implement theAll servlets are classes that either implement the ServletServlet interface or extend a class that interface or extend a class that implementsimplements the Servlet interfacethe Servlet interface

PProvides the interfaces for the methods that rovides the interfaces for the methods that manage servlets and their interactions with clientsmanage servlets and their interactions with clients

DDeclares three methods that are eclares three methods that are called by the called by the servlet containerservlet container (the (the life-cycle methodslife-cycle methods)) initinit –– initializes initializes the servlet and prepares it to respond to the servlet and prepares it to respond to

client requests client requests serviceservice –– controls controls how the servlet responds to requestshow the servlet responds to requests destroydestroy –– takes takes the servlet out of servicethe servlet out of service

AW lecture notes

Page 22: Programming for WWW (ICE 1338) Lecture #10 Lecture #10 July 28, 2004 In-Young Ko iko.AT. icu.ac.kr Information and Communications University (ICU) iko.AT

July 28, 2004 22 Programming for WWW (Lecture#10) In-Young Ko, Information Communications University

Servlet Interface Servlet Interface (cont.)(cont.)

The Servlet interface declares two methods The Servlet interface declares two methods that are used by the servlet:that are used by the servlet: getServletConfiggetServletConfig –– to to get initialization and get initialization and

startup parameters for itselfstartup parameters for itself getServletInfogetServletInfo –– to to allow the servlet to return allow the servlet to return

info about itself (author, version #, etc.) to info about itself (author, version #, etc.) to clientsclients

Most user-written servlet classes are Most user-written servlet classes are extensionsextensions to to HttpServletHttpServlet HttpServletHttpServlet is an extension of is an extension of GenericServletGenericServlet, ,

which implements the which implements the ServletServlet Interface)Interface)AW lecture notes

Page 23: Programming for WWW (ICE 1338) Lecture #10 Lecture #10 July 28, 2004 In-Young Ko iko.AT. icu.ac.kr Information and Communications University (ICU) iko.AT

July 28, 2004 23 Programming for WWW (Lecture#10) In-Young Ko, Information Communications University

Servlet Interface Servlet Interface (cont.)(cont.)

Two other necessary interfaces: Two other necessary interfaces: ServletResponseServletResponse – to encapsulate the – to encapsulate the

communications, client to servercommunications, client to server ServletRequestServletRequest – to encapsulate the – to encapsulate the

communications, server to clientcommunications, server to client Provides servlet access toProvides servlet access to ServletOutputStreamServletOutputStream

AW lecture notes

Page 24: Programming for WWW (ICE 1338) Lecture #10 Lecture #10 July 28, 2004 In-Young Ko iko.AT. icu.ac.kr Information and Communications University (ICU) iko.AT

July 28, 2004 24 Programming for WWW (Lecture#10) In-Young Ko, Information Communications University

HttpServletHttpServlet HttpServletHttpServlet – an abstract class – an abstract class

Extends GenericServletExtends GenericServlet Implements java.io.SerializableImplements java.io.Serializable

Every subclass of HttpServlet MUST override at Every subclass of HttpServlet MUST override at least one of the methods of HttpServletleast one of the methods of HttpServlet doGetdoGet** doPostdoPost** doPutdoPut** doDeletedoDelete** initinit destroydestroy getServletInfogetServletInfo ((* Called by the server* Called by the server))

AW lecture notes

Page 25: Programming for WWW (ICE 1338) Lecture #10 Lecture #10 July 28, 2004 In-Young Ko iko.AT. icu.ac.kr Information and Communications University (ICU) iko.AT

July 28, 2004 25 Programming for WWW (Lecture#10) In-Young Ko, Information Communications University

HttpServlet RequestHttpServlet Request The protocol of doGet:The protocol of doGet:

protected void doGet(HttpServletRequest request,protected void doGet(HttpServletRequest request, HttpServletResponse response)HttpServletResponse response) throws ServletException, java.io.IOExceptionthrows ServletException, java.io.IOException

ServletException is thrown if the ServletException is thrown if the GET GET request couldrequest could notnot be handled be handled

TThe he getParametergetParameter method method is used to access form is used to access form data from the clientdata from the client

e.g., e.g., zip = request.getParameter("zip");zip = request.getParameter("zip"); If an element has no value, the returned value is nullIf an element has no value, the returned value is null If a form value is not a string, the If a form value is not a string, the inputinput must be parsed must be parsed

e.g., e.g., price = Integer.parseInt(request.getParameter("price"));price = Integer.parseInt(request.getParameter("price"));

The protocol of doPost is the similarThe protocol of doPost is the similarAW lecture notes

Page 26: Programming for WWW (ICE 1338) Lecture #10 Lecture #10 July 28, 2004 In-Young Ko iko.AT. icu.ac.kr Information and Communications University (ICU) iko.AT

July 28, 2004 26 Programming for WWW (Lecture#10) In-Young Ko, Information Communications University

Servlet ResponseServlet Response

Use the setContentType method of the Use the setContentType method of the response object to set the content type to response object to set the content type to text/htmltext/html

response.response.setContentType("text/html")setContentType("text/html");; Create a PrintWriter object with the Create a PrintWriter object with the

getWritergetWriter method of the response objectmethod of the response objectPrintWriter servletOut = response.PrintWriter servletOut = response.getWriter()getWriter();;

AW lecture notes

Page 27: Programming for WWW (ICE 1338) Lecture #10 Lecture #10 July 28, 2004 In-Young Ko iko.AT. icu.ac.kr Information and Communications University (ICU) iko.AT

July 28, 2004 27 Programming for WWW (Lecture#10) In-Young Ko, Information Communications University

Servlet Client ExampleServlet Client Example

<html><html> <head> <title> Test greeting </title><head> <title> Test greeting </title> </head></head> <body><body> <form action = "<form action = "greetingwebapp/greetinggreetingwebapp/greeting" method = "" method = "getget">">

<input type = "text" name="name"/><br/><input type = "text" name="name"/><br/> <p>Press the button to enact the servlet <p>Press the button to enact the servlet <input type = "submit" value = "Enact Servlet" /><input type = "submit" value = "Enact Servlet" /> </p></p> </form></form> </body></body></html></html>

Page 28: Programming for WWW (ICE 1338) Lecture #10 Lecture #10 July 28, 2004 In-Young Ko iko.AT. icu.ac.kr Information and Communications University (ICU) iko.AT

July 28, 2004 28 Programming for WWW (Lecture#10) In-Young Ko, Information Communications University

Servlet ExampleServlet Exampleimport import javax.servlet.*javax.servlet.*;;import import javax.servlet.http.*javax.servlet.http.*;;import java.io.*;import java.io.*;

public class Greeting extendspublic class Greeting extends HttpServlet HttpServlet { {

public void public void doGetdoGet((HttpServletRequestHttpServletRequest request, request, HttpServletResponseHttpServletResponse response) response) throws ServletException, IOException {throws ServletException, IOException {

String inputName = request.String inputName = request.getParametergetParameter("name");("name");

PrintWriter returnHTML;PrintWriter returnHTML; response.response.setContentType("text/html")setContentType("text/html");; returnHTML = response.returnHTML = response.getWriter()getWriter();; returnHTML.println("<html><head><title>");returnHTML.println("<html><head><title>"); returnHTML.println("A simple GET servlet");returnHTML.println("A simple GET servlet"); returnHTML.println("</title></head><body>");returnHTML.println("</title></head><body>"); returnHTML.println("<h2> returnHTML.println("<h2> Hello " + inputName + “!Hello " + inputName + “! </h2>") </h2>") returnHTML.println("</body></html>");returnHTML.println("</body></html>"); returnHTML.close();returnHTML.close(); }}}}

Page 29: Programming for WWW (ICE 1338) Lecture #10 Lecture #10 July 28, 2004 In-Young Ko iko.AT. icu.ac.kr Information and Communications University (ICU) iko.AT

July 28, 2004 29 Programming for WWW (Lecture#10) In-Young Ko, Information Communications University

Servlet Mapping ExampleServlet Mapping Example<web-app><web-app> <display-name>Greeting Servlet</display-name><display-name>Greeting Servlet</display-name> <description><description>

This is a sample servlet to display a greeting message.This is a sample servlet to display a greeting message. </description></description> <servlet><servlet> <servlet-name>GreetingServlet</servlet-name><servlet-name>GreetingServlet</servlet-name> <servlet-class>Greeting</servlet-class><servlet-class>Greeting</servlet-class> </servlet></servlet> <servlet-mapping><servlet-mapping> <servlet-name>GreetingServlet</servlet-name><servlet-name>GreetingServlet</servlet-name>

<url-pattern>/greeting</url-pattern><url-pattern>/greeting</url-pattern> </servlet-mapping></servlet-mapping></web-app></web-app>

/WEB-INF/w/WEB-INF/web.xmleb.xml

Page 30: Programming for WWW (ICE 1338) Lecture #10 Lecture #10 July 28, 2004 In-Young Ko iko.AT. icu.ac.kr Information and Communications University (ICU) iko.AT

July 28, 2004 30 Programming for WWW (Lecture#10) In-Young Ko, Information Communications University

Storing Information about ClientsStoring Information about Clients

A session A session between a client and a server can between a client and a server can be managed by exchanging Cookiesbe managed by exchanging Cookies

A A CCookieookie object has data members and object has data members and methodsmethods Data membersData members:: lifetimelifetime, , namename, and the , and the

cookies’ valuecookies’ value Methods: Methods: setCommentsetComment, , setMaxAgesetMaxAge, , setValuesetValue,,

getMaxAgegetMaxAge, , getNamegetName, and , and getValuegetValue Cookie constructorCookie constructor

Cookie newCookie = Cookie newCookie = new Cookie(new Cookie(""namename"", , ""valuevalue""););

AW lecture notes

Page 31: Programming for WWW (ICE 1338) Lecture #10 Lecture #10 July 28, 2004 In-Young Ko iko.AT. icu.ac.kr Information and Communications University (ICU) iko.AT

July 28, 2004 31 Programming for WWW (Lecture#10) In-Young Ko, Information Communications University

Cookies in ServletsCookies in Servlets

By default, a cookie’s lifetime is the current By default, a cookie’s lifetime is the current sessionsession If you want it to be longer, use If you want it to be longer, use setMaxAgesetMaxAge A cookie is attached to the response with A cookie is attached to the response with

addCookieaddCookie The browser does nothing with cookies, other The browser does nothing with cookies, other

than storing them and passing them backthan storing them and passing them back A servlet gets a cookie from the browser with A servlet gets a cookie from the browser with

the getCookies methodthe getCookies methodCookieCookie[][] theCookies = request.getCookies(); theCookies = request.getCookies();

AW lecture notes

Page 32: Programming for WWW (ICE 1338) Lecture #10 Lecture #10 July 28, 2004 In-Young Ko iko.AT. icu.ac.kr Information and Communications University (ICU) iko.AT

July 28, 2004 32 Programming for WWW (Lecture#10) In-Young Ko, Information Communications University

Session TrackingSession Tracking

An An alternative to cookiesalternative to cookies Use the Use the HttpSessionHttpSession object, which can store a list object, which can store a list

of names and valuesof names and values Create a Create a SessionSession object object

Put value in the session object with Put value in the session object with putValueputValue e.g., e.g., mySession.putValue(mySession.putValue(""namename", "", "valuevalue");");

A session can be killed with the A session can be killed with the invalidateinvalidate method method A value can be removed with A value can be removed with removeValueremoveValue A value can be gotten with A value can be gotten with getValue(getValue(namename)) All names of values can be gotten withAll names of values can be gotten with getValueNamesgetValueNames

AW lecture notes

Page 33: Programming for WWW (ICE 1338) Lecture #10 Lecture #10 July 28, 2004 In-Young Ko iko.AT. icu.ac.kr Information and Communications University (ICU) iko.AT

July 28, 2004 33 Programming for WWW (Lecture#10) In-Young Ko, Information Communications University

JavaServer Pages (JSP)JavaServer Pages (JSP)

A A simplified, fast waysimplified, fast way of creating dynamic Web of creating dynamic Web pages by pages by including bits of Java code in HTMLincluding bits of Java code in HTML

ProvideProvide processing and dynamic content to HTML processing and dynamic content to HTML documents (similar to servlets)documents (similar to servlets)

Can be used as a Can be used as a server-side scripting languageserver-side scripting language (scriplets)(scriplets)

Scriplets Scriplets (JSP pages) (JSP pages) are translated by the JSP are translated by the JSP container into servletscontainer into servlets

The file extension of a JSP page is The file extension of a JSP page is .jsp.jsp rather rather than .html than .html Tells the server that this page Tells the server that this page requires special handlingrequires special handling

AW lecture noteshttp://java.sun.com/developer/technicalArticles/javaserverpages/servlets_jsp/

Page 34: Programming for WWW (ICE 1338) Lecture #10 Lecture #10 July 28, 2004 In-Young Ko iko.AT. icu.ac.kr Information and Communications University (ICU) iko.AT

July 28, 2004 34 Programming for WWW (Lecture#10) In-Young Ko, Information Communications University

A Simple JSP ExampleA Simple JSP Example

<HTML><HTML><HEAD><TITLE>Welcome to Our Store</TITLE></HEAD><HEAD><TITLE>Welcome to Our Store</TITLE></HEAD><BODY><BODY><H1>Welcome to Our Store</H1><H1>Welcome to Our Store</H1><SMALL>Welcome,<SMALL>Welcome,<!-- User name is "New User" for first-time visitors --> <!-- User name is "New User" for first-time visitors --> <% out.println(Utils.getUserNameFromCookie(request)); %><% out.println(Utils.getUserNameFromCookie(request)); %>To access your account settings, clickTo access your account settings, click<A HREF="Account-Settings.html">here.</A></SMALL><A HREF="Account-Settings.html">here.</A></SMALL><P><P>……</BODY></BODY></HTML></HTML>

http://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/Servlet-Tutorial-Overview.html

Page 35: Programming for WWW (ICE 1338) Lecture #10 Lecture #10 July 28, 2004 In-Young Ko iko.AT. icu.ac.kr Information and Communications University (ICU) iko.AT

July 28, 2004 35 Programming for WWW (Lecture#10) In-Young Ko, Information Communications University

JSP Execution MechanismJSP Execution Mechanism When a JSP page is called, it will be When a JSP page is called, it will be compiled compiled

(by the JSP engine) into a Java servlet(by the JSP engine) into a Java servlet The servlet engine then loads the servlet class The servlet engine then loads the servlet class

(using a class loader) and (using a class loader) and executes itexecutes it to create to create dynamic HTML to be sent to the browserdynamic HTML to be sent to the browser

http://java.sun.com/developer/technicalArticles/javaserverpages/servlets_jsp/

The next time the page is The next time the page is requested, the JSP engine requested, the JSP engine executes the already-loaded executes the already-loaded servletservlet

If the JSP page has changed, If the JSP page has changed, it is it is automatically recompiledautomatically recompiled into a servlet and executedinto a servlet and executed

Page 36: Programming for WWW (ICE 1338) Lecture #10 Lecture #10 July 28, 2004 In-Young Ko iko.AT. icu.ac.kr Information and Communications University (ICU) iko.AT

July 28, 2004 36 Programming for WWW (Lecture#10) In-Young Ko, Information Communications University

JSP ExampleJSP Example<%@ page import="hello.NameHandler" %><%@ page import="hello.NameHandler" %><jsp:useBean id="mybean" scope="page" class="hello.NameHandler" /><jsp:useBean id="mybean" scope="page" class="hello.NameHandler" /><jsp:setProperty name="mybean" property="*" /><jsp:setProperty name="mybean" property="*" /><html><html><head><title>Hello, User</title></head><head><title>Hello, User</title></head><body bgcolor="#ffffff" background="background.gif"><body bgcolor="#ffffff" background="background.gif"><%@ include file="dukebanner.html" %><%@ include file="dukebanner.html" %>

<table border="0" width="700"><table border="0" width="700"><tr><td width="150"> &nbsp; </td><tr><td width="150"> &nbsp; </td><td width="550"><h1>My name is Duke. What's yours?<td width="550"><h1>My name is Duke. What's yours?</h1></td></tr></h1></td></tr><tr><td width="150" &nbsp; </td><td width="550"><tr><td width="150" &nbsp; </td><td width="550"> <form method="get"><form method="get"> <input type="text" name="<input type="text" name="usernameusername" size="25"><br>" size="25"><br> <input type="submit" value="Submit"><input type="submit" value="Submit"> <input type="reset" value="Reset"></td><input type="reset" value="Reset"></td></tr></form></table></tr></form></table><% if ( request.getParameter("<% if ( request.getParameter("usernameusername") != null ) { %>") != null ) { %><%@ include file="response.jsp" %><%@ include file="response.jsp" %><% } %><% } %></body></html></body></html> http://java.sun.com/products/jsp/html/jspbasics.fm2.html

hellouser.jsphellouser.jsp

Page 37: Programming for WWW (ICE 1338) Lecture #10 Lecture #10 July 28, 2004 In-Young Ko iko.AT. icu.ac.kr Information and Communications University (ICU) iko.AT

July 28, 2004 37 Programming for WWW (Lecture#10) In-Young Ko, Information Communications University

JSP Example JSP Example (cont.)(cont.)

<table border="0" width="700"><table border="0" width="700"><tr><tr><td width="150"> &nbsp; </td><td width="150"> &nbsp; </td><td width="550"><td width="550"><h1>Hello, <h1>Hello, <jsp:getProperty name="mybean" <jsp:getProperty name="mybean" property="username" />!property="username" />!</h1></h1></td></td></tr></tr></table></table>

http://java.sun.com/products/jsp/html/jspbasics.fm2.html

response.jspresponse.jsp

package hello;public class NameHandler { private String username; public NameHandler() { username = null; } public void setUsername(String name) { username = name; } public String getUsername() { return username; }}

nnamehandler.javaamehandler.java

Page 38: Programming for WWW (ICE 1338) Lecture #10 Lecture #10 July 28, 2004 In-Young Ko iko.AT. icu.ac.kr Information and Communications University (ICU) iko.AT

July 28, 2004 38 Programming for WWW (Lecture#10) In-Young Ko, Information Communications University

Servlet ReferencesServlet References The Java Servlet API White Paper: The Java Servlet API White Paper:

http://java.sun.com/products/servlet/whitepaper.htmlhttp://java.sun.com/products/servlet/whitepaper.html Java Servlet Technology: Java Servlet Technology:

http://java.sun.com/products/servlet/http://java.sun.com/products/servlet/ J2EE API Manual: J2EE API Manual:

http://java.sun.com/j2ee/1.4/docs/api/index.htmlhttp://java.sun.com/j2ee/1.4/docs/api/index.html Java Servlet Tutorial: Java Servlet Tutorial:

http://java.sun.com/j2ee/tutorial/1_3-fcs/doc/Servlets.htmlhttp://java.sun.com/j2ee/tutorial/1_3-fcs/doc/Servlets.html Servlets and JSP Pages Best Practices: Servlets and JSP Pages Best Practices:

http://java.sun.com/developer/technicalArticles/javaserverphttp://java.sun.com/developer/technicalArticles/javaserverpages/servlets_jsp/ ages/servlets_jsp/

Apache Jakarta Tomcat: Apache Jakarta Tomcat: http://jakarta.apache.org/tomcat/http://jakarta.apache.org/tomcat/