Web Technology A computer Science perspective
Pradeep Pocha
11th Feb 2012
What is a protocol?
Protocol An agreement about how to do something
This enables computers and software built by different people to be able to communicate in the same language
Examples that we have seen:
Hyper Text Transfer Protocol (HTTP) Web Browser File Transfer Protocol (FTP) File transfer Simple Mail Transfer Protocol (SMTP) Email Internet Protocol (IP) Packets across the Internet
#1
Human Protocols
Sending a letter via the postal service
Shayne Evans 5501 Sennott Sq. Pittsburgh, PA. 15260 Kim Morrison Contents! St. 123 Somewhere Someplace, PA. 15555
#1
Computer Protocols
Sending a packet via the network
To: From: 192.168.1.1 on port 23 192.168.1.110 on port 6710
Payload: The contents of the message belong here.
#1
Visual Comparison
To: 192.168.1.1 on port 23 From: 192.168.1.110 on port 6710
Payload: The contents of the message belong here.
Contents!!! Shayne Evans 5501 Sennott Sq. Pittsburgh, PA. 15260 Contents! Kim Morrison
#1
123 Somewhere St. Someplace, PA. 15555
Textual Comparison
The address of the letter is the destination of the packet The return address of the letter is the source of the packet The content of the envelope is the payload of the packet In both protocols, if you disobey the rules your message will not be received
#1
Protocol Layers
Protocols can be layered on top of other protocols to enable new ways of communicating
#1
Example: Writing a letter
A common protocol that is followed when writing a letter is:
[Date]
Dear [Recipient],
[Body of message goes here] [Closing] [Sender signature] [Sender name]
#1
Example: Writing a letter
A common protocol that is followed when writing a letter is:
04/01/2008
Dear Kim,
Hey there! Whats up? Im good. Thanks. Sincerely,
Shayne Evans
Shayne Evans #1
Example: Writing a Letter
After following the protocol for writing a letter, I can use the protocol for sending a letter via the postal service:
Shayne Evans 5501 Sennott Sq. Dear Kim, Pittsburgh, PA. 15260 04/01/2008
Hey there! Whats up? Im good. Thanks. Kim Morrison 123 Somewhere St. Sincerely,Someplace, PA. 15555
Shayne Evans
Shayne Evans
#1
Example: Writing a letter
Thus, I have layered two protocols on top of each other.
Letter Writing Protocol
Sending a Letter via USPS Protocol
The lower protocol provides a service used by the higher protocols.
#1
Protocol Layering: The Internet is build this way
Internet Protocol (IP) provides a way to deliver packets to a destination
SSH, FTP, HTTP, SMTP
DNS, VoIP
TCP
UDP
Internet Protocol #1
Protocol Layering: The Internet is build this way
TCP uses packets to maintain connections across a network, and thus is layered above IP
SSH, FTP, HTTP, SMTP
DNS, VoIP
TCP
UDP
Internet Protocol #1
Protocol Layering: The Internet is build this way
UDP just sends or receives raw packets with a best-effort approach, also layered above IP
SSH, FTP, HTTP, SMTP
DNS, VoIP
TCP
UDP
Internet Protocol #1
Protocol Layering: The Internet is build this way
SSH, FTP, HTTP, SMTP and many more applications use TCP connections to communicate data back and forth
SSH, FTP, HTTP, SMTP DNS, VoIP
TCP
UDP
Internet Protocol #1
Protocol Layering: The Internet is build this way
DNS, VoIP, and many more applications use UDP packets to communicate data
SSH, FTP, HTTP, SMTP
DNS, VoIP
TCP
UDP
Internet Protocol #1
HTTP Request Messages
GET retrieve document specified by URL PUT store specified document under given URL HEAD retrieve info. about document specified by URL OPTIONS retrieve information about available options POST give information (eg. annotation) to the server DELETE remove document specified by URL TRACE loopback request message CONNECT for use by caches
CS 640 17
HTTP Response Codes
1xx Informational request received, processing 2xx Success action received, understood, accepted 3xx Redirection further action necessary 4xx Client Error bad syntax or cannot be fulfilled 5xx Server Error server failed
CS 640
18
URI,URN,URL
Uniform Resource Identifier
Information about a resource
Uniform Resource Name
The name of the resource with in a namespace
Uniform Resource Locator
How to find the resource, a URI that says how to find the resource
Using HTML/XHTML
XHTML is relatively simple. You do most of your work with about twenty tags. XHTML is orderly and structured Good references and tutorial sites are available Follow the standards and your work will be much simpler, more consistent, and your results more reliable
Plus your co-workers will like you more
Device Independence
Your audience may view your site with many different devices and browser types.
The Browser
The browser is not print!
The Browser Is Not Print
No fixed page size No fixed page length User can change the font size User can link to her/his own local style sheet Screen size can be tiny or huge
The Adjustable Document
The Birth of HTML
Created by Tim Berners-Lee at CERN Open standard developed under supervision of the World Wide Web Consortium (www.w3.org)
Works to ensure the full potential of the Web for shared, integrated functionality is realized
The History of HTML/XHTML
1992 HTML first defined 1994 HTML 2.0 1995 Netscape specific non-standard HTML 1996 HTML 3.2, compromise version 1997 HTML 4.0, separates content from presentation 1998 XML standard for writing Web languages 2000 XHTML 1.0, XML compliant HTML 2002 XHTML 2.0
Problems With HTML
Competing versions of browsers introduced features beyond the standards Inconsistent implementations of display engines and scripting Content and presentation mixed together
Layout often done with tables Each element had many presentation attributes, resulting in laborious maintenance
The Slop Code Era
XHTML
XHTML is a version of HTML modified to conform to the XML standard Designed to separate content from presentation
Content in XHTML Presentation controlled by Cascading Style Sheets (CSS)
Extensible Additional elements can be defined XML Compatible Other XML based languages can be embedded in XHTML documents Like a programming language
Specific syntax to use Validators help you get it right
XHTML Differences
Case is significant All elements must have begin tags and end tags <p>Hello</p> Empty elements contain their own end tag <br /> Attribute values must be enclosed in quotation marks More specfics available at http://www.w3.org/TR/xhtml1/#diffs
A Simple XHTML File
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title> My Home Page </title> </head> <body> <h1>My Home Page </h1> <p> Welcome to my home page </p> </body> </html>
Hierarchical Structure
Well formed xhtml forms a hierarchy
Content Types
Documents are made up of logical types of content.
Semantic Structure
Content of the same type usually is formatted to look the same.
Semantic Markup
HTML markup is based on logical content types
Hierarchy
The resulting hierarchy
The DOCTYPE Statement
Declares the specific version of HTML or XHTML being used on the page Used by the browser to decide how to process the page Three types
Transitional - Forgiving Strict Requires adherence to standards Frameset Use if page has frames
Always first in file
Strict DOCTYPE
Enter exactly as below
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> Using Strict encourages standards based coding
Validators will flag logical errors in your methods Your CSS will work better and more predictably
Elements
Consist of three parts
Begin tag, which can contain attributes Contents End tag
Example: <p id=intro>Welcome</p> W3schools specifications for <p> http://www.w3schools.com/tags/tag_p.asp
Attributes
Always only used in the element begin tag Three types
Optional attributes: Varies with element type Standard attributes: id, class, title, style, dir, lang, xml:lang Event attributes: onclick, ondblclick, onmousedown, onmouseup, onmouseover, onmousemove, onmouseout, onkeypress, onkeydown, onkeyup
Used in scripting
Empty Elements
Some elements have no content and therefore also have no end tag
<img src=photo.jpg /> <br /> <hr /> <link rel="stylesheet" type="text/css" href=main.css" />
In XHTML, which requires end tags on all elements, a single tag represents both the begin and end tag
<h1>, <h2>, <h3>, etc.
Headings on the page Represent the main topic, subtopics, subsubtopics, etc. of the page Important to use they in a logical manner, which greatly helps assistive technology like voice browsers present the page content intelligibly
<p>
Paragraph Important for presentation control to put text in an element. When in doubt, put text in a paragraph Blockquotes (<blockquote>) except they have wider left and right margins
Lists
Unordered lists (bulleted lists) <ul> <li>One</li> <li>Two</li> </ul> Ordered lists (numbered lists) <ol> <li>One</li> <li>Two</li> </ol>
Text Markup
Bolding
<b>text</b> <strong>text</strong>
Italics
<i>text</i> <em>text</em>
Other
<sub>text</sub> subscript <sup>text</sup> superscript <del>text</del> deleted text
Tables
<table border cellspacing="5" cellpadding="10"> <caption>People on the team</caption> <tr> <th>Name</th> <th>Position</th> </tr> <tr> <td>Mary</td> <td>Analyst</td> </tr> <tr> <td>John</td> <td>Technician</td> </tr> </table>
Graphics
Graphics are placed by using an img element The alt attribute provides alternative text describing the graphic in case the graphic itself cannot be shown or the user cannot see the graphic <img src="picture.gif" alt="Suzzallo">
Anchors
Anchors can link your page to any file on the Web
<a href="http://www.washington.edu/"> University of Washington </a>
Divs
Divs enclose a set of elements
<div style=text-align: center;> <h2> News</h2> <p><a href=budget.html>Budget</a></p> <p><a href=invest.html>Investment</a></p> </div>
Spans
Spans enclose objects (text, graphics) within an element
<p>Call me Ishmael. Some years ago <span style=font-style: italic;>never mind how long precisely</span> having little or no money in my purse, and nothing particular to interest me on shore,
Cascading Style Sheets
Are used to control how elements are presented in the Web page Use a different syntax that HTML/XHTML Work with the common visual browsers (Internet Explorer, FireFox, Opera) Used properly, can great simplify visual design, site management and content maintenance
A Style
Selector Property Value p { font-family: times; } Note the punctuation: The property is followed by a colon (:) and the value is followed by a semicolon(;)
Using CSS
Styles can be set in a stylesheet, in a style element in the head or in a style attribute
Selectors
Simple selectors p { color: blue } h1, h2, h3, h4 { font-style: italic; } Contextual selectors ul li { font-weight: bold; } #main img { border: solid black 5px; } p.intro { font-family: verdana, sans-serif;}
The Box Model
Each element has padding, border, and margin
Vertical Margins
The larger of the two vertical margins will determine the distance between elements
Visual Formatting Model
Pages are built as a series of blocks stacked from the top down
Controlling Layout
Styles can control size and placement of elements Example: #nav { width: 12em; float: left; } #news { width: 12em; float: right; } #main { margin: 1em 13em 1em 13em;
Nav Div Float Left
Nav Div Float Right
Nav Across Top
Items in the Nav bar are anchors within a div
HTML-Kit
HTML-Kit (Windows) is free editor that makes it easy to make standards compliant XHTML
HTML-Kit Has Tidy
Press F9 and your XHTML is validated and tidied for easy reading
Resources
HTML-Kit editor http://chami.com/ Amaya editor http://www.w3c.org/Amaya W3schools XHTML and CSS tutorials http://www.w3schools.com/ Web Head Start tutorials http://www.webheadstart.org/ Tidy Web Interface - http://www.washington.edu/webinfo/tidy.cgi CSS Validator - http://jigsaw.w3.org/css-validator/ Dave Raggett XHTML and CSS tutorials http://www.w3.org/MarkUp/Guide/Overview.html Web Accessibility in Mind (WebAIM) - http://www.webaim.org/ Color contrast analyzer http://www.visionaustralia.org.au/info.aspx?page=628 Stylin With CSS, A Designers Guide, Second Edition by Charles Wyke-Smith
Web Application
64
Model 1 Architecture
Model 1 Architecture
Model 2 Architecture
Model 2 Architecture
Model-View-Controller
Servlet
A servlet is a JavaTM technology-based Web component, managed by a container, that generates dynamic content. --- Servlet API Specification, Version 2.4 The servlet container is a part of a Web server or application server that provides the network services over which requests and responses are sent, decodes MIME-based requests, and formats MIME-based responses. A servlet container also contains and manages servlets through their lifecycle
Web App Processing with Servlet
URL
Request
Client
Web Server App (e.g. Apache)
Web Container App (e.g. Tomcat)
Web Server Machine Servlet
Web App Processing with Servlet
Apache forwards HTTP request to Tomcat Using AJP protocol URL
Request
Client
Web Server App (e.g. Apache)
Web Container App (e.g. Tomcat)
Web Server Machine Servlet
Web App Processing with Servlet
Tomcat uses the mapping info in a configuration file called web.xml of the web application to find the right servlet
Request
Client
Web Server App (e.g. Apache)
Web Container App (e.g. Tomcat)
Web Server Machine Servlet
Web App Processing with Servlet
Tomcat uses the mapping info in a configuration file called web.xml of the web application to find the right servlet
Client
Web Server App (e.g. Apache)
Web Container App (e.g. Tomcat)
Web Server Machine Servlet
Response
Web App Processing with Servlet
Client
Web Server App (e.g. Apache)
Response
Web Container App (e.g. Tomcat)
Web Server Machine Servlet
Web App Processing with Servlet
Client
Response
Web Server App (e.g. Apache)
Web Container App (e.g. Tomcat)
Web Server Machine Servlet
What Container Provides?
Communication Support (to web server; no socket code) Lifecycle Management of Servlet (loading; instantiating; initializing; invoking; garbage collection; fault tolerance) Multithread Support (create threat for each servlet request) Declarative Security (use XML deployment descriptor to configure/modify security without having to hard-code it into servlet code) JSP Support (translating that JSP code into real java)
What a Simple Servlet looks Like?
import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class SimpleServlet extends HttpServlet { public void doGet (HttpServletRequest request, HttpServletResponse response) throws IOException { PrintWriter out = response.getWriter(); java.util.Date today = new java.util.Date(); out.println("<html><body><h1>This is a simple web page generated by SimpleServlet with date info.</h1><br>Today is "+today+"</body></html>"); } }
What a Servlet Code looks Like?
package com.example.web; import com.example.model.*; import javax.servlet.*; import javax.servlet.http.*; import java.io.*; import java.util.*; public class BeerSelect extends HttpServlet { public void doPost (HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String c = request.getParameter("color"); BeerExpert be = new BeerExpert(); List result = be.getBrands(c); request.setAttribute("styles", result); RequestDispatcher view = request.getRequestDispatcher("result.jsp"); view.forward(request, response); } }
How Does Container Find Right Servlet?
Using the Deployment Descriptor web.xml <web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" version="2.4"> <servlet> <servlet-name> CS301 Simple Servlet</servlet-name> <servlet-class> SimpleServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name> CS301 Simple Servlet</servlet-name> <url-pattern> /s1</url-pattern> </servlet-mapping> </web-app> This mapping improves flexibility and security. How?
A Simple Web Application Following ModelView-Controller Design Pattern
Servlet
Controller e.g. BeerSelect.java
<% JSP Class Beer{ //Business //Logic }
%>
View e.g. result.jsp
Model e.g., BeerExpert.java
File Structure in A Java Web Development Environment
beerV1
etc
lib
src
classes
web
<webapp> Web.xml </webapp>
com
example
<% result.jsp %>
model
web
BeerExpert.java
BeerSelect.java
File Structure in a Java Web Deployment Environment
<webapp> Web.xml </webapp>
tomcatChow
webapps
Beer-v1
WEB-INF
classes com example
lib
<% result.jsp %>
Form.html
model
web
BeerExpert.java
BeerSelect.java
Servlet with JDBC demo
import java.sql.*; import javax.sql.*; public class InventoryDBServlet extends HttpServlet { Driver D; Connection con; Statement stmt; PrintWriter out = response.getWriter(); try { Class.forName("org.gjt.mm.mysql.Driver").newInstance(); } catch(java.lang.ClassNotFoundException e) { System.err.print("ClassNotFoundException: +e.getMessage()); } String url="jdbc:mysql://blanca.uccs.edu:3306/"+database+"?user="+user+"&password="+passwd; con = DriverManager.getConnection(url); stmt = con.createStatement(); String sqlcmd = "select * from inventory"; ResultSet rs = stmt.executeQuery(sqlcmd); while (rs.next()) { StringBuffer itemName = new StringBuffer(rs.getString(1)); StringBuffer amount = new StringBuffer(rs.getString(2)); out.println("<tr bgcolor=\"#FFBBDD\"><td align=center>"+itemName+"</td><td align=right> "+amount+"</tr>"); } }
JSP with JSTL SQL Tag Demo
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql" %> <sql:query var="rs" dataSource="jdbc/InventoryDB"> select price.item, price.unitPrice, inventory.amount from price, inventory where price.item = inventory.item </sql:query> <html> <head> <title>DBcatalog</title> </head> <body> <h2>DB Catalog Retrieval Results</h2> <table border=1> <tr bgcolor="#EEDDCC"> <th>item</th><th>unitPrice</th><th>amount</th></tr> <c:set var="counter" value="1" /> <c:forEach var="row" items="${rs.rows}"> <c:choose> <c:when test="${counter mod 2 == 0}"> <tr bgcolor="#99EEFF"> </c:when> <c:otherwise> <tr bgcolor="#99FFAA"> </c:otherwise> </c:choose> <td align=center>${row.item}</td> <td align=right>${row.unitPrice}</td> <td align=right>${row.amount}</td> </tr> <c:set var="counter" value="${counter+1}" /> </c:forEach> </table> </body> </html>
JSP with SQL:UPDATE Parameter Access
Demo http://windom.uccs.edu:9888/sql/passwd.jsp Source <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql" %> <!-- c:set tag need to terminate with /> --> <c:set var="login" value="${param.login}" /> <c:set var="password" value="${param.password}" /> <c:if test="${!empty login and !empty password}"> <sql:update var="result" dataSource="jdbc/InventoryDB" sql="insert into password values (?, ?)" > <sql:param value="${login}" /> <sql:param value="${password}" /> </sql:update> </c:if> Note that we really do not need to set login/password variable. Just use directly in <sql:param value="${param.login}" /> and in <c:if>
JDBC
Load the driver class Get a connection Create a statement Execute the query, returns ResultSet Iterate through ResultSet
JDBC Example
// Load the Oracle JDBC driver Class.forName ("oracle.jdbc.driver.OracleDriver"); //Connect to DB server as authorized user Connection conn = DriverManager.getConnection ("jdbc:oracle:thin:@orion.towson.edu:1521:cosc", account, password); // Create a JDBC Statement to hold SQL query Statement stmt = conn.createStatement (); ResultSet rset = stmt.executeQuery ("select ticker from stocks"); // Iterate through the result and print the employee names while (rset.next ()) { out.println (rset.getString (1)); }
Storing and Sharing Data
Persistent Database, Flat files Temporary Class level variable, Session, Application context Session cookie
Server side
Client side
Persistent cookie
87
HTTP State and Session
What is a session?
A serial of consecutive and related requests from and responses to a single client, in a certain duration and scope
What is state?
State is the information to describe or identify a session at a certain point of time Stateful: each request/response can maintain its state at different points of times
Phone calls are stateful
Stateless: each request/response cannot maintain its state at different points of times
HTTP protocol is stateless, i.e., HTTP itself does not provide mechanisms to maintain state information for each request/response. In other words, HTTP does not remember.
88
Applications
Where is session/state needed?
User sign-in status A transaction involving multiple steps (requests/responses), such as
shopping (cart) multi-page survey or multi-page test auto insurance quote
User preferences, personalization, customization
89
Making HTTP Stateful
HTTP itself is not stateful. Application level statement management is needed. How to manage state (with Java platform)?
Cookie (persistent cookie and session cookie) Java session API URL rewriting Using form hidden variables
90
Cookies
Cookie is a small piece of textual information stored on the client computer which web servers can interact with
Cookie facts
Cookie is pure text information Cookie is sent with HTTP headers Cookie has restrictions (number, size, domain, path)
For more cookie informaiton
http://wp.netscape.com/newsref/std/cookie_spec.html http://www.w3.org/Protocols/rfc2109/rfc2109.txt http://kristol.org/cookie/
91
Cookie Life Cycle
Server side
Response to set cookies
Client Computer
Persistent Cookie
Servlets or JSPs
Response to set cookies
Session Cookie
Subsequent requests: Cookie is sent with HTTP header
Cookie expires at certain duration
92
Java Cookie API
javax.servlet.http.Cookie
Creating a cookie
Cookie cookie=new Cookie(cookieName, cookieValue); cookie.setMaxAge(int seconds); //only for persistent cookie response.addCookie(cookie); //sending cookie to client
Reading a cookie
Cookie cookies[]=request.getCookies() getName() and getValue()
93 and Listing 8.2 See example cookieset.jsp, cookieread.jsp
Session Cookie
Session cookie is not saved to the disk; it only exist in the memory for the duration of the browser
Session cookie expires when the browser window is closed
Dont set maxAge when creating a session cookie Note: a session cookie JSESSIONID is automatically set by the server
94 See example cookieset.jsp and cookieread.jsp
Cookie Practices
Cookies only handle simple data
Numbers, characters, strings
Persistent cookies save data on client computers for a certain period of time
A unique feature that can be utilized Often used to save user preferences or convenience information
See example cookieset.jsp and cookieread.jsp
Client computers might block cookies
See IE privacy settings How to detect that? See section 8.3
95
Web Application Server Session
State information can also be saved on the server side (in server memory)
How to relate each visit/client with a specific session (server memory storage)?
Each visit/session is identified by a unique ID (session id), which is passed with every request What are the ways to pass this ID to server?
Session duration
On the server side, session duration is set by the server. Session expires when there is no activity for a certain amount of time.
96
Session Life Cycle
Server side
Session Created Server Memory
Client Browser
1st request
First response: session id is set
Session Cookie
Put data into memory
Servlets or JSPs Subsequent requests: session id is sent to server
Read data from memory
Session ends after a certain idle period
97
Session ends after browser is closed*
Servlet Session API
Session class
javax.servlet.http.HttpSession object represents a session
To get a session object
Servlet
Session session=request.getSession();
JSP: session is given as an implicit object
Properties
Session ID: session.getId() Creation time Is it a new session?
98 See example sessioninfo1.jsp and sessioninfo2.jsp; or Listing 9.1
Using Session API
Web server settings
Session is automatically created by web server Session ID is automatically generated by web server Session ID is sent to client (either as session cookie or URL parameter) automatically
Store data in session
session.setAttribute()
Read data from session
session.getAttribute()
needs type casting if an object is stored in the session
99 See example sessioninfo1.jsp and sessioninfo2.jsp; or Listing 9.1
Session Practice
What data to put in session?
Information that should be shared during a users visit of multiple requests
User preferences, choices User status, e.g. login information Shopping cart information Temporary data between page transition
How much data to put in session?
Use session only for necessary and frequently accessed data
100
Servlet Class Variables
Class level variable is accessed and shared by all requests to the same servlet (JSP page)
For JSP page, it is the variable defined in the declaration element
The value of the variable remains in the memory until the servlet is reloaded
Example
Counter of the servlet/JSP page How to prevent count cheating?
See example classvariable.jsp
101
Application Context API
To share the data application wide (across all sessions), use the ServletContext class
javax.servlet.ServletContext class
To get the application context object
Servlet
ServletContext application=this.getServletContext();
JSP: application is given as an implicit object
Usage
A counter of user visits (sessions)
102
Web Application Events
A J2EE web application (context), and every session, has its own life cycle
Usage
How to count website (application) visits? How to perform some operations every time a user issues the first request (for any file)
For more information
http://www.stardeveloper.com/articles/display.html?article=2001111901
103
Summary: Data Sharing and Access
JSP/Servlet JSP/Servlet JSP/Servlet ServletContext / application
Class Level Variable shares information across all computers, but within that JSP/servlet Request/Response Session / session cookie shares information only for that session
Computer A
Computer B
104
Persistent cookie shares information for all sessions on one computer
References:
www.cs.pitt.edu/~sevans/cs110/protocols.ppt(#1)
XHTML and CSS:Rick Ells UW Technology
http://staff.washington.edu/rells/
Java Web Application Framework (WAF)
Melek OKTAY 50050403
[email protected] Servlet and JSP C Edward Chow
Data Sharing and State Management -Jack G. Zheng
CS 640
105