web application: java servlets ine2720 web application software development essential materials

94
Web Application: Web Application: Java Servlets Java Servlets INE2720 INE2720 Web Application Software Web Application Software Development Development Essential Materials Essential Materials

Post on 18-Dec-2015

216 views

Category:

Documents


0 download

TRANSCRIPT

Web Application:Web Application:Java ServletsJava Servlets

INE2720INE2720

Web Application Software Web Application Software DevelopmentDevelopment

Essential MaterialsEssential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

22

OutlineOutline

Overview of Web application, Servlet technologyOverview of Web application, Servlet technology Writing your first servletWriting your first servlet Running and debugging ServletsRunning and debugging Servlets Handling the client requestHandling the client request

– Form data, retrieve parametersForm data, retrieve parameters– Understand HTTP, HTTP request headersUnderstand HTTP, HTTP request headers

Generating the server responseGenerating the server response– HTTP status codesHTTP status codes– HTTP response headersHTTP response headers

Advanced Servlet ConceptsAdvanced Servlet Concepts– HTTP Redirects, Handling cookies, Session trackingHTTP Redirects, Handling cookies, Session tracking

Review ServletsReview Servlets

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

33

Web Application Web Application TopicsTopics Web Application ArchitectureWeb Application Architecture

– 1-, 2-, 3-Tier Architectures1-, 2-, 3-Tier Architectures J2EE frameworkJ2EE framework

– Java ServletsJava Servlets– JavaServer PagesJavaServer Pages– Enterprise JavaBeansEnterprise JavaBeans– JDBCJDBC– JavaMailJavaMail– Java Transaction Service (JTS), …Java Transaction Service (JTS), …

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

44

Web Application modelWeb Application model

Client Tier Middle TierEnterprise Information

System (EIS) Tier

application

browser

Web Container

ServletServlet

JSP…

DatabaseJDBC

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

55

A Servlet’s JobA Servlet’s Job

ReadRead explicit data sent by client (form data) explicit data sent by client (form data) ReadRead implicit data sent by client (request implicit data sent by client (request

headers)headers) GenerateGenerate the results the results SendSend the explicit data back to client (HTML) the explicit data back to client (HTML) Send Send the implicit data to clientthe implicit data to client

(status codes and response headers)(status codes and response headers)

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

66

The Advantages of The Advantages of Servlets Over Servlets Over “Traditional” CGI“Traditional” CGI Efficient Efficient

– Threads instead of OS processes, one servlet copy, Threads instead of OS processes, one servlet copy, persistencepersistence

ConvenientConvenient– Lots of high-level utilitiesLots of high-level utilities

PowerfulPowerful– Sharing data, pooling, persistenceSharing data, pooling, persistence

PortablePortable– Run on virtually all operating systems and serversRun on virtually all operating systems and servers

SecureSecure– No shell escapes, no buffer overflowsNo shell escapes, no buffer overflows

InexpensiveInexpensive

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

77

Why Build Pages Why Build Pages Dynamically?Dynamically?

The Web page is based on data submitted The Web page is based on data submitted by the userby the user– E.g., results page from search engines and E.g., results page from search engines and

order-confirmation pages at on-line storesorder-confirmation pages at on-line stores The Web page is derived from data that The Web page is derived from data that

changes frequentlychanges frequently (E.g., a weather (E.g., a weather report)report)

The Web page uses information from The Web page uses information from databases or other server-side sourcesdatabases or other server-side sources – E.g., an e-commerce site could use a servlet to E.g., an e-commerce site could use a servlet to

build a Web page that lists the current price build a Web page that lists the current price and availability of each item that is for saleand availability of each item that is for sale

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

88

Free Servlet and JSP Free Servlet and JSP EnginesEngines(Servlet/JSP Containers)(Servlet/JSP Containers) Apache TomcatApache Tomcat

– http://http://jakarta.apache.orgjakarta.apache.org/tomcat//tomcat/– Version 4.1.12 - support Servlet 2.3 and JSP 1.2Version 4.1.12 - support Servlet 2.3 and JSP 1.2– Version 5 – support Servlet 2.4 and JSP 2.0Version 5 – support Servlet 2.4 and JSP 2.0

Allaire/Macromedia JRunAllaire/Macromedia JRun– http://http://www.allaire.com/products/jrunwww.allaire.com/products/jrun//

New Atlanta ServletExecNew Atlanta ServletExec– http://http://www.servletexec.comwww.servletexec.com//

Gefion Software LiteWebServerGefion Software LiteWebServer– http://http://www.gefionsoftware.com/LiteWebServerwww.gefionsoftware.com/LiteWebServer//

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

99

Servlet Engine Servlet Engine (container)(container)

IE

NetscapeOpera

Many other Servlets

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

1010

Compiling and Compiling and Invoking ServletsInvoking Servlets Set your CLASSPATHSet your CLASSPATH

– Servlet JAR file (e.g., Servlet JAR file (e.g., install_dirinstall_dir/lib/servlet.jar). /lib/servlet.jar). – Top of your package hierarchyTop of your package hierarchy

Put your servlet classes in proper locationPut your servlet classes in proper location– Locations vary from server to server. E.g.,Locations vary from server to server. E.g.,

tomcat_install_dirtomcat_install_dir/webapps/ROOT//webapps/ROOT/WEB-INF/classesWEB-INF/classes

Invoke your servlets (HTTP request)Invoke your servlets (HTTP request)– http://localhost/servlet/http://localhost/servlet/ServletNameServletName– Custom URL-to-servlet mapping (via web.xml)Custom URL-to-servlet mapping (via web.xml)

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

1111

A Simple Servlet That A Simple Servlet That Generates Plain TextGenerates Plain Text

import java.io.*; import java.io.*; import javax.servlet.*;import javax.servlet.*;import javax.servlet.http.*;import javax.servlet.http.*;

publicpublic class HelloWorld extends HttpServlet { class HelloWorld extends HttpServlet { publicpublic void void doGetdoGet(HttpServletRequest (HttpServletRequest

request,request, HttpServletResponse response)HttpServletResponse response) throws ServletException, IOException {throws ServletException, IOException { PrintWriter out = response.getWriter();PrintWriter out = response.getWriter(); out.println("Hello World");out.println("Hello World"); }}}}

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

1212

Servlets PackagesServlets Packages

Package: javax.servletPackage: javax.servlet– Provides many interfaces and abstract classes Provides many interfaces and abstract classes

for protocol independent generic servletsfor protocol independent generic servlets Package: javax.servlet.httpPackage: javax.servlet.http

– Provides interfaces and abstract classes for Provides interfaces and abstract classes for HTTP servletsHTTP servlets

– Extends from the interfaces and classes used Extends from the interfaces and classes used in the generic servletsin the generic servlets

Located in <tomcat_home>/lib/servlet.jarLocated in <tomcat_home>/lib/servlet.jar Or, you can get the servlet class file from Or, you can get the servlet class file from

http://java.sun.comhttp://java.sun.com for your development. for your development.

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

1313

Basic Servlet StructureBasic Servlet Structure

The skeleton of a common servlet.The skeleton of a common servlet.

publicpublic class class MyServlet MyServlet extends extends HttpServletHttpServlet{{

publicpublic void void init()init(){{ // Initialization here// Initialization here}}publicpublic void void service()service(){{ // Your work happens here// Your work happens here}}publicpublic void void destroy()destroy(){{ // release resources here// release resources here}}

}}

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

1414

Generating HTMLGenerating HTML

Set the Content-Type headerSet the Content-Type header– Use Use response.setContentTyperesponse.setContentType

Output HTML Output HTML – Be sure to include the DOCTYPEBe sure to include the DOCTYPE– PrintWriter.println()PrintWriter.println()

Use an HTML validation serviceUse an HTML validation service– http://validator.w3.org/http://validator.w3.org/– http://www.htmlhelp.com/tools/http://www.htmlhelp.com/tools/

validator/validator/

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

1515

A Servlet That Generates A Servlet That Generates HTMLHTML

publicpublic class HelloWWW extends HttpServlet { class HelloWWW extends HttpServlet { publicpublic void void doGetdoGet(HttpServletRequest request,(HttpServletRequest request, HttpServletResponse response)HttpServletResponse response) throws ServletException, IOException {throws ServletException, IOException { response.setContentType("text/html");response.setContentType("text/html"); PrintWriter out = response.getWriter();PrintWriter out = response.getWriter(); String docType =String docType = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " +"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " + "Transitional//EN\">\n";"Transitional//EN\">\n"; out.println(out.println(docType + "<HTML>\n" +docType + "<HTML>\n" + "<HEAD><TITLE>Hello WWW</TITLE></HEAD>\"<HEAD><TITLE>Hello WWW</TITLE></HEAD>\

n"+n"+ "<BODY>\n" + "<H1>Hello WWW</H1>\n" +"<BODY>\n" + "<H1>Hello WWW</H1>\n" + "</BODY></HTML>""</BODY></HTML>");); }} }}

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

1616

The Servlet Life CycleThe Servlet Life Cycle

initinit– Executed once when the servlet is first loaded, or at Executed once when the servlet is first loaded, or at

server start. Not called for each requestserver start. Not called for each request serviceservice

– Called in a new thread by server for each request. Called in a new thread by server for each request. Dispatches to doGet, doPost, etc. Dispatches to doGet, doPost, etc. Don’t override this method!Don’t override this method!

doGet, doPost, doXxxdoGet, doPost, doXxx– Handles GET, POST, etc. requestsHandles GET, POST, etc. requests– Override these methods to provide desired behaviorOverride these methods to provide desired behavior

destroydestroy– Called when server deletes servlet instance. Called when server deletes servlet instance.

Not called after each requestNot called after each request

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

1717

The Servlet Life CycleThe Servlet Life Cycle

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

1818

Idea of Web Idea of Web ApplicationsApplications

Servlets, JSP pages, HTML files, utility Servlets, JSP pages, HTML files, utility classes, beans, tag libraries, etc. are bundled classes, beans, tag libraries, etc. are bundled together in a single directory hierarchy or filetogether in a single directory hierarchy or file

Access to content in the Web app is always Access to content in the Web app is always through a URL that has a common prefixthrough a URL that has a common prefix– http://host/http://host/webAppPrefixwebAppPrefix/Servlet/MyServlet/Servlet/MyServlet

Many aspects of Web application behavior Many aspects of Web application behavior controlled through controlled through deployment descriptordeployment descriptor (web.xml)(web.xml)– The deployment descriptor is covered in the The deployment descriptor is covered in the

tutorial.tutorial.

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

1919

Purposes of Web Purposes of Web ApplicationsApplications(A single WAR file)(A single WAR file) OrganizationOrganization

– Related files grouped together in a single file Related files grouped together in a single file or directory hierarchy.or directory hierarchy.

HTML files, JSP pages, servlets, beans, images, etc.HTML files, JSP pages, servlets, beans, images, etc.

PortabilityPortability– All compliant servers support Web apps.All compliant servers support Web apps.– Can redeploy on new server by moving a Can redeploy on new server by moving a

singlesingle file. file. SeparationSeparation

– Each Web app has its own:Each Web app has its own: ServletContext, Class loaderServletContext, Class loader Sessions, URL prefix, Directory structureSessions, URL prefix, Directory structure

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

2020

Structure of a Web Structure of a Web ApplicationApplication

JSP and regular Web contentJSP and regular Web content (HTML, style sheets, images, (HTML, style sheets, images, etc.): etc.): – Main directory or a subdirectory thereof.Main directory or a subdirectory thereof.

ServletsServlets::– WEB-INF/classes (if servlet is unpackaged – i.e. in default WEB-INF/classes (if servlet is unpackaged – i.e. in default

package)package)– A subdirectory thereof that matches the package name.A subdirectory thereof that matches the package name.

JAR filesJAR files::– WEB-INF/lib.WEB-INF/lib.

web.xmlweb.xml::– WEB-INFWEB-INF

Tag Library Descriptor filesTag Library Descriptor files::– WEB-INF or subdirectory thereofWEB-INF or subdirectory thereof

Files in WEB-INF Files in WEB-INF notnot directly accessible to outside clients directly accessible to outside clients

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

2121

Example StructureExample Structure

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

2222

Why You Should Why You Should Not Override serviceNot Override service You can add support for other types of requests You can add support for other types of requests

by adding doPut, doTrace, etc.by adding doPut, doTrace, etc. You can add support for modification datesYou can add support for modification dates

– Add a getLastModified methodAdd a getLastModified method The service method gives you automatic The service method gives you automatic

support for: support for: – HEAD, OPTIONS, and TRACE requestsHEAD, OPTIONS, and TRACE requests

Alternative: have doPost call doGetAlternative: have doPost call doGet

public void public void doPostdoPost(HttpServletRequest (HttpServletRequest requestrequest,, HttpServletResponse HttpServletResponse responseresponse) … {) … { doGetdoGet((requestrequest, , responseresponse););

}}

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

2323

Initializing ServletsInitializing Servlets

Common in real-life servletsCommon in real-life servlets– E.g., initializing database connection pools.E.g., initializing database connection pools.

Use ServletConfig.getInitParameter to read Use ServletConfig.getInitParameter to read initialization parametersinitialization parameters– Call getServletConfig to obtain the ServletConfig object Call getServletConfig to obtain the ServletConfig object

Set init parameters in web.xml (ver 2.2/2.3)Set init parameters in web.xml (ver 2.2/2.3)– ……/WEB-INF/web.xml/WEB-INF/web.xml– Many servers have custom interfaces to create Many servers have custom interfaces to create

web.xmlweb.xml It is common to use init even when It is common to use init even when

you don’t read init parametersyou don’t read init parameters– E.g., to set up data structures that don’t change during E.g., to set up data structures that don’t change during

the life of the servlet, to load information from disk, the life of the servlet, to load information from disk, etc.etc.

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

2424

publicpublic class ShowMessage extends HttpServlet { class ShowMessage extends HttpServlet { private String message;private String message; private String defaultMessage = "No message.";private String defaultMessage = "No message."; private int repeats = 1;private int repeats = 1; publicpublic void void init()init() throws ServletException { throws ServletException { ServletConfig config = getServletConfig();ServletConfig config = getServletConfig(); message = config.getInitParameter("message");message = config.getInitParameter("message"); if (message == null) { message = defaultMessage; }if (message == null) { message = defaultMessage; } try {try { String repeatString = config.getInitParameter("repeats");String repeatString = config.getInitParameter("repeats"); repeats = Integer.parseInt(repeatString);repeats = Integer.parseInt(repeatString); } catch(NumberFormatException nfe) {}} catch(NumberFormatException nfe) {} }} publicpublic void void doGet(HttpServletRequest request, HttpServletResponse response)doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {throws ServletException, IOException { response.setContentType("text/html");response.setContentType("text/html"); PrintWriter out = response.getWriter();PrintWriter out = response.getWriter(); String title = "The ShowMessage Servlet";String title = "The ShowMessage Servlet"; out.println(ServletUtilities.headWithTitle(title)+out.println(ServletUtilities.headWithTitle(title)+ "<BODY BGCOLOR=\"#FDF5E6\">\n" + "<H1 ALIGN=CENTER>" + title + "<BODY BGCOLOR=\"#FDF5E6\">\n" + "<H1 ALIGN=CENTER>" + title +

"</H1>");"</H1>"); for(int i=0; i<for(int i=0; i<repeatsrepeats; i++) {; i++) { out.println(out.println(messagemessage + "<BR>"); + "<BR>"); }} out.println("</BODY></HTML>");out.println("</BODY></HTML>"); } }} }

A Servlet That Uses A Servlet That Uses Initialization Initialization ParametersParameters

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

2525

Debugging ServletsDebugging Servlets

You don’t execute them directly, but you You don’t execute them directly, but you trigger errors by means of an HTTP request.trigger errors by means of an HTTP request.

Look at the HTML sourceLook at the HTML source Return error pages to the clientReturn error pages to the client

– Plan ahead for missing/malformed dataPlan ahead for missing/malformed data Use the log fileUse the log file

– log("message") or log("message", Throwable)log("message") or log("message", Throwable) Look at the request data separatelyLook at the request data separately Look at the response data separatelyLook at the response data separately Stop and restart the serverStop and restart the server

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

2626

Handling the Client Handling the Client Request: Request: Form DataForm Data Example URL at online travel agentExample URL at online travel agent

– http://host/path?http://host/path?user=Marty+Hall&origin=iad&dest=nrtuser=Marty+Hall&origin=iad&dest=nrt

– Names (user) come from HTML author; Names (user) come from HTML author; values (Marty+Hall) usually come from end uservalues (Marty+Hall) usually come from end user

Parsing form (query) data in traditional CGIParsing form (query) data in traditional CGI– Read the data one way for GET requests, another way Read the data one way for GET requests, another way

for POST requestsfor POST requests– Chop pairs at &, then separate parameter names (left Chop pairs at &, then separate parameter names (left

of the "=") from parameter values (right of the "=")of the "=") from parameter values (right of the "=")– URL decode valuesURL decode values (e.g., "%7E" becomes "~") (e.g., "%7E" becomes "~")– Need special cases for omitted valuesNeed special cases for omitted values

(param1=val1&(param1=val1&param2=param2=&param3=val3) and &param3=val3) and repeated params repeated params ((param1=val1param1=val1&param2=val2&&param2=val2&param1=val3param1=val3) )

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

2727

Reading Form Data Reading Form Data (Query Data)(Query Data) getParameter("name")getParameter("name")

– Returns value as user entered it. I.e., URL-decoded Returns value as user entered it. I.e., URL-decoded value of first occurrence of name in query string. value of first occurrence of name in query string.

– Works identically for GET and POST requestsWorks identically for GET and POST requests– Returns null if no such parameter is in queryReturns null if no such parameter is in query

getParameterValues("name")getParameterValues("name")– Returns an array of the URL-decoded values of all Returns an array of the URL-decoded values of all

occurrences of name in query stringoccurrences of name in query string– Returns a one-element array if param not repeatedReturns a one-element array if param not repeated– Returns null if no such parameter is in queryReturns null if no such parameter is in query

getParameterNames()getParameterNames()– Returns Enumeration of request paramsReturns Enumeration of request params

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

2828

An HTML Form With An HTML Form With Three ParametersThree Parameters

<FORM ACTION="/servlet/cwp.ThreeParams"><FORM ACTION="/servlet/cwp.ThreeParams"> First Parameter: <INPUT TYPE="TEXT" First Parameter: <INPUT TYPE="TEXT" NAME="param1"NAME="param1"><BR>><BR> Second Parameter: <INPUT TYPE="TEXT" Second Parameter: <INPUT TYPE="TEXT" NAME="param2"NAME="param2"><BR>><BR> Third Parameter: <INPUT TYPE="TEXT" Third Parameter: <INPUT TYPE="TEXT" NAME="param3"NAME="param3"><BR>><BR> <CENTER><INPUT TYPE="SUBMIT"></CENTER><CENTER><INPUT TYPE="SUBMIT"></CENTER></FORM></FORM>

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

2929

publicpublic class ThreeParams extends HttpServlet { class ThreeParams extends HttpServlet {

publicpublic void void doGetdoGet(HttpServletRequest request, HttpServletResponse response)(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {throws ServletException, IOException {

response.setContentType("text/html");response.setContentType("text/html");

PrintWriter out = response.getWriter();PrintWriter out = response.getWriter();

String title = "Reading Three Request Parameters";String title = "Reading Three Request Parameters";

out.println(ServletUtilities.headWithTitle(title) +out.println(ServletUtilities.headWithTitle(title) +

"<BODY BGCOLOR=\"#FDF5E6\">\n" +"<H1 ALIGN=CENTER>" + title "<BODY BGCOLOR=\"#FDF5E6\">\n" +"<H1 ALIGN=CENTER>" + title + + "</H1>\n" + "<UL>\n" +"</H1>\n" + "<UL>\n" +

" <LI><B>param1</B>: " + " <LI><B>param1</B>: " + request.getParameter("param1")request.getParameter("param1") + "\n" + + "\n" +

" <LI><B>param2</B>: " + " <LI><B>param2</B>: " + request.getParameter("param2")request.getParameter("param2") + "\n" + + "\n" +

" <LI><B>param3</B>: " + " <LI><B>param3</B>: " + request.getParameter("param3")request.getParameter("param3") + "\n" + + "\n" +

"</UL>\n" + "</BODY></HTML>"); }}"</UL>\n" + "</BODY></HTML>"); }}

Reading the Reading the Three Three ParametersParameters

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

3030

Result of ShowParameters Result of ShowParameters ServletServletServer receives the data from Server receives the data from useruser

– Note that order of parameters in Enumeration Note that order of parameters in Enumeration does not match order they appeared in Web pagedoes not match order they appeared in Web page

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

3131

Filtering Strings for Filtering Strings for HTML-Specific HTML-Specific CharactersCharacters You cannot safely insert arbitrary strings into You cannot safely insert arbitrary strings into

servlet outputservlet output– < and > can cause problems anywhere< and > can cause problems anywhere– & and " cause problems inside of HTML attributes& and " cause problems inside of HTML attributes

You sometimes cannot manually translateYou sometimes cannot manually translate– String is derived from a program excerpt or another String is derived from a program excerpt or another

source where it is already in standard formatsource where it is already in standard format– String is derived from HTML form dataString is derived from HTML form data

Failing to filter special characters makes you Failing to filter special characters makes you vulnerable to cross-site scripting attackvulnerable to cross-site scripting attack– http://www.cert.org/advisories/CA-2000-02.htmlhttp://www.cert.org/advisories/CA-2000-02.html– http://www.microsoft.com/technet/security/http://www.microsoft.com/technet/security/

crssite.aspcrssite.asp

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

3232

Filtering Code Filtering Code (ServletUtilities.java)(ServletUtilities.java)

publicpublic static String filter(String input) { static String filter(String input) { StringBufferStringBuffer filtered = new StringBuffer(input.length()); filtered = new StringBuffer(input.length()); char c;char c; for(int i=0; i<input.length(); i++) {for(int i=0; i<input.length(); i++) { c = input.charAt(i);c = input.charAt(i); if (c == '<') { filtered.append("&lt;"); }if (c == '<') { filtered.append("&lt;"); }

else if (c == '>') { filtered.append("&gt;"); }else if (c == '>') { filtered.append("&gt;"); } else if (c == '"') { filtered.append("&quot;"); }else if (c == '"') { filtered.append("&quot;"); } else if (c == '&') { filtered.append("&amp;"); }else if (c == '&') { filtered.append("&amp;"); } else { filtered.append(c); }else { filtered.append(c); }

}} return(filtered.toString());return(filtered.toString()); }}

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

3333

Servlet That Fails to Servlet That Fails to Filter and filtered Filter and filtered resultsresults

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

3434

Understand HyperText Understand HyperText Transfer Protocol Transfer Protocol (HTTP)(HTTP)

1) Specify Get / Post

2) Request header

3) Form Data (Parameters)

request

response

1) Status code

2) Response header

3) Content-Type

4) HTML pages / Other files

Web Client Web Server

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

3535

Reminder: What do Reminder: What do Servlets really do?Servlets really do? Handle the incoming requestsHandle the incoming requests

– Handle Get / Post / or othersHandle Get / Post / or others– Read and parse request headersRead and parse request headers– Process form parametersProcess form parameters

Generate the server response Generate the server response pagespages– HTTP Status codes for the clientHTTP Status codes for the client– Generate HTTP response headersGenerate HTTP response headers– Specify the content typeSpecify the content type– Send the web pages and other filesSend the web pages and other files

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

3636

Break Time – 15 Break Time – 15 minutesminutes

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

3737

Handling the Client Handling the Client Request: HTTP Request Request: HTTP Request HeadersHeaders Request headers are distinct from the form Request headers are distinct from the form

data.data. They are indirectly set by the browser.They are indirectly set by the browser. Example HTTP 1.1 RequestExample HTTP 1.1 Request

– GETGET /search?keywords=servlets+jsp /search?keywords=servlets+jsp HTTP/1.1HTTP/1.1– Accept:Accept: image/gif, image/jpg, */* image/gif, image/jpg, */*– Accept-Encoding:Accept-Encoding: gzip gzip– Connection:Connection: Keep-Alive Keep-Alive– Cookie:Cookie: userID=id456578 userID=id456578– Host:Host: www.somebookstore.com www.somebookstore.com– Referer:Referer: http://www.somebookstore.com/findbooks.html http://www.somebookstore.com/findbooks.html– User-Agent:User-Agent: Mozilla/4.7 [en] (Win98; U) Mozilla/4.7 [en] (Win98; U)

The servlet needs to explicitly read these HTTP The servlet needs to explicitly read these HTTP request headers to make use of this information.request headers to make use of this information.

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

3838

Java Web ClientJava Web Client

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

3939

Reading Request Reading Request HeadersHeaders General-purpose wayGeneral-purpose way

– getHeader,getHeader, getHeaders, getHeaderNamesgetHeaders, getHeaderNames Specialized – commonly used headersSpecialized – commonly used headers

– getCookiesgetCookies– getAuthType and getRemoteUsergetAuthType and getRemoteUser– getContentLength, getContentTypegetContentLength, getContentType– getDateHeader, getIntHeadergetDateHeader, getIntHeader

Related info – main request lineRelated info – main request line– getMethod, getRequestURI, getProtocolgetMethod, getRequestURI, getProtocol

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

4040

publicpublic class ShowRequestHeaders extends HttpServlet { class ShowRequestHeaders extends HttpServlet {

publicpublic void void doGetdoGet(HttpServletRequest request, HttpServletResponse response) throws (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {ServletException, IOException {

response.setContentType("text/html");response.setContentType("text/html");

PrintWriter out = response.getWriter();PrintWriter out = response.getWriter();

String title = "Servlet Example: Showing Request Headers";String title = "Servlet Example: Showing Request Headers";

out.println(ServletUtilities.headWithTitle(title) +out.println(ServletUtilities.headWithTitle(title) +

"<BODY BGCOLOR=\"#FDF5E6\">\n" +"<BODY BGCOLOR=\"#FDF5E6\">\n" +

"<H1 ALIGN=CENTER>" + title + "</H1>\n" +"<H1 ALIGN=CENTER>" + title + "</H1>\n" +

"<B>Request Method: </B>" + "<B>Request Method: </B>" + request.getMethod() request.getMethod() + "<BR>\n" ++ "<BR>\n" +

"<B>Request URI: </B>" + "<B>Request URI: </B>" + request.getRequestURI()request.getRequestURI() + "<BR>\n" + + "<BR>\n" + "<B>Request Protocol: </B>" + "<B>Request Protocol: </B>" + request.getProtocol()request.getProtocol() + "<BR><BR>\n" + "<BR><BR>\n" + +

"<TABLE BORDER=1 ALIGN=CENTER>\n" + "<TR "<TABLE BORDER=1 ALIGN=CENTER>\n" + "<TR BGCOLOR=\"#FFAD00\">\n" +BGCOLOR=\"#FFAD00\">\n" +

"<TH>Header Name<TH>Header Value");"<TH>Header Name<TH>Header Value");

Enumeration headerNames = Enumeration headerNames = request.getHeaderNames()request.getHeaderNames();;

while(headerNames.hasMoreElements()) {while(headerNames.hasMoreElements()) {

String headerName = (String)headerNames.nextElement();String headerName = (String)headerNames.nextElement();

out.println("<TR><TD>" + headerName);out.println("<TR><TD>" + headerName);

out.println(" <TD>" + out.println(" <TD>" + request.getHeader(headerName)request.getHeader(headerName)); }); }

out.println("</TABLE>\n</BODY></HTML>"); }out.println("</TABLE>\n</BODY></HTML>"); }

publicpublic void void doPostdoPost(HttpServletRequest request, HttpServletResponse response)(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {throws ServletException, IOException {

doGetdoGet(request, response);(request, response);

} }} }

Printing Printing All All HeadersHeaders

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

4141

Printing All Headers:Printing All Headers:Netscape & IE ResultsNetscape & IE Results

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

4242

Common HTTP 1.1 Common HTTP 1.1 Request HeadersRequest Headers AcceptAccept

– Indicates MIME types browser can handleIndicates MIME types browser can handle– Can send different content to different clientsCan send different content to different clients

Accept-Encoding Accept-Encoding – Indicates encodings (e.g., gzip) browser can Indicates encodings (e.g., gzip) browser can

handlehandle– See following exampleSee following example

AuthorizationAuthorization– User identification for password-protected pages.User identification for password-protected pages.– Instead of HTTP authorization, use HTML forms to Instead of HTTP authorization, use HTML forms to

send username/password. Store in session send username/password. Store in session object.object.

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

4343

Common HTTP 1.1 Common HTTP 1.1 Request Headers Request Headers (Continued)(Continued)

Connection Connection – In HTTP 1.0, keep-alive means browser can handle In HTTP 1.0, keep-alive means browser can handle

persistent connection. In HTTP 1.1, persistent persistent connection. In HTTP 1.1, persistent connection is default. connection is default. Persistent connections mean Persistent connections mean that the server can reuse the same socket over that the server can reuse the same socket over again for requests very close together from the again for requests very close together from the same client.same client.

– Servlets can't do this unilaterally; the best they can Servlets can't do this unilaterally; the best they can do is to give the server enough info to permit do is to give the server enough info to permit persistent connections. So, they should set Content-persistent connections. So, they should set Content-Length with setContentLength.Length with setContentLength.

CookieCookie– Gives cookies previously sent to client. (getCookies)Gives cookies previously sent to client. (getCookies)

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

4444

Common HTTP 1.1 Common HTTP 1.1 Request Headers Request Headers (Continued)(Continued) HostHost

– Indicates host given in original URL Indicates host given in original URL – This is a required header in HTTP 1.1. This This is a required header in HTTP 1.1. This

fact is important to know if you write a fact is important to know if you write a custom HTTP client (e.g., WebClient used in custom HTTP client (e.g., WebClient used in book) or telnet to a server and use the book) or telnet to a server and use the HTTP/1.1 versionHTTP/1.1 version

If-Modified-SinceIf-Modified-Since– Indicates client wants page only if it has Indicates client wants page only if it has

been changed after specified datebeen changed after specified date– Don’t handle this situation directly.Don’t handle this situation directly.

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

4545

Common HTTP 1.1 Common HTTP 1.1 Request Headers Request Headers (Continued)(Continued) ReferrerReferrer

– URL of referring Web pageURL of referring Web page– Useful for tracking traffic; Useful for tracking traffic;

logged by many serverslogged by many servers– Can be easily spoofedCan be easily spoofed

User-AgentUser-Agent– String identifying the browser making the String identifying the browser making the

requestrequest– Use sparinglyUse sparingly– Again, can be easily spoofedAgain, can be easily spoofed

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

4646

public void doGet(HttpServletRequest request, HttpServletResponse response)public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {throws ServletException, IOException { response.setContentType("text/html");response.setContentType("text/html"); String encodings = request.getHeader("Accept-Encoding");String encodings = request.getHeader("Accept-Encoding"); String encodeFlag = request.getParameter("encoding");String encodeFlag = request.getParameter("encoding"); PrintWriter out; String title;PrintWriter out; String title; if ((if ((encodingsencodings != null) && ( != null) && (encodings.indexOf("gzip")encodings.indexOf("gzip") != -1) != -1)

&& !"none".equals(encodeFlag)) {&& !"none".equals(encodeFlag)) { title = "Page Encoded with GZip";title = "Page Encoded with GZip"; OutputStream out1 = response.getOutputStream();OutputStream out1 = response.getOutputStream(); out =out = new PrintWriter(new GZIPOutputStream(out1), false); new PrintWriter(new GZIPOutputStream(out1), false); response.setHeader("Content-Encoding", "gzip");response.setHeader("Content-Encoding", "gzip"); } else {} else { title = "Unencoded Page";title = "Unencoded Page"; out =out = response.getWriter(); response.getWriter(); }} out.println(ServletUtilities.headWithTitle(title) + "<BODY BGCOLOR=\"#FDF5E6\">\n" out.println(ServletUtilities.headWithTitle(title) + "<BODY BGCOLOR=\"#FDF5E6\">\n"

++ "<H1 ALIGN=CENTER>" + title + "</H1>\n");"<H1 ALIGN=CENTER>" + title + "</H1>\n"); String line = "Blah, blah, blah, blah, blah. " + "Yadda, yadda, yadda, yadda.";String line = "Blah, blah, blah, blah, blah. " + "Yadda, yadda, yadda, yadda."; for(int i=0; i<10000; i++) {for(int i=0; i<10000; i++) { out.println(line);out.println(line); }} out.println("</BODY></HTML>");out.println("</BODY></HTML>"); out.close();out.close(); }}

Sending Compressed Sending Compressed PagesPages

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

4747

Sending Compressed Sending Compressed Pages:Pages:ResultsResults UncompressedUncompressed (28.8K modem), (28.8K modem),

Netscape 4.7 and Internet Explorer 5.0: > 50 Netscape 4.7 and Internet Explorer 5.0: > 50 secondsseconds

Compressed Compressed (28.8K modem), (28.8K modem), Netscape 4.7 and Internet Explorer 5.0: < 5 Netscape 4.7 and Internet Explorer 5.0: < 5 secondsseconds

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

4848

Generating the Server Generating the Server Response: 1) HTTP Status Response: 1) HTTP Status CodesCodes Example HTTP 1.1 ResponseExample HTTP 1.1 Response

HTTP/1.1 200 OKHTTP/1.1 200 OKContent-Type: text/html (or text/plain or …)Content-Type: text/html (or text/plain or …)

<!DOCTYPE ...><!DOCTYPE ...><HTML><HTML>......</HTML></HTML>

Changing the status code lets you perform Changing the status code lets you perform a number of tasks not otherwise possiblea number of tasks not otherwise possible– Forward client to another pageForward client to another page– Indicate a missing resourceIndicate a missing resource– Instruct browser to use cached copyInstruct browser to use cached copy

Set status Set status before before sending documentsending document

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

4949

Setting Status CodesSetting Status Codes

publicpublic voidvoid setStatussetStatus(int statusCode)(int statusCode) – Use a constant for the code, not an explicit int.Use a constant for the code, not an explicit int.

Constants are in HttpServletResponseConstants are in HttpServletResponse– Names derived from standard message.Names derived from standard message.

E.g., SC_OK, SC_NOT_FOUND, etc.E.g., SC_OK, SC_NOT_FOUND, etc.– SC stands for “Status Code”.SC stands for “Status Code”.

publicpublic voidvoid sendErrorsendError(int code, String (int code, String message) message) – Wraps message inside small HTML documentWraps message inside small HTML document– Usually 404 with a short message.Usually 404 with a short message.

publicpublic voidvoid sendRedirectsendRedirect(String url) (String url) – Generates a 302 response with a location headerGenerates a 302 response with a location header– Relative URLs permitted in Servlets 2.2/2.3Relative URLs permitted in Servlets 2.2/2.3– Also sets Location headerAlso sets Location header

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

5050

SC general categoriesSC general categories

100-199100-199– Indicate the client should respond with some other Indicate the client should respond with some other

actions.actions. 200-299200-299

– Indicate the request was successful.Indicate the request was successful. 300-399300-399

– Usually include a location headerUsually include a location header 400-499400-499

– Indicate an error by the client.Indicate an error by the client. 500-599500-599

– Indicate an error by the server.Indicate an error by the server.

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

5151

Common HTTP 1.1 Common HTTP 1.1 Status CodesStatus Codes 200 (OK)200 (OK)

– Everything is fine; document followsEverything is fine; document follows– Default for servletsDefault for servlets

204 (No Content)204 (No Content)– Browser should keep displaying previous Browser should keep displaying previous

document, no new document is available.document, no new document is available. 301 (Moved Permanently)301 (Moved Permanently)

– Requested document permanently moved Requested document permanently moved elsewhere (indicated in Location header)elsewhere (indicated in Location header)

– Browsers go to new location automaticallyBrowsers go to new location automatically

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

5252

Common HTTP 1.1 Common HTTP 1.1 Status Codes Status Codes (Continued)(Continued) 302 (Found)302 (Found)

– Requested document temporarily moved elsewhere Requested document temporarily moved elsewhere (indicated in Location header)(indicated in Location header)

– Browsers go to new location automaticallyBrowsers go to new location automatically– Servlets should use sendRedirect, not setStatus, when Servlets should use sendRedirect, not setStatus, when

setting this header. See examplesetting this header. See example 401 (Unauthorized)401 (Unauthorized)

– Browser tried to access password protected page Browser tried to access password protected page without proper Authorization header.without proper Authorization header.

404 (Not Found)404 (Not Found)– SC_NOT_FOUNDSC_NOT_FOUND– No such page. No such page. – Servlets should use sendError to set this headerServlets should use sendError to set this header

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

5353

publicpublic void void doGetdoGet(HttpServletRequest request, HttpServletResponse response)(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {throws ServletException, IOException { String searchString = request.getParameter("searchString");String searchString = request.getParameter("searchString"); if ((searchString == null) || (searchString.length() == 0)) {if ((searchString == null) || (searchString.length() == 0)) { reportProblem(response, "Missing search string.");reportProblem(response, "Missing search string."); return;return; }} searchString = URLEncoder.encode(searchString);searchString = URLEncoder.encode(searchString); String numResults = request.getParameter("numResults");String numResults = request.getParameter("numResults"); ...... String searchEngine = request.getParameter("searchEngine");String searchEngine = request.getParameter("searchEngine"); SearchSpec[] commonSpecs = SearchSpec.getCommonSpecs();SearchSpec[] commonSpecs = SearchSpec.getCommonSpecs(); for(int i=0; i<commonSpecs.length; i++) {for(int i=0; i<commonSpecs.length; i++) { SearchSpec searchSpec = commonSpecs[i];SearchSpec searchSpec = commonSpecs[i]; if (searchSpec.getName().equals(searchEngine)) {if (searchSpec.getName().equals(searchEngine)) { String url = searchSpec.makeURL(searchString, numResults);String url = searchSpec.makeURL(searchString, numResults); response.sendRedirect(url);response.sendRedirect(url); return; return; }} }} reportProblem(response, "Unrecognized search engine.");reportProblem(response, "Unrecognized search engine.");

private void reportProblem(HttpServletResponse response, String message)private void reportProblem(HttpServletResponse response, String message) throws IOException {throws IOException { response.sendError(response.SC_NOT_FOUND, "<H2>" + message + "</H2>");response.sendError(response.SC_NOT_FOUND, "<H2>" + message + "</H2>"); }}

A Front End A Front End to Various to Various Search Search EnginesEngines

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

5454

Front End to Search Front End to Search Engines: Result of Legal Engines: Result of Legal RequestRequest

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

5555

Generating the Server Generating the Server Response: 2) HTTP Response Response: 2) HTTP Response HeadersHeaders PurposesPurposes

– Give forwarding locationGive forwarding location– Specify cookies Specify cookies – Supply the page modification date Supply the page modification date – Instruct the browser to reload the page after Instruct the browser to reload the page after

a designated interval a designated interval – Give the document size so that persistent Give the document size so that persistent

HTTP connections can be usedHTTP connections can be used– Designate the type of document being Designate the type of document being

generatedgenerated– Etc.Etc.

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

5656

Setting Arbitrary Setting Arbitrary Response HeadersResponse Headers publicpublic voidvoid setHeadersetHeader(String headerName, (String headerName,

String headerValue) String headerValue) – Sets an arbitrary headerSets an arbitrary header

publicpublic voidvoid setDateHeadersetDateHeader(String name, (String name, long millisecs) long millisecs) – Converts millis since 1970 to date in GMT formatConverts millis since 1970 to date in GMT format

publicpublic voidvoid setIntHeadersetIntHeader(String name, (String name, int headerValue) int headerValue) – Prevents need to convert int to StringPrevents need to convert int to String

addHeaderaddHeader, , addDateHeaderaddDateHeader, , addIntHeaderaddIntHeader – Adds header instead of replacing Adds header instead of replacing

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

5757

Setting Common Setting Common Response HeadersResponse Headers Methods for specifying common headersMethods for specifying common headers setContentType setContentType

– Sets the Content-Type header (MIME Types). Sets the Content-Type header (MIME Types). Servlets almost always use this header. Servlets almost always use this header.

setContentLength setContentLength – Sets the Content-Length header.Sets the Content-Length header.

Used for persistent HTTP connections. Used for persistent HTTP connections. addCookieaddCookie

– Adds a value to the Set-Cookie header. Adds a value to the Set-Cookie header. sendRedirect sendRedirect

– Sets Location header (plus changes status code) Sets Location header (plus changes status code)

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

5858

Common HTTP 1.1 Common HTTP 1.1 Response HeadersResponse Headers Cache-Control (1.1) and Pragma (1.0) Cache-Control (1.1) and Pragma (1.0)

– A no-cache value prevents browsers from A no-cache value prevents browsers from caching page. Send both headers or check caching page. Send both headers or check HTTP versionHTTP version

Content-Encoding Content-Encoding – The way document is encoded. Browser The way document is encoded. Browser

reverses this encoding before handling reverses this encoding before handling document (compression example).document (compression example).

Content-LengthContent-Length– The number of bytes in the responseThe number of bytes in the response– Use ByteArrayOutputStream to buffer Use ByteArrayOutputStream to buffer

document so you can determine size.document so you can determine size.

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

5959

Common HTTP 1.1 Common HTTP 1.1 Response Headers Response Headers (Continued)(Continued) Content-TypeContent-Type

– The MIME type of the document being returned.The MIME type of the document being returned.– Use setContentType to set this headerUse setContentType to set this header

ExpiresExpires– The time at which document should be The time at which document should be

considered out-of-date and thus should no considered out-of-date and thus should no longer be cachedlonger be cached

– Use setDateHeader to set this headerUse setDateHeader to set this header Last-ModifiedLast-Modified

– The time document was last changed. The time document was last changed. – Don’t set this header explicitly; provide a Don’t set this header explicitly; provide a

getLastModified method instead.getLastModified method instead.

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

6060

Common HTTP 1.1 Common HTTP 1.1 Response Headers Response Headers (Continued)(Continued)

LocationLocation– The URL to which browser should reconnect.The URL to which browser should reconnect.– Use sendRedirect instead of setting this directly. Use sendRedirect instead of setting this directly.

RefreshRefresh– The number of seconds until browser should The number of seconds until browser should

reload page. Can also include URL to connect to.reload page. Can also include URL to connect to. Set-CookieSet-Cookie

– The cookies that browser should remember. The cookies that browser should remember. Don’t set this header directly; use addCookie Don’t set this header directly; use addCookie instead.instead.

Via, WWW-Authenticate, …Via, WWW-Authenticate, …

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

6161

Persistent Servlet State Persistent Servlet State and and Auto-Reloading PagesAuto-Reloading Pages Idea:Idea: generate list of large (e.g., 150-digit) generate list of large (e.g., 150-digit)

prime numbersprime numbers– Show partial results until completedShow partial results until completed– Let new clients make use of results from othersLet new clients make use of results from others

Demonstrates use of the Refresh headerDemonstrates use of the Refresh header Shows how easy it is for servlets to maintain Shows how easy it is for servlets to maintain

state between requestsstate between requests– Very difficult in traditional CGI Very difficult in traditional CGI

Also illustrates that servlets can handle Also illustrates that servlets can handle multiple simultaneous connectionsmultiple simultaneous connections– Each request is in a separate threadEach request is in a separate thread– Synchronization required for shared dataSynchronization required for shared data

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

6262

publicpublic void void doGetdoGet(HttpServletRequest request, HttpServletResponse response)(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {throws ServletException, IOException { int numPrimes = ServletUtilities.getIntParameter(request, "numPrimes", 50);int numPrimes = ServletUtilities.getIntParameter(request, "numPrimes", 50); int numDigits = ServletUtilities.getIntParameter(request, "numDigits", 120);int numDigits = ServletUtilities.getIntParameter(request, "numDigits", 120); // findPrimeList is synchronized// findPrimeList is synchronized PrimeList primeList = findPrimeList(primeListVector, numPrimes, numDigits);PrimeList primeList = findPrimeList(primeListVector, numPrimes, numDigits); if (primeList == null) {if (primeList == null) { primeList = new PrimeList(numPrimes, numDigits, true);primeList = new PrimeList(numPrimes, numDigits, true); synchronized(primeListVector) {synchronized(primeListVector) { if (primeListVector.size() >= maxPrimeLists)if (primeListVector.size() >= maxPrimeLists) primeListVector.removeElementAt(0);primeListVector.removeElementAt(0); primeListVector.addElement(primeList);primeListVector.addElement(primeList); }} }} Vector currentPrimes = primeList.getPrimes();Vector currentPrimes = primeList.getPrimes(); int numCurrentPrimes = currentPrimes.size();int numCurrentPrimes = currentPrimes.size(); int numPrimesRemaining = (numPrimes - numCurrentPrimes);int numPrimesRemaining = (numPrimes - numCurrentPrimes); boolean isLastResult = (numPrimesRemaining == 0);boolean isLastResult = (numPrimesRemaining == 0); if (!isLastResult) {if (!isLastResult) { response.setHeader("Refresh", "5");response.setHeader("Refresh", "5"); }} response.setContentType("text/html");response.setContentType("text/html"); PrintWriter out = response.getWriter();PrintWriter out = response.getWriter(); // Show List of Primes found ...// Show List of Primes found ...

Generating Generating Prime Prime NumbersNumbers

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

6363

Prime Number Servlet:Prime Number Servlet:Initial & Final ResultInitial & Final Result

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

6464

Break Time – 15 Break Time – 15 minutesminutes

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

6565

The Potential of The Potential of CookiesCookies IdeaIdea

– Servlet sends a simple name and value to clientServlet sends a simple name and value to client– Client returns same name and value when it Client returns same name and value when it

connects to same site (or same domain, connects to same site (or same domain, depending on cookie settings)depending on cookie settings)

Typical Uses of CookiesTypical Uses of Cookies– Identifying a user during an e-commerce Identifying a user during an e-commerce

sessionsession Servlets have a higher-level API for this taskServlets have a higher-level API for this task

– Avoiding username and passwordAvoiding username and password– Customizing a siteCustomizing a site– Focusing advertisingFocusing advertising

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

6666

Cookies and Focused Cookies and Focused AdvertisingAdvertising

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

6767

Some Problems with Some Problems with CookiesCookies The problem is The problem is privacyprivacy, not , not securitysecurity

– Servers can remember your previous actions Servers can remember your previous actions – If you give out personal information, servers can If you give out personal information, servers can

link that information to your previous actionslink that information to your previous actions– Servers can share cookie information through use Servers can share cookie information through use

of a cooperating third party like doubleclick.netof a cooperating third party like doubleclick.net– Poorly designed sites store sensitive information Poorly designed sites store sensitive information

like credit card numbers directly in cookielike credit card numbers directly in cookie Morals for servlet authorsMorals for servlet authors

– If cookies are not critical to your task, avoid If cookies are not critical to your task, avoid servlets that totally fail when cookies are disabled.servlets that totally fail when cookies are disabled.

– Don't put sensitive info in cookiesDon't put sensitive info in cookies

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

6868

Sending Cookies to Sending Cookies to BrowserBrowser Standard approach:Standard approach:

Cookie c = new Cookie("name", "value");Cookie c = new Cookie("name", "value");c.setMaxAge(...); // Means cookie persists on diskc.setMaxAge(...); // Means cookie persists on disk// Set other attributes.// Set other attributes.response.addCookie(c);response.addCookie(c);

Simplified approach:Simplified approach:– Use LongLivedCookie class:Use LongLivedCookie class:public class LongLivedCookie extends Cookie {public class LongLivedCookie extends Cookie { public static final int SECONDS_PER_YEAR =public static final int SECONDS_PER_YEAR = 60*60*24*365;60*60*24*365; public LongLivedCookie(String name, String value) {public LongLivedCookie(String name, String value) { super(name, value);super(name, value); setMaxAge(SECONDS_PER_YEAR);setMaxAge(SECONDS_PER_YEAR); }}}}

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

6969

Reading Cookies from Reading Cookies from BrowserBrowser Standard approach:Standard approach:

Cookie[] cookies = request.getCookies();Cookie[] cookies = request.getCookies();if (cookies != null) {if (cookies != null) { for(int i=0; i<cookies.length; i++) {for(int i=0; i<cookies.length; i++) { Cookie c = cookies[i];Cookie c = cookies[i]; if (c.getName().equals("someName")) {if (c.getName().equals("someName")) { doSomethingWith(c);doSomethingWith(c); break;break; }} }}}}

Simplified approach:Simplified approach:– Extract cookie or cookie value from cookie array Extract cookie or cookie value from cookie array

by using ServletUtilities.getCookieValue or by using ServletUtilities.getCookieValue or ServletUtilities.getCookieServletUtilities.getCookie

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

7070

ServletUtilities.getCookieVServletUtilities.getCookieValuealue publicpublic static String getCookieValue(Cookie[] cookies, static String getCookieValue(Cookie[] cookies,

String cookieName, String defaultVal) {String cookieName, String defaultVal) {

if (cookies != null) {if (cookies != null) {

for(int i=0; i<cookies.length; i++) {for(int i=0; i<cookies.length; i++) {

Cookie cookie = cookies[i];Cookie cookie = cookies[i];

if (cookieName.equals(cookie.getName()))if (cookieName.equals(cookie.getName()))

return(cookie.getValue());return(cookie.getValue());

}}

}}

return(defaultVal);return(defaultVal);

}}

The getCookie method is similarThe getCookie method is similar– Returns the Cookie object instead of the valueReturns the Cookie object instead of the value

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

7171

Simple Simple Cookie-Cookie-Setting Setting ServletServlet

public class SetCookies extends HttpServlet {public class SetCookies extends HttpServlet { public void doGet(HttpServletRequest request, public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, HttpServletResponse response) throws ServletException,

IOException {IOException { for(int i=0; i<3; i++) {for(int i=0; i<3; i++) { CookieCookie cookiecookie = = newnew Cookie Cookie("Session-Cookie-" + i, "Cookie-Value-("Session-Cookie-" + i, "Cookie-Value-

S" + i);S" + i); responseresponse.addCookie(.addCookie(cookiecookie);); cookiecookie = new = new CookieCookie("Persistent-Cookie-" + i, "Cookie-Value-P" + i);("Persistent-Cookie-" + i, "Cookie-Value-P" + i); cookiecookie.setMaxAge(3600);.setMaxAge(3600); responseresponse.addCookie(.addCookie(cookiecookie);); } } response.setContentType("text/html");response.setContentType("text/html"); PrintWriter out = response.getWriter();PrintWriter out = response.getWriter(); out.println(...);out.println(...);

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

7272

publicpublic class ShowCookies extends HttpServlet { class ShowCookies extends HttpServlet { publicpublic void void doGetdoGet(HttpServletRequest request, HttpServletResponse (HttpServletRequest request, HttpServletResponse

response)response) throws ServletException, IOException {throws ServletException, IOException { response.setContentType("text/html");response.setContentType("text/html"); PrintWriter out = response.getWriter();PrintWriter out = response.getWriter(); String title = "Active Cookies";String title = "Active Cookies"; out.println(ServletUtilities.headWithTitle(title) +out.println(ServletUtilities.headWithTitle(title) + "<BODY BGCOLOR=\"#FDF5E6\">\n" + "<H1 ALIGN=\"CENTER\">" + "<BODY BGCOLOR=\"#FDF5E6\">\n" + "<H1 ALIGN=\"CENTER\">" +

title + "</H1>\n" + "<TABLE BORDER=1 ALIGN=\"CENTER\">\n" + title + "</H1>\n" + "<TABLE BORDER=1 ALIGN=\"CENTER\">\n" + "<TR BGCOLOR=\"#FFAD00\">\n" +"<TR BGCOLOR=\"#FFAD00\">\n" + " <TH>Cookie Name\n" + " <TH>Cookie Value");" <TH>Cookie Name\n" + " <TH>Cookie Value"); CookieCookie[] [] cookiescookies = request.getCookies(); = request.getCookies(); if (if (cookiescookies != null) { != null) { Cookie cookieCookie cookie;; for(int i=0; i<for(int i=0; i<cookiescookies.length; i++) {.length; i++) { cookiecookie = = cookiescookies[i];[i]; out.println("<TR>\n" +out.println("<TR>\n" + " <TD>" + " <TD>" + cookiecookie.getName().getName() + "\n" + " <TD>" + + "\n" + " <TD>" +

cookiecookie.getValue().getValue());); } }} } out.println("</TABLE></BODY></HTML>");out.println("</TABLE></BODY></HTML>"); } }} }

Cookie-Cookie-ViewinViewing g ServletServlet

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

7373

Result of Cookie-Viewer Result of Cookie-Viewer (Before & After Restarting (Before & After Restarting Browser)Browser)

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

7474

Methods in the Cookie Methods in the Cookie APIAPI getDomain/setDomaingetDomain/setDomain

– Lets you specify domain to which cookie applies. Lets you specify domain to which cookie applies. Current host must be part of domain specifiedCurrent host must be part of domain specified

getMaxAge/setMaxAgegetMaxAge/setMaxAge– Gets/sets the cookie expiration time (in seconds). If Gets/sets the cookie expiration time (in seconds). If

you fail to set this, cookie applies to current you fail to set this, cookie applies to current browsing session only. See LongLivedCookie helper browsing session only. See LongLivedCookie helper class given earlierclass given earlier

getName/setNamegetName/setName– Gets/sets the cookie name. For new cookies, you Gets/sets the cookie name. For new cookies, you

supply name to constructor, not to setName. For supply name to constructor, not to setName. For incoming cookie array, you use getName to find incoming cookie array, you use getName to find the cookie of interestthe cookie of interest

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

7575

Methods in the Cookie Methods in the Cookie API (Continued)API (Continued) getPath/setPathgetPath/setPath

– Gets/sets the path to which cookie applies. If Gets/sets the path to which cookie applies. If unspecified, cookie applies to URLs that are within unspecified, cookie applies to URLs that are within or below directory containing current pageor below directory containing current page

getSecure/setSecuregetSecure/setSecure– Gets/sets flag indicating whether cookie should Gets/sets flag indicating whether cookie should

apply only to SSL connections or to all connectionsapply only to SSL connections or to all connections getValue/setValuegetValue/setValue

– Gets/sets value associated with cookie. For new Gets/sets value associated with cookie. For new cookies, you supply value to constructor, not to cookies, you supply value to constructor, not to setValue. For incoming cookie array, you use setValue. For incoming cookie array, you use getName to find the cookie of interest, then call getName to find the cookie of interest, then call getValue on the resultgetValue on the result

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

7676

Customized Search Customized Search EngineEngine

The specified option will be used as the initial choicesnext time when you browsethe same page.

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

7777

Session TrackingSession Tracking

Why?Why?– When clients at an on-line store add an item to their When clients at an on-line store add an item to their

shopping cart, how does the server know what’s already in shopping cart, how does the server know what’s already in the cart?the cart?

– When clients decide to proceed to checkout, how can the When clients decide to proceed to checkout, how can the server determine which previously created shopping cart is server determine which previously created shopping cart is theirs?theirs?

– HTTP is a “Stateless” protocol.HTTP is a “Stateless” protocol. How?How?

– CookiesCookies– URL-rewritingURL-rewriting– Hidden form fieldsHidden form fields

Servlets provide a technical solution: Servlets provide a technical solution: HttpSession APIHttpSession API– Higher-level API neededHigher-level API needed

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

7878

The Session Tracking The Session Tracking APIAPI Session objects live on the serverSession objects live on the server Automatically associated with client via Automatically associated with client via

cookies or URL-rewritingcookies or URL-rewriting– Use Use request.getSession(true)request.getSession(true) to get either existing to get either existing

or new sessionor new session Behind the scenes, the system looks at cookie or URL Behind the scenes, the system looks at cookie or URL

extra info and sees if it matches the key to some extra info and sees if it matches the key to some previously stored session object. If so, it returns that previously stored session object. If so, it returns that object. If not, it creates a new one, assigns a cookie or object. If not, it creates a new one, assigns a cookie or URL info as its key, and returns that new session URL info as its key, and returns that new session object.object.

Hashtable-like mechanism lets you store Hashtable-like mechanism lets you store arbitrary objects inside sessionarbitrary objects inside session– setAttributesetAttribute stores values stores values– getAttributegetAttribute retrieves values retrieves values

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

7979

Using SessionsUsing Sessions

HttpSessionHttpSession session = request.getSession(true); session = request.getSession(true);

ShoppingCart cart =ShoppingCart cart =

    (ShoppingCart)session.getAttribute("shoppingCa(ShoppingCart)session.getAttribute("shoppingCart");rt");

if (cart == null) { if (cart == null) {

// No cart already in session// No cart already in session

    cart = new ShoppingCart();cart = new ShoppingCart();

    session.setAttribute("shoppingCart", cart);session.setAttribute("shoppingCart", cart);

}}

doSomethingWith(cart);doSomethingWith(cart);

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

8080

HttpSession MethodsHttpSession Methods

getAttribute, getValue [2.1]getAttribute, getValue [2.1]– Extracts a previously stored value from a session Extracts a previously stored value from a session

object. Returns null if no value is associated with object. Returns null if no value is associated with given namegiven name

setAttribute, putValue [2.1] setAttribute, putValue [2.1] – Associates a value with a name. Monitor changes: Associates a value with a name. Monitor changes:

values implement HttpSessionBindingListener.values implement HttpSessionBindingListener. removeAttribute, removeValue [2.1] removeAttribute, removeValue [2.1]

– Removes values associated with name Removes values associated with name getAttributeNames, getValueNames [2.1] getAttributeNames, getValueNames [2.1]

– Returns names of all attributes in the sessionReturns names of all attributes in the session getId getId

– Returns the unique identifier for each session.Returns the unique identifier for each session.

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

8181

HttpSession Methods HttpSession Methods (Continued)(Continued) isNew isNew

– Determines if session is new to client (not to page)Determines if session is new to client (not to page) getCreationTimegetCreationTime

– Returns time at which session was first created Returns time at which session was first created getLastAccessedTime getLastAccessedTime

– Returns time session was last sent from client Returns time session was last sent from client getMaxInactiveInterval,getMaxInactiveInterval,

setMaxInactiveInterval setMaxInactiveInterval – Gets or sets the amount of time session should go Gets or sets the amount of time session should go

without access before being invalidated without access before being invalidated invalidate invalidate

– Invalidates the session and unbinds all Invalidates the session and unbinds all objects associated with itobjects associated with it

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

8282

A Servlet Showing Per-A Servlet Showing Per-Client Access CountsClient Access Counts

publicpublic void void doGetdoGet(HttpServletRequest request,(HttpServletRequest request,

HttpServletResponse response) throws ServletException, IOException {HttpServletResponse response) throws ServletException, IOException {

response.setContentType("text/html");response.setContentType("text/html");

PrintWriter out = response.getWriter();PrintWriter out = response.getWriter();

String title = "Session Tracking Example";String title = "Session Tracking Example";

HttpSessionHttpSession sessionsession = request. = request.getSessiongetSession(true);(true);

String heading;String heading;

Integer accessCount = (Integer)session.Integer accessCount = (Integer)session.getAttributegetAttribute("accessCount");("accessCount");

if (accessCount == null) {if (accessCount == null) {

accessCount = new Integer(0);accessCount = new Integer(0);

heading = "Welcome, Newcomer";heading = "Welcome, Newcomer";

} else {} else {

heading = "Welcome Back";heading = "Welcome Back";

accessCount = new Integer(accessCount.intValue() + 1);accessCount = new Integer(accessCount.intValue() + 1);

}}

sessionsession..setAttributesetAttribute("accessCount", accessCount);("accessCount", accessCount);

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

8383

First and Eleventh First and Eleventh Visit to ShowSession Visit to ShowSession ServletServlet

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

8484

Review: Getting Review: Getting StartedStarted Servlets are efficient, portable, powerful, and Servlets are efficient, portable, powerful, and

widely accepted in industrywidely accepted in industry Regardless of deployment server, run a free Regardless of deployment server, run a free

server on your desktop for developmentserver on your desktop for development Getting started:Getting started:

– Set your CLASSPATHSet your CLASSPATH Servlet and JSP JAR filesServlet and JSP JAR files Top of your package hierarchyTop of your package hierarchy

– Put class files in proper locationPut class files in proper location .../WEB-INF/classes with servlets 2.2/2.3.../WEB-INF/classes with servlets 2.2/2.3

– Use proper URL; default is Use proper URL; default is http://http://hosthost/servlet//servlet/ServletNameServletName

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

8585

Review: Getting Review: Getting StartedStarted(Continued)(Continued) Main servlet code goes in doGet or Main servlet code goes in doGet or

doPost:doPost:– The HttpServletRequest contains the The HttpServletRequest contains the

incoming informationincoming information– The HttpServletResponse lets you set The HttpServletResponse lets you set

outgoing informationoutgoing information Call setContentType to specify MIME typeCall setContentType to specify MIME type Call getWriter to obtain a Writer pointing to clientCall getWriter to obtain a Writer pointing to client

One-time setup code goes in initOne-time setup code goes in init– Servlet gets initialized and loaded onceServlet gets initialized and loaded once– Servlet gets invoked multiple timesServlet gets invoked multiple times

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

8686

Review: Handling Form Review: Handling Form Data Data (Query Data)(Query Data)

Query data comes from HTML forms Query data comes from HTML forms as URL-encoded name/value pairsas URL-encoded name/value pairs

Servlets read data by calling Servlets read data by calling request.getParameter("name")request.getParameter("name")– Results in value as entered into form, Results in value as entered into form,

not as sent over network. not as sent over network. – Always check for missing or Always check for missing or

malformed datamalformed data– Special case: query data that contains Special case: query data that contains

special HTML characters (filtering).special HTML characters (filtering).

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

8787

Review: Review: Using HTTP Request Using HTTP Request HeadersHeaders Many servlet tasks can only be Many servlet tasks can only be

accomplished by making use of HTTP accomplished by making use of HTTP headers coming from the browserheaders coming from the browser

Use request.getHeader for arbitrary headerUse request.getHeader for arbitrary header Cookies, authorization info, content length, Cookies, authorization info, content length,

and content type have shortcut methodsand content type have shortcut methods Most important headers you read directlyMost important headers you read directly

– Accept, Accept, – Accept-EncodingAccept-Encoding– Connection, Referer, User-AgentConnection, Referer, User-Agent

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

8888

Review: Review: Generating the HTTP Generating the HTTP ResponseResponse Many servlet tasks can only be Many servlet tasks can only be

accomplished through use of HTTP status accomplished through use of HTTP status codes and headers sent to the browsercodes and headers sent to the browser

Two parts of the responseTwo parts of the response– Status line Status line

In general, set via response.setStatusIn general, set via response.setStatus In special cases, set via In special cases, set via

response.sendRedirect and response.sendError response.sendRedirect and response.sendError

– Response headersResponse headers In general, set via response.setHeaderIn general, set via response.setHeader In special cases, set via response.setContentType, In special cases, set via response.setContentType,

response.setContentLength, response.addCookie, …response.setContentLength, response.addCookie, …

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

8989

Review: Generating the Review: Generating the HTTP Response HTTP Response (Continued)(Continued) Most important status codesMost important status codes

– 200 (default)200 (default)– 302 (forwarding; set via sendRedirect)302 (forwarding; set via sendRedirect)– 401 (password needed)401 (password needed)– 404 (not found; set via sendError)404 (not found; set via sendError)

Most important headers you set directlyMost important headers you set directly– Cache-Control and PragmaCache-Control and Pragma– Content-EncodingContent-Encoding– Content-LengthContent-Length– Expires, RefreshExpires, Refresh– WWW-AuthenticateWWW-Authenticate

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

9090

Review: Handling Review: Handling CookiesCookies

Cookies involve name/value pairs sent from Cookies involve name/value pairs sent from server to browser and returned when the same server to browser and returned when the same page, site, or domain is visited later, you canpage, site, or domain is visited later, you can– Track sessions (use higher-level API)Track sessions (use higher-level API)– Permit users to avoid logging in at low-security sitesPermit users to avoid logging in at low-security sites– Customize sites for different usersCustomize sites for different users– Focus content or advertisingFocus content or advertising

Setting cookiesSetting cookies– Cookie constructor, set age, response.addCookieCookie constructor, set age, response.addCookie

Reading cookiesReading cookies– Call request.getCookiesCall request.getCookies

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

9191

Review: Session Review: Session TrackingTracking Although it usually uses cookies behind the Although it usually uses cookies behind the

scenes, the session tracking API is higher-scenes, the session tracking API is higher-level and easier to use than the cookie APIlevel and easier to use than the cookie API

Session information lives on serverSession information lives on server– Cookie or extra URL info associates it with a userCookie or extra URL info associates it with a user

Obtaining sessionObtaining session– request.getSession(true)request.getSession(true)

Associating values with keysAssociating values with keys– session.setAttributesession.setAttribute

Finding values associated with keysFinding values associated with keys– session.getAttributesession.getAttribute

Always check if this value is null before trying to use Always check if this value is null before trying to use itit

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

9292

Preview: The Need for Preview: The Need for JSPJSP With servlets, it is easy toWith servlets, it is easy to

– Read form dataRead form data– Read HTTP request headersRead HTTP request headers– Set HTTP status codes and response headersSet HTTP status codes and response headers– Use cookies and session trackingUse cookies and session tracking– Share data among servletsShare data among servlets– Remember data between requestsRemember data between requests– Get fun, high-paying jobsGet fun, high-paying jobs

But, it sure is a pain toBut, it sure is a pain to– Use those println statements to generate HTMLUse those println statements to generate HTML– Maintain that HTMLMaintain that HTML

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

9393

Preview: Benefits of Preview: Benefits of JSPJSP Although JSP technically can't do anything Although JSP technically can't do anything

servlets can't do, JSP makes it easier to:servlets can't do, JSP makes it easier to:– Write HTML, read and maintain the HTMLWrite HTML, read and maintain the HTML

JSP makes it possible to:JSP makes it possible to:– Use standard HTML tools such as HomeSite or Use standard HTML tools such as HomeSite or

UltraDevUltraDev– Have different members of your team do the Have different members of your team do the

HTML layout and the programmingHTML layout and the programming JSP encourages you toJSP encourages you to

– Separate the (JavaSeparate the (JavaTMTM technology) code that technology) code that creates the content from the (HTML) code that creates the content from the (HTML) code that presents itpresents it

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

9494

ReferencesReferences

CWP2: Chapter 19CWP2: Chapter 19 http://java.sun.com/docs/books/tutorial/http://java.sun.com/docs/books/tutorial/

servlets/servlets/ Core Servlets and JavaServer PagesCore Servlets and JavaServer Pages More Servlets and JavaServer PagesMore Servlets and JavaServer Pages http://java.sun.com/products/servlet/http://java.sun.com/products/servlet/

The End.The End. Thank you for patience!Thank you for patience!