SlideShare a Scribd company logo
Java/J2EE Programming Training
Generating the Server Response: HTTP
Status Codes
Page 2Classification: Restricted
Agenda
• Format of the HTTP response
• How to set status codes
• What the status codes are good for
• Shortcut methods for redirection and error pages
• A servlet that redirects users to browser-specific pages
• A front end to various search engines
Page 3Classification: Restricted
• Request
• GET /servlet/SomeName
HTTP/1.1
• Host: ...
• Header2: ...
• ...
• HeaderN:
• (Blank Line)
• Response
• HTTP/1.1 200 OK
• Content-Type: text/html
• Header2: ...
• ...
• HeaderN: ...
• (Blank Line)
• <!DOCTYPE ...>
• <HTML>
• <HEAD>...</HEAD>
• <BODY>
• ...
• </BODY></HTML>
HTTP Request/Response
Page 4Classification: Restricted
• response.setStatus(int statusCode)
– Use a constant for the code, not an explicit int.
Constants are in HttpServletResponse
– Names derived from standard message.
E.g., SC_OK, SC_NOT_FOUND, etc.
• response.sendError(int code,
String message)
– Wraps message inside small HTML document
• response.sendRedirect(String url)
– Sets status code to 302
– Sets Location response header also
Setting Status Codes
Page 5Classification: Restricted
• 200 (OK)
– Everything is fine; document follows.
– Default for servlets.
• 204 (No Content)
– Browser should keep displaying previous document.
• 301 (Moved Permanently)
– Requested document permanently moved elsewhere (indicated in
Location header).
– Browsers go to new location automatically.
Common HTTP 1.1 Status Codes
Page 6Classification: Restricted
• 302 (Found)
– Requested document temporarily moved elsewhere (indicated in Location
header).
– Browsers go to new location automatically.
– Servlets should use sendRedirect, not setStatus, when setting this header.
See example.
• 401 (Unauthorized)
– Browser tried to access password-protected page without proper
Authorization header.
• 404 (Not Found)
– No such page. Servlets should use sendError to set this.
– Problem: Internet Explorer and small (< 512KB) error pages. IE ignores
error page by default.
– Fun and games: http://www.plinko.net/404/
Common HTTP 1.1 Status Codes (Continued)
Page 7Classification: Restricted
• public class WrongDestination extends HttpServlet {
• public void doGet(HttpServletRequest request,
• HttpServletResponse response)
• throws ServletException, IOException {
• String userAgent = request.getHeader("User-Agent");
• if ((userAgent != null) &&
• (userAgent.indexOf("MSIE") != -1)) {
• response.sendRedirect("http://home.netscape.com");
• } else {
• response.sendRedirect("http://www.microsoft.com");
• }
• }
• }
A Servlet That Redirects Users to Browser-Specific Pages
Page 8Classification: Restricted
A Servlet That Redirects Users to Browser-Specific Pages
Generating the Server Response:
HTTP Response Headers
Page 10Classification: Restricted
Agenda
• Format of the HTTP response
• Setting response headers
• Understanding what response headers are good for
• Building Excel spread sheets
• Sending incremental updates
to the browser
Page 11Classification: Restricted
• Request
• GET /servlet/SomeName
HTTP/1.1
• Host: ...
• Header2: ...
• ...
• HeaderN:
• (Blank Line)
• Response
• HTTP/1.1 200 OK
• Content-Type: text/html
• Header2: ...
• ...
• HeaderN: ...
• (Blank Line)
• <!DOCTYPE ...>
• <HTML>
• <HEAD>...</HEAD>
• <BODY>
• ...
• </BODY></HTML>
HTTP Request/Response
Page 12Classification: Restricted
• public void setHeader(String headerName,
String headerValue)
– Sets an arbitrary header
• public void setDateHeader(String name,
long millisecs)
– Converts milliseconds since 1970 to a date string
in GMT format
• public void setIntHeader(String name,
int headerValue)
– Prevents need to convert int to String before calling setHeader
• addHeader, addDateHeader, addIntHeader
– Adds new occurrence of header instead of replacing
Setting Arbitrary Response Headers
Page 13Classification: Restricted
• setContentType
– Sets the Content-Type header.
– Servlets almost always use this.
– See table of common MIME types.
• setContentLength
– Sets the Content-Length header.
– Used for persistent HTTP connections.
– See Connection request header.
• addCookie
– Adds a value to the Set-Cookie header.
– See separate section on cookies.
• sendRedirect
– Sets the Location header (plus changes status code).
Setting Arbitrary Response Headers
Page 14Classification: Restricted
Type Meaning
application/msword Microsoft Word document
application/octet-stream Unrecognized or binary data
application/pdf Acrobat (.pdf) file
application/postscript PostScript file
application/vnd.ms-excel Excel spreadsheet
application/vnd.ms-powerpoint Powerpoint presentation
application/x-gzip Gzip archive
application/x-java-archive JAR file
application/x-java-vm Java bytecode (.class) file
application/zip Zip archive
audio/basic Sound file in .au or .snd format
audio/x-aiff AIFF sound file
audio/x-wav Microsoft Windows sound file
audio/midi MIDI sound file
text/css HTML cascading style sheet
text/html HTML document
text/plain Plain text
text/xml XML document
image/gif GIF image
image/jpeg JPEG image
image/png PNG image
image/tiff TIFF image
video/mpeg MPEG video clip
video/quicktime QuickTime video clip
Common MIME Types
Page 15Classification: Restricted
• Cache-Control (1.1) and Pragma (1.0)
– A no-cache value prevents browsers from caching page.
• Content-Disposition
– Lets you request that the browser ask the user to save the response to
disk in a file of the given name
• Content-Disposition: attachment; filename=file-name
• Content-Encoding
– The way document is encoded. See earlier compression example
• Content-Length
– The number of bytes in the response.
– See setContentLength on previous slide.
– Use ByteArrayOutputStream to buffer document before sending it, so
that you can determine size. See discussion of the Connection request
header
Common HTTP 1.1 Response Headers
Page 16Classification: Restricted
• Content-Type
– The MIME type of the document being returned.
– Use setContentType to set this header.
• Expires
– The time at which document should be considered out-of-date and thus
should no longer be cached.
– Use setDateHeader to set this header.
• Last-Modified
– The time document was last changed.
– Don’t set this header explicitly; provide a getLastModified method
instead. See lottery number example in book (Chapter 3).
Common HTTP 1.1 Response Headers (Continued)
Page 17Classification: Restricted
• Location
– The URL to which browser should reconnect.
– Use sendRedirect instead of setting this directly.
• Refresh
– The number of seconds until browser should reload page. Can also
include URL to connect to.
See following example.
• Set-Cookie
– The cookies that browser should remember. Don’t set this header
directly; use addCookie instead. See next section.
• WWW-Authenticate
– The authorization type and realm needed in Authorization header. See
security chapters in More Servlets & JSP.
Common HTTP 1.1 Response Headers (Continued)
Handling Cookies
Page 19Classification: Restricted
Agenda
• Understanding the benefits and drawbacks of cookies
• Sending outgoing cookies
• Receiving incoming cookies
• Tracking repeat visitors
• Specifying cookie attributes
• Differentiating between session cookies and persistent cookies
• Simplifying cookie usage with utility classes
• Modifying cookie values
• Remembering user preferences
Page 20Classification: Restricted
• Idea
– Servlet sends a simple name and value to client.
– Client returns same name and value when it connects to same site (or
same domain, depending on cookie settings).
• Typical Uses of Cookies
– Identifying a user during an e-commerce session
• Servlets have a higher-level API for this task
– Avoiding username and password
– Customizing a site
– Focusing advertising
The Potential of Cookies
Page 21Classification: Restricted
Cookies and Focused Advertising
Page 22Classification: Restricted
• The problem is privacy, not security.
– Servers can remember your previous actions
– If you give out personal information, servers can link that information to
your previous actions
– Servers can share cookie information through use of a cooperating third
party like doubleclick.net
– Poorly designed sites store sensitive information like credit card numbers
directly in cookie
– JavaScript bugs let hostile sites steal cookies (old browsers)
• Moral for servlet authors
– If cookies are not critical to your task, avoid servlets that totally fail when
cookies are disabled
– Don't put sensitive info in cookies
Some Problems with Cookies
Page 23Classification: Restricted
Manually Deleting Cookies (To Simplify Testing)
Page 24Classification: Restricted
• Create a Cookie object.
– Call the Cookie constructor with a cookie name and a cookie value, both
of which are strings.
• Cookie c = new Cookie("userID", "a1234");
• Set the maximum age.
– To tell browser to store cookie on disk instead of just in memory, use
setMaxAge (argument is in seconds)
• c.setMaxAge(60*60*24*7); // One week
• Place the Cookie into the HTTP response
– Use response.addCookie.
– If you forget this step, no cookie is sent to the browser!
• response.addCookie(c);
Sending Cookies to the Client
Page 25Classification: Restricted
• Call request.getCookies
– This yields an array of Cookie objects.
• Loop down the array, calling getName on each entry until you find the
cookie of interest
– Use the value (getValue) in application-specific way.
– String cookieName = "userID";
– Cookie[] cookies = request.getCookies();
– if (cookies != null) {
– for(int i=0; i<cookies.length; i++) {
– Cookie cookie = cookies[i];
– if (cookieName.equals(cookie.getName())) {
– doSomethingWith(cookie.getValue());
– }
– }
– }
Reading Cookies from the Client
Page 26Classification: Restricted
• public class RepeatVisitor extends HttpServlet {
• public void doGet(HttpServletRequest request,
• HttpServletResponse response)
• throws ServletException, IOException {
• boolean newbie = true;
• Cookie[] cookies = request.getCookies();
• if (cookies != null) {
• for(int i=0; i<cookies.length; i++) {
• Cookie c = cookies[i];
• if ((c.getName().equals("repeatVisitor"))&&
• (c.getValue().equals("yes"))) {
• newbie = false;
• break;
• }
• }
• }
Using Cookies to Detect First-Time Visitors
Page 27Classification: Restricted
• String title;
• if (newbie) {
• Cookie returnVisitorCookie =
• new Cookie("repeatVisitor", "yes");
• returnVisitorCookie.setMaxAge(60*60*24*365);
• response.addCookie(returnVisitorCookie);
• title = "Welcome Aboard";
• } else {
• title = "Welcome Back";
• }
• response.setContentType("text/html");
• PrintWriter out = response.getWriter();
• … // (Output page with above title)
Using Cookies to Detect First-Time Visitors (Continued)
Page 28Classification: Restricted
Using Cookies to Detect First-Time Visitors (Results)
Page 29Classification: Restricted
• getDomain/setDomain
– Lets you specify domain to which cookie applies. Current host must be
part of domain specified.
• getMaxAge/setMaxAge
– Gets/sets the cookie expiration time (in seconds). If you fail to set this,
cookie applies to current browsing session only. See LongLivedCookie
helper class given earlier.
• getName
– Gets the cookie name. There is no setName method; you supply name to
constructor. For incoming cookie array, you use getName to find the
cookie of interest.
Using Cookie Attributes
Page 30Classification: Restricted
• getPath/setPath
– Gets/sets the path to which cookie applies. If unspecified, cookie applies
to URLs that are within or below directory containing current page.
• getSecure/setSecure
– Gets/sets flag indicating whether cookie should apply only to SSL
connections or to all connections.
• getValue/setValue
– Gets/sets value associated with cookie. For new cookies, you supply value
to constructor, not to setValue. For incoming cookie array, you use
getName to find the cookie of interest, then call getValue on the result. If
you set the value of an incoming cookie, you still have to send it back out
with response.addCookie.
Using Cookie Attributes
Page 31Classification: Restricted
• public class CookieTest extends HttpServlet {
• public void doGet(HttpServletRequest request,
• HttpServletResponse response)
• throws ServletException, IOException {
• for(int i=0; i<3; i++) {
• Cookie cookie =
• new Cookie("Session-Cookie-" + i,
• "Cookie-Value-S" + i);
• // No maxAge (ie maxAge = -1)
• response.addCookie(cookie);
• cookie = new Cookie("Persistent-Cookie-" + i,
• "Cookie-Value-P" + i);
• cookie.setMaxAge(3600);
• response.addCookie(cookie);
• }
Differentiating Session Cookies from Persistent Cookies
Page 32Classification: Restricted
Differentiating Session Cookies from Persistent Cookies (Cont)
• … // Start an HTML table
• Cookie[] cookies = request.getCookies();
• if (cookies == null) {
• out.println("<TR><TH COLSPAN=2>No cookies");
• } else {
• Cookie cookie;
• for(int i=0; i<cookies.length; i++) {
• cookie = cookies[i];
• out.println
• ("<TR>n" +
• " <TD>" + cookie.getName() + "n" +
• " <TD>" + cookie.getValue());
• }
• }
Page 33Classification: Restricted
• Result of initial visit to CookieTest servlet
– Same result as when visiting the servlet, quitting the browser, waiting an
hour, and revisiting the servlet.
Differentiating Session Cookies from Persistent Cookies
Page 34Classification: Restricted
• Result of revisiting CookieTest within an hour of original visit (same browser
session)
– I.e., browser stayed open between the original visit and the visit shown
here
Differentiating Session Cookies from Persistent Cookies
Session Tracking
Page 36Classification: Restricted
• Implementing session tracking from scratch
• Using basic session tracking
• Understanding the session-tracking API
• Differentiating between server and browser sessions
• Encoding URLs
• Storing immutable objects vs. storing mutable objects
• Tracking user access counts
• Accumulating user purchases
• Implementing a shopping cart
• Building an online store
Agenda
Page 37Classification: Restricted
• Idea: associate cookie with data on server
– String sessionID = makeUniqueString();
– HashMap sessionInfo = new HashMap();
– HashMap globalTable = findTableStoringSessions();
– globalTable.put(sessionID, sessionInfo);
– Cookie sessionCookie =
– new Cookie("JSESSIONID", sessionID);
– sessionCookie.setPath("/");
– response.addCookie(sessionCookie);
• Still to be done:
– Extracting cookie that stores session identifier
– Setting appropriate expiration time for cookie
– Associating the hash tables with each request
– Generating the unique session identifiers
Rolling Your Own Session Tracking: Cookies
Page 38Classification: Restricted
• Idea
– Client appends some extra data on the end of each URL that identifies the
session
– Server associates that identifier with data it has stored about that session
– E.g., http://host/path/file.html;jsessionid=1234
• Advantage
– Works even if cookies are disabled or unsupported
• Disadvantages
– Must encode all URLs that refer to your own site
– All pages must be dynamically generated
– Fails for bookmarks and links from other sites
Rolling Your Own Session Tracking: URL-Rewriting
Page 39Classification: Restricted
• Idea:
– <INPUT TYPE="HIDDEN" NAME="session" VALUE="...">
• Advantage
– Works even if cookies are disabled or unsupported
• Disadvantages
– Lots of tedious processing
– All pages must be the result of form submissions
Rolling Your Own Session Tracking: Hidden Form Fields
Page 40Classification: Restricted
• Session objects live on the server
• Sessions automatically associated with client via cookies or URL-rewriting
– Use request.getSession to get session
• Behind the scenes, the system looks at cookie or URL extra info and
sees if it matches the key to some previously stored session object. If
so, it returns that object. If not, it creates a new one, assigns a cookie
or URL info as its key, and returns that new session object.
• Hashtable-like mechanism lets you store arbitrary objects inside session
– setAttribute stores values
– getAttribute retrieves values
Session Tracking in Java
Page 41Classification: Restricted
• Access the session object
– Call request.getSession to get HttpSession object
• This is a hashtable associated with the user
• Look up information associated with a session.
– Call getAttribute on the HttpSession object, cast the return value to the
appropriate type, and check whether the result is null.
• Store information in a session.
– Use setAttribute with a key and a value.
• Discard session data.
– Call removeAttribute discards a specific value.
– Call invalidate to discard an entire session.
– Call logout to log the client out of the Web/app server
Session Tracking Basics
Page 42Classification: Restricted
• HttpSession session = request.getSession();
• SomeClass value =
• (SomeClass)session.getAttribute("someID");
• if (value == null) {
• value = new SomeClass(...);
• session.setAttribute("someID", value);
• }
• doSomethingWith(value);
– Do not need to call setAttribute again (after modifying value) if the
modified value is the same object. But, if value is immutable, modified
value will be a new object reference, and you must call setAttribute again.
Session Tracking Basics: Sample Code
Page 43Classification: Restricted
• Session tracking code:
– No change
• Code that generates hypertext links back to same site:
– Pass URL through response.encodeURL.
• If server is using cookies, this returns URL unchanged
• If server is using URL rewriting, this appends the session info to the
URL
• E.g.:
String url = "order-page.html";
url = response.encodeURL(url);
• Code that does sendRedirect to own site:
– Pass URL through response.encodeRedirectURL
What Changes if Server Uses URL Rewriting?
Page 44Classification: Restricted
• getAttribute
– Extracts a previously stored value from a session object. Returns null if no
value is associated with given name.
• setAttribute
– Associates a value with a name. Monitor changes: values implement
HttpSessionBindingListener.
• removeAttribute
– Removes values associated with name.
• getAttributeNames
– Returns names of all attributes in the session.
• getId
– Returns the unique identifier.
HttpSession Methods
Page 45Classification: Restricted
• isNew
– Determines if session is new to client (not to page)
• getCreationTime
– Returns time at which session was first created
• getLastAccessedTime
– Returns time at which session was last sent from client
• getMaxInactiveInterval, setMaxInactiveInterval
– Gets or sets the amount of time session should go without access before
being invalidated
• invalidate
– Invalidates current session
• logout
– Invalidates all sessions associated with user
HttpSession Methods (Continued)
Page 46Classification: Restricted
• public class ShowSession extends HttpServlet {
• public void doGet(HttpServletRequest request,
• HttpServletResponse response)
• throws ServletException, IOException {
• response.setContentType("text/html");
• HttpSession session = request.getSession();
• String heading;
• Integer accessCount =
• (Integer)session.getAttribute("accessCount");
• if (accessCount == null) {
• accessCount = new Integer(0);
• heading = "Welcome, Newcomer";
• } else { heading = "Welcome Back";
• accessCount =
• new Integer(accessCount.intValue() + 1);
• }
• session.setAttribute("accessCount", accessCount);
A Servlet that Shows Per-Client Access Counts
Page 47Classification: Restricted
• PrintWriter out = response.getWriter();
• …
• out.println
• (docType +
• "<HTML>n" +
• "<HEAD><TITLE>" + title + "</TITLE></HEAD>n" +
• "<BODY BGCOLOR="#FDF5E6">n" +
• "<CENTER>n" +
• "<H1>" + heading + "</H1>n" +
• "<H2>Information on Your Session:</H2>n" +
• "<TABLE BORDER=1>n" +
• "<TR BGCOLOR="#FFAD00">n" +
• " <TH>Info Type<TH>Valuen" +
• …
• " <TD>Number of Previous Accessesn" +
• " <TD>" + accessCount + "n" +
• "</TABLE>n" +
• "</CENTER></BODY></HTML>");
A Servlet that Shows Per-Client Access Counts (Continued)
Page 48Classification: Restricted
A Servlet that Shows Per-Client Access Counts: Result 2
Page 49Classification: Restricted
Thank You

More Related Content

What's hot

AD102 - Break out of the Box
AD102 - Break out of the BoxAD102 - Break out of the Box
AD102 - Break out of the Box
Karl-Henry Martinsson
 
Building high performing web pages
Building high performing web pagesBuilding high performing web pages
Building high performing web pages
Nilesh Bafna
 
Progressive downloads and rendering (Stoyan Stefanov)
Progressive downloads and rendering (Stoyan Stefanov)Progressive downloads and rendering (Stoyan Stefanov)
Progressive downloads and rendering (Stoyan Stefanov)Ontico
 
Ajax Performance Tuning and Best Practices
Ajax Performance Tuning and Best PracticesAjax Performance Tuning and Best Practices
Ajax Performance Tuning and Best Practices
Doris Chen
 
Indic threads delhi13-rest-anirudh
Indic threads delhi13-rest-anirudhIndic threads delhi13-rest-anirudh
Indic threads delhi13-rest-anirudhAnirudh Bhatnagar
 
Changhao jiang facebook
Changhao jiang facebookChanghao jiang facebook
Changhao jiang facebook
zipeng zhang
 
Course Tech 2013, Sasha Vodnik, A Crash Course in HTML5
Course Tech 2013, Sasha Vodnik, A Crash Course in HTML5Course Tech 2013, Sasha Vodnik, A Crash Course in HTML5
Course Tech 2013, Sasha Vodnik, A Crash Course in HTML5
Cengage Learning
 
Optimising Web Application Frontend
Optimising Web Application FrontendOptimising Web Application Frontend
Optimising Web Application Frontendtkramar
 
How to optimize your Magento store
How to optimize your Magento store How to optimize your Magento store
How to optimize your Magento store
Rasbor.com
 
Top5 scalabilityissues
Top5 scalabilityissuesTop5 scalabilityissues
Top5 scalabilityissues
ColdFusionConference
 
Jatkoaika.com - building sports website using Drupal
Jatkoaika.com - building sports website using DrupalJatkoaika.com - building sports website using Drupal
Jatkoaika.com - building sports website using Drupal
Exove
 
Persistent Offline Storage White
Persistent Offline Storage WhitePersistent Offline Storage White
Persistent Offline Storage WhiteAlexei White
 
Advanced java+JDBC+Servlet
Advanced java+JDBC+ServletAdvanced java+JDBC+Servlet
Advanced java+JDBC+Servlet
Anuj Singh Rajput
 
Session 34 - JDBC Best Practices, Introduction to Design Patterns
Session 34 - JDBC Best Practices, Introduction to Design PatternsSession 34 - JDBC Best Practices, Introduction to Design Patterns
Session 34 - JDBC Best Practices, Introduction to Design Patterns
PawanMM
 
07 response-headers
07 response-headers07 response-headers
07 response-headers
hanichandra
 
NOMAD ENTERPRISE & WAN CACHING APPLIANCES NETWORK OPTIMIZATION IN A CONFIGURA...
NOMAD ENTERPRISE & WAN CACHING APPLIANCES NETWORK OPTIMIZATION IN A CONFIGURA...NOMAD ENTERPRISE & WAN CACHING APPLIANCES NETWORK OPTIMIZATION IN A CONFIGURA...
NOMAD ENTERPRISE & WAN CACHING APPLIANCES NETWORK OPTIMIZATION IN A CONFIGURA...
1E: Software Lifecycle Automation
 
WebPagetest - Good, Bad & Ugly
WebPagetest - Good, Bad & UglyWebPagetest - Good, Bad & Ugly
WebPagetest - Good, Bad & Ugly
Aaron Peters
 

What's hot (20)

AD102 - Break out of the Box
AD102 - Break out of the BoxAD102 - Break out of the Box
AD102 - Break out of the Box
 
Building high performing web pages
Building high performing web pagesBuilding high performing web pages
Building high performing web pages
 
Optimize
OptimizeOptimize
Optimize
 
Progressive downloads and rendering (Stoyan Stefanov)
Progressive downloads and rendering (Stoyan Stefanov)Progressive downloads and rendering (Stoyan Stefanov)
Progressive downloads and rendering (Stoyan Stefanov)
 
Ajax Performance Tuning and Best Practices
Ajax Performance Tuning and Best PracticesAjax Performance Tuning and Best Practices
Ajax Performance Tuning and Best Practices
 
Indic threads delhi13-rest-anirudh
Indic threads delhi13-rest-anirudhIndic threads delhi13-rest-anirudh
Indic threads delhi13-rest-anirudh
 
Varnish Cache
Varnish CacheVarnish Cache
Varnish Cache
 
Changhao jiang facebook
Changhao jiang facebookChanghao jiang facebook
Changhao jiang facebook
 
Course Tech 2013, Sasha Vodnik, A Crash Course in HTML5
Course Tech 2013, Sasha Vodnik, A Crash Course in HTML5Course Tech 2013, Sasha Vodnik, A Crash Course in HTML5
Course Tech 2013, Sasha Vodnik, A Crash Course in HTML5
 
Optimising Web Application Frontend
Optimising Web Application FrontendOptimising Web Application Frontend
Optimising Web Application Frontend
 
How to optimize your Magento store
How to optimize your Magento store How to optimize your Magento store
How to optimize your Magento store
 
Top5 scalabilityissues
Top5 scalabilityissuesTop5 scalabilityissues
Top5 scalabilityissues
 
Jatkoaika.com - building sports website using Drupal
Jatkoaika.com - building sports website using DrupalJatkoaika.com - building sports website using Drupal
Jatkoaika.com - building sports website using Drupal
 
Persistent Offline Storage White
Persistent Offline Storage WhitePersistent Offline Storage White
Persistent Offline Storage White
 
Advanced java+JDBC+Servlet
Advanced java+JDBC+ServletAdvanced java+JDBC+Servlet
Advanced java+JDBC+Servlet
 
Session 34 - JDBC Best Practices, Introduction to Design Patterns
Session 34 - JDBC Best Practices, Introduction to Design PatternsSession 34 - JDBC Best Practices, Introduction to Design Patterns
Session 34 - JDBC Best Practices, Introduction to Design Patterns
 
07 response-headers
07 response-headers07 response-headers
07 response-headers
 
NOMAD ENTERPRISE & WAN CACHING APPLIANCES NETWORK OPTIMIZATION IN A CONFIGURA...
NOMAD ENTERPRISE & WAN CACHING APPLIANCES NETWORK OPTIMIZATION IN A CONFIGURA...NOMAD ENTERPRISE & WAN CACHING APPLIANCES NETWORK OPTIMIZATION IN A CONFIGURA...
NOMAD ENTERPRISE & WAN CACHING APPLIANCES NETWORK OPTIMIZATION IN A CONFIGURA...
 
WebPagetest - Good, Bad & Ugly
WebPagetest - Good, Bad & UglyWebPagetest - Good, Bad & Ugly
WebPagetest - Good, Bad & Ugly
 
Css
CssCss
Css
 

Similar to Generating the Server Response: HTTP Status Codes

ASP.NET Lecture 2
ASP.NET Lecture 2ASP.NET Lecture 2
ASP.NET Lecture 2
Julie Iskander
 
AWS re:Invent 2016: Amazon CloudFront Flash Talks: Best Practices on Configur...
AWS re:Invent 2016: Amazon CloudFront Flash Talks: Best Practices on Configur...AWS re:Invent 2016: Amazon CloudFront Flash Talks: Best Practices on Configur...
AWS re:Invent 2016: Amazon CloudFront Flash Talks: Best Practices on Configur...
Amazon Web Services
 
High Performance Ajax Applications
High Performance Ajax ApplicationsHigh Performance Ajax Applications
High Performance Ajax Applications
Siarhei Barysiuk
 
session and cookies.ppt
session and cookies.pptsession and cookies.ppt
session and cookies.ppt
Jayaprasanna4
 
Presentation Tier optimizations
Presentation Tier optimizationsPresentation Tier optimizations
Presentation Tier optimizations
Anup Hariharan Nair
 
Frontend performance
Frontend performanceFrontend performance
Frontend performance
sacred 8
 
BITM3730Week12.pptx
BITM3730Week12.pptxBITM3730Week12.pptx
BITM3730Week12.pptx
MattMarino13
 
Week 05 Web, App and Javascript_Brandon, S.H. Wu
Week 05 Web, App and Javascript_Brandon, S.H. WuWeek 05 Web, App and Javascript_Brandon, S.H. Wu
Week 05 Web, App and Javascript_Brandon, S.H. Wu
AppUniverz Org
 
[DSBW Spring 2009] Unit 02: Web Technologies (2/2)
[DSBW Spring 2009] Unit 02: Web Technologies (2/2)[DSBW Spring 2009] Unit 02: Web Technologies (2/2)
[DSBW Spring 2009] Unit 02: Web Technologies (2/2)Carles Farré
 
High performance website
High performance websiteHigh performance website
High performance websiteChamnap Chhorn
 
Building production websites with Node.js on the Microsoft stack
Building production websites with Node.js on the Microsoft stackBuilding production websites with Node.js on the Microsoft stack
Building production websites with Node.js on the Microsoft stack
CellarTracker
 
Bt0083 server side programing
Bt0083 server side programing Bt0083 server side programing
Bt0083 server side programing
Techglyphs
 
SharePoint 2013 Performance Analysis - Robi Vončina
SharePoint 2013 Performance Analysis - Robi VončinaSharePoint 2013 Performance Analysis - Robi Vončina
SharePoint 2013 Performance Analysis - Robi Vončina
SPC Adriatics
 
Session 33 - Session Management using other Techniques
Session 33 - Session Management using other TechniquesSession 33 - Session Management using other Techniques
Session 33 - Session Management using other Techniques
PawanMM
 
Web Performance Optimization (WPO)
Web Performance Optimization (WPO)Web Performance Optimization (WPO)
Web Performance Optimization (WPO)
Betclic Everest Group Tech Team
 
19_JavaScript - Storage_Cookies-tutorial .pptx
19_JavaScript - Storage_Cookies-tutorial .pptx19_JavaScript - Storage_Cookies-tutorial .pptx
19_JavaScript - Storage_Cookies-tutorial .pptx
ssuser4a97d3
 
19_JavaScript - Storage_Cookies_students.pptx
19_JavaScript - Storage_Cookies_students.pptx19_JavaScript - Storage_Cookies_students.pptx
19_JavaScript - Storage_Cookies_students.pptx
VatsalJain39
 
Code for Startup MVP (Ruby on Rails) Session 1
Code for Startup MVP (Ruby on Rails) Session 1Code for Startup MVP (Ruby on Rails) Session 1
Code for Startup MVP (Ruby on Rails) Session 1
Henry S
 
01 - Web Programming Intro.pptx
01 - Web Programming Intro.pptx01 - Web Programming Intro.pptx
01 - Web Programming Intro.pptx
Karina González
 

Similar to Generating the Server Response: HTTP Status Codes (20)

Chapter 8 part1
Chapter 8   part1Chapter 8   part1
Chapter 8 part1
 
ASP.NET Lecture 2
ASP.NET Lecture 2ASP.NET Lecture 2
ASP.NET Lecture 2
 
AWS re:Invent 2016: Amazon CloudFront Flash Talks: Best Practices on Configur...
AWS re:Invent 2016: Amazon CloudFront Flash Talks: Best Practices on Configur...AWS re:Invent 2016: Amazon CloudFront Flash Talks: Best Practices on Configur...
AWS re:Invent 2016: Amazon CloudFront Flash Talks: Best Practices on Configur...
 
High Performance Ajax Applications
High Performance Ajax ApplicationsHigh Performance Ajax Applications
High Performance Ajax Applications
 
session and cookies.ppt
session and cookies.pptsession and cookies.ppt
session and cookies.ppt
 
Presentation Tier optimizations
Presentation Tier optimizationsPresentation Tier optimizations
Presentation Tier optimizations
 
Frontend performance
Frontend performanceFrontend performance
Frontend performance
 
BITM3730Week12.pptx
BITM3730Week12.pptxBITM3730Week12.pptx
BITM3730Week12.pptx
 
Week 05 Web, App and Javascript_Brandon, S.H. Wu
Week 05 Web, App and Javascript_Brandon, S.H. WuWeek 05 Web, App and Javascript_Brandon, S.H. Wu
Week 05 Web, App and Javascript_Brandon, S.H. Wu
 
[DSBW Spring 2009] Unit 02: Web Technologies (2/2)
[DSBW Spring 2009] Unit 02: Web Technologies (2/2)[DSBW Spring 2009] Unit 02: Web Technologies (2/2)
[DSBW Spring 2009] Unit 02: Web Technologies (2/2)
 
High performance website
High performance websiteHigh performance website
High performance website
 
Building production websites with Node.js on the Microsoft stack
Building production websites with Node.js on the Microsoft stackBuilding production websites with Node.js on the Microsoft stack
Building production websites with Node.js on the Microsoft stack
 
Bt0083 server side programing
Bt0083 server side programing Bt0083 server side programing
Bt0083 server side programing
 
SharePoint 2013 Performance Analysis - Robi Vončina
SharePoint 2013 Performance Analysis - Robi VončinaSharePoint 2013 Performance Analysis - Robi Vončina
SharePoint 2013 Performance Analysis - Robi Vončina
 
Session 33 - Session Management using other Techniques
Session 33 - Session Management using other TechniquesSession 33 - Session Management using other Techniques
Session 33 - Session Management using other Techniques
 
Web Performance Optimization (WPO)
Web Performance Optimization (WPO)Web Performance Optimization (WPO)
Web Performance Optimization (WPO)
 
19_JavaScript - Storage_Cookies-tutorial .pptx
19_JavaScript - Storage_Cookies-tutorial .pptx19_JavaScript - Storage_Cookies-tutorial .pptx
19_JavaScript - Storage_Cookies-tutorial .pptx
 
19_JavaScript - Storage_Cookies_students.pptx
19_JavaScript - Storage_Cookies_students.pptx19_JavaScript - Storage_Cookies_students.pptx
19_JavaScript - Storage_Cookies_students.pptx
 
Code for Startup MVP (Ruby on Rails) Session 1
Code for Startup MVP (Ruby on Rails) Session 1Code for Startup MVP (Ruby on Rails) Session 1
Code for Startup MVP (Ruby on Rails) Session 1
 
01 - Web Programming Intro.pptx
01 - Web Programming Intro.pptx01 - Web Programming Intro.pptx
01 - Web Programming Intro.pptx
 

More from DeeptiJava

Java Generics
Java GenericsJava Generics
Java Generics
DeeptiJava
 
Java Collection
Java CollectionJava Collection
Java Collection
DeeptiJava
 
Java Exception Handling
Java Exception HandlingJava Exception Handling
Java Exception Handling
DeeptiJava
 
Java OOPs
Java OOPs Java OOPs
Java OOPs
DeeptiJava
 
Java Access Specifier
Java Access SpecifierJava Access Specifier
Java Access Specifier
DeeptiJava
 
Java JDBC
Java JDBCJava JDBC
Java JDBC
DeeptiJava
 
Java Thread
Java ThreadJava Thread
Java Thread
DeeptiJava
 
Java Inner Class
Java Inner ClassJava Inner Class
Java Inner Class
DeeptiJava
 
JSP Part 2
JSP Part 2JSP Part 2
JSP Part 2
DeeptiJava
 
JSP Part 1
JSP Part 1JSP Part 1
JSP Part 1
DeeptiJava
 
Java I/O
Java I/OJava I/O
Java I/O
DeeptiJava
 
Java Hibernate Basics
Java Hibernate BasicsJava Hibernate Basics
Java Hibernate Basics
DeeptiJava
 
Introduction to Java
Introduction to JavaIntroduction to Java
Introduction to Java
DeeptiJava
 

More from DeeptiJava (13)

Java Generics
Java GenericsJava Generics
Java Generics
 
Java Collection
Java CollectionJava Collection
Java Collection
 
Java Exception Handling
Java Exception HandlingJava Exception Handling
Java Exception Handling
 
Java OOPs
Java OOPs Java OOPs
Java OOPs
 
Java Access Specifier
Java Access SpecifierJava Access Specifier
Java Access Specifier
 
Java JDBC
Java JDBCJava JDBC
Java JDBC
 
Java Thread
Java ThreadJava Thread
Java Thread
 
Java Inner Class
Java Inner ClassJava Inner Class
Java Inner Class
 
JSP Part 2
JSP Part 2JSP Part 2
JSP Part 2
 
JSP Part 1
JSP Part 1JSP Part 1
JSP Part 1
 
Java I/O
Java I/OJava I/O
Java I/O
 
Java Hibernate Basics
Java Hibernate BasicsJava Hibernate Basics
Java Hibernate Basics
 
Introduction to Java
Introduction to JavaIntroduction to Java
Introduction to Java
 

Recently uploaded

State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
UiPathCommunity
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
Elena Simperl
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
Dorra BARTAGUIZ
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Inflectra
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
Alison B. Lowndes
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Ramesh Iyer
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
Elena Simperl
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
Product School
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
ControlCase
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
DianaGray10
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
Safe Software
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Albert Hoitingh
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Tobias Schneck
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
Thijs Feryn
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Product School
 

Recently uploaded (20)

State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
 

Generating the Server Response: HTTP Status Codes

  • 1. Java/J2EE Programming Training Generating the Server Response: HTTP Status Codes
  • 2. Page 2Classification: Restricted Agenda • Format of the HTTP response • How to set status codes • What the status codes are good for • Shortcut methods for redirection and error pages • A servlet that redirects users to browser-specific pages • A front end to various search engines
  • 3. Page 3Classification: Restricted • Request • GET /servlet/SomeName HTTP/1.1 • Host: ... • Header2: ... • ... • HeaderN: • (Blank Line) • Response • HTTP/1.1 200 OK • Content-Type: text/html • Header2: ... • ... • HeaderN: ... • (Blank Line) • <!DOCTYPE ...> • <HTML> • <HEAD>...</HEAD> • <BODY> • ... • </BODY></HTML> HTTP Request/Response
  • 4. Page 4Classification: Restricted • response.setStatus(int statusCode) – Use a constant for the code, not an explicit int. Constants are in HttpServletResponse – Names derived from standard message. E.g., SC_OK, SC_NOT_FOUND, etc. • response.sendError(int code, String message) – Wraps message inside small HTML document • response.sendRedirect(String url) – Sets status code to 302 – Sets Location response header also Setting Status Codes
  • 5. Page 5Classification: Restricted • 200 (OK) – Everything is fine; document follows. – Default for servlets. • 204 (No Content) – Browser should keep displaying previous document. • 301 (Moved Permanently) – Requested document permanently moved elsewhere (indicated in Location header). – Browsers go to new location automatically. Common HTTP 1.1 Status Codes
  • 6. Page 6Classification: Restricted • 302 (Found) – Requested document temporarily moved elsewhere (indicated in Location header). – Browsers go to new location automatically. – Servlets should use sendRedirect, not setStatus, when setting this header. See example. • 401 (Unauthorized) – Browser tried to access password-protected page without proper Authorization header. • 404 (Not Found) – No such page. Servlets should use sendError to set this. – Problem: Internet Explorer and small (< 512KB) error pages. IE ignores error page by default. – Fun and games: http://www.plinko.net/404/ Common HTTP 1.1 Status Codes (Continued)
  • 7. Page 7Classification: Restricted • public class WrongDestination extends HttpServlet { • public void doGet(HttpServletRequest request, • HttpServletResponse response) • throws ServletException, IOException { • String userAgent = request.getHeader("User-Agent"); • if ((userAgent != null) && • (userAgent.indexOf("MSIE") != -1)) { • response.sendRedirect("http://home.netscape.com"); • } else { • response.sendRedirect("http://www.microsoft.com"); • } • } • } A Servlet That Redirects Users to Browser-Specific Pages
  • 8. Page 8Classification: Restricted A Servlet That Redirects Users to Browser-Specific Pages
  • 9. Generating the Server Response: HTTP Response Headers
  • 10. Page 10Classification: Restricted Agenda • Format of the HTTP response • Setting response headers • Understanding what response headers are good for • Building Excel spread sheets • Sending incremental updates to the browser
  • 11. Page 11Classification: Restricted • Request • GET /servlet/SomeName HTTP/1.1 • Host: ... • Header2: ... • ... • HeaderN: • (Blank Line) • Response • HTTP/1.1 200 OK • Content-Type: text/html • Header2: ... • ... • HeaderN: ... • (Blank Line) • <!DOCTYPE ...> • <HTML> • <HEAD>...</HEAD> • <BODY> • ... • </BODY></HTML> HTTP Request/Response
  • 12. Page 12Classification: Restricted • public void setHeader(String headerName, String headerValue) – Sets an arbitrary header • public void setDateHeader(String name, long millisecs) – Converts milliseconds since 1970 to a date string in GMT format • public void setIntHeader(String name, int headerValue) – Prevents need to convert int to String before calling setHeader • addHeader, addDateHeader, addIntHeader – Adds new occurrence of header instead of replacing Setting Arbitrary Response Headers
  • 13. Page 13Classification: Restricted • setContentType – Sets the Content-Type header. – Servlets almost always use this. – See table of common MIME types. • setContentLength – Sets the Content-Length header. – Used for persistent HTTP connections. – See Connection request header. • addCookie – Adds a value to the Set-Cookie header. – See separate section on cookies. • sendRedirect – Sets the Location header (plus changes status code). Setting Arbitrary Response Headers
  • 14. Page 14Classification: Restricted Type Meaning application/msword Microsoft Word document application/octet-stream Unrecognized or binary data application/pdf Acrobat (.pdf) file application/postscript PostScript file application/vnd.ms-excel Excel spreadsheet application/vnd.ms-powerpoint Powerpoint presentation application/x-gzip Gzip archive application/x-java-archive JAR file application/x-java-vm Java bytecode (.class) file application/zip Zip archive audio/basic Sound file in .au or .snd format audio/x-aiff AIFF sound file audio/x-wav Microsoft Windows sound file audio/midi MIDI sound file text/css HTML cascading style sheet text/html HTML document text/plain Plain text text/xml XML document image/gif GIF image image/jpeg JPEG image image/png PNG image image/tiff TIFF image video/mpeg MPEG video clip video/quicktime QuickTime video clip Common MIME Types
  • 15. Page 15Classification: Restricted • Cache-Control (1.1) and Pragma (1.0) – A no-cache value prevents browsers from caching page. • Content-Disposition – Lets you request that the browser ask the user to save the response to disk in a file of the given name • Content-Disposition: attachment; filename=file-name • Content-Encoding – The way document is encoded. See earlier compression example • Content-Length – The number of bytes in the response. – See setContentLength on previous slide. – Use ByteArrayOutputStream to buffer document before sending it, so that you can determine size. See discussion of the Connection request header Common HTTP 1.1 Response Headers
  • 16. Page 16Classification: Restricted • Content-Type – The MIME type of the document being returned. – Use setContentType to set this header. • Expires – The time at which document should be considered out-of-date and thus should no longer be cached. – Use setDateHeader to set this header. • Last-Modified – The time document was last changed. – Don’t set this header explicitly; provide a getLastModified method instead. See lottery number example in book (Chapter 3). Common HTTP 1.1 Response Headers (Continued)
  • 17. Page 17Classification: Restricted • Location – The URL to which browser should reconnect. – Use sendRedirect instead of setting this directly. • Refresh – The number of seconds until browser should reload page. Can also include URL to connect to. See following example. • Set-Cookie – The cookies that browser should remember. Don’t set this header directly; use addCookie instead. See next section. • WWW-Authenticate – The authorization type and realm needed in Authorization header. See security chapters in More Servlets & JSP. Common HTTP 1.1 Response Headers (Continued)
  • 19. Page 19Classification: Restricted Agenda • Understanding the benefits and drawbacks of cookies • Sending outgoing cookies • Receiving incoming cookies • Tracking repeat visitors • Specifying cookie attributes • Differentiating between session cookies and persistent cookies • Simplifying cookie usage with utility classes • Modifying cookie values • Remembering user preferences
  • 20. Page 20Classification: Restricted • Idea – Servlet sends a simple name and value to client. – Client returns same name and value when it connects to same site (or same domain, depending on cookie settings). • Typical Uses of Cookies – Identifying a user during an e-commerce session • Servlets have a higher-level API for this task – Avoiding username and password – Customizing a site – Focusing advertising The Potential of Cookies
  • 21. Page 21Classification: Restricted Cookies and Focused Advertising
  • 22. Page 22Classification: Restricted • The problem is privacy, not security. – Servers can remember your previous actions – If you give out personal information, servers can link that information to your previous actions – Servers can share cookie information through use of a cooperating third party like doubleclick.net – Poorly designed sites store sensitive information like credit card numbers directly in cookie – JavaScript bugs let hostile sites steal cookies (old browsers) • Moral for servlet authors – If cookies are not critical to your task, avoid servlets that totally fail when cookies are disabled – Don't put sensitive info in cookies Some Problems with Cookies
  • 23. Page 23Classification: Restricted Manually Deleting Cookies (To Simplify Testing)
  • 24. Page 24Classification: Restricted • Create a Cookie object. – Call the Cookie constructor with a cookie name and a cookie value, both of which are strings. • Cookie c = new Cookie("userID", "a1234"); • Set the maximum age. – To tell browser to store cookie on disk instead of just in memory, use setMaxAge (argument is in seconds) • c.setMaxAge(60*60*24*7); // One week • Place the Cookie into the HTTP response – Use response.addCookie. – If you forget this step, no cookie is sent to the browser! • response.addCookie(c); Sending Cookies to the Client
  • 25. Page 25Classification: Restricted • Call request.getCookies – This yields an array of Cookie objects. • Loop down the array, calling getName on each entry until you find the cookie of interest – Use the value (getValue) in application-specific way. – String cookieName = "userID"; – Cookie[] cookies = request.getCookies(); – if (cookies != null) { – for(int i=0; i<cookies.length; i++) { – Cookie cookie = cookies[i]; – if (cookieName.equals(cookie.getName())) { – doSomethingWith(cookie.getValue()); – } – } – } Reading Cookies from the Client
  • 26. Page 26Classification: Restricted • public class RepeatVisitor extends HttpServlet { • public void doGet(HttpServletRequest request, • HttpServletResponse response) • throws ServletException, IOException { • boolean newbie = true; • Cookie[] cookies = request.getCookies(); • if (cookies != null) { • for(int i=0; i<cookies.length; i++) { • Cookie c = cookies[i]; • if ((c.getName().equals("repeatVisitor"))&& • (c.getValue().equals("yes"))) { • newbie = false; • break; • } • } • } Using Cookies to Detect First-Time Visitors
  • 27. Page 27Classification: Restricted • String title; • if (newbie) { • Cookie returnVisitorCookie = • new Cookie("repeatVisitor", "yes"); • returnVisitorCookie.setMaxAge(60*60*24*365); • response.addCookie(returnVisitorCookie); • title = "Welcome Aboard"; • } else { • title = "Welcome Back"; • } • response.setContentType("text/html"); • PrintWriter out = response.getWriter(); • … // (Output page with above title) Using Cookies to Detect First-Time Visitors (Continued)
  • 28. Page 28Classification: Restricted Using Cookies to Detect First-Time Visitors (Results)
  • 29. Page 29Classification: Restricted • getDomain/setDomain – Lets you specify domain to which cookie applies. Current host must be part of domain specified. • getMaxAge/setMaxAge – Gets/sets the cookie expiration time (in seconds). If you fail to set this, cookie applies to current browsing session only. See LongLivedCookie helper class given earlier. • getName – Gets the cookie name. There is no setName method; you supply name to constructor. For incoming cookie array, you use getName to find the cookie of interest. Using Cookie Attributes
  • 30. Page 30Classification: Restricted • getPath/setPath – Gets/sets the path to which cookie applies. If unspecified, cookie applies to URLs that are within or below directory containing current page. • getSecure/setSecure – Gets/sets flag indicating whether cookie should apply only to SSL connections or to all connections. • getValue/setValue – Gets/sets value associated with cookie. For new cookies, you supply value to constructor, not to setValue. For incoming cookie array, you use getName to find the cookie of interest, then call getValue on the result. If you set the value of an incoming cookie, you still have to send it back out with response.addCookie. Using Cookie Attributes
  • 31. Page 31Classification: Restricted • public class CookieTest extends HttpServlet { • public void doGet(HttpServletRequest request, • HttpServletResponse response) • throws ServletException, IOException { • for(int i=0; i<3; i++) { • Cookie cookie = • new Cookie("Session-Cookie-" + i, • "Cookie-Value-S" + i); • // No maxAge (ie maxAge = -1) • response.addCookie(cookie); • cookie = new Cookie("Persistent-Cookie-" + i, • "Cookie-Value-P" + i); • cookie.setMaxAge(3600); • response.addCookie(cookie); • } Differentiating Session Cookies from Persistent Cookies
  • 32. Page 32Classification: Restricted Differentiating Session Cookies from Persistent Cookies (Cont) • … // Start an HTML table • Cookie[] cookies = request.getCookies(); • if (cookies == null) { • out.println("<TR><TH COLSPAN=2>No cookies"); • } else { • Cookie cookie; • for(int i=0; i<cookies.length; i++) { • cookie = cookies[i]; • out.println • ("<TR>n" + • " <TD>" + cookie.getName() + "n" + • " <TD>" + cookie.getValue()); • } • }
  • 33. Page 33Classification: Restricted • Result of initial visit to CookieTest servlet – Same result as when visiting the servlet, quitting the browser, waiting an hour, and revisiting the servlet. Differentiating Session Cookies from Persistent Cookies
  • 34. Page 34Classification: Restricted • Result of revisiting CookieTest within an hour of original visit (same browser session) – I.e., browser stayed open between the original visit and the visit shown here Differentiating Session Cookies from Persistent Cookies
  • 36. Page 36Classification: Restricted • Implementing session tracking from scratch • Using basic session tracking • Understanding the session-tracking API • Differentiating between server and browser sessions • Encoding URLs • Storing immutable objects vs. storing mutable objects • Tracking user access counts • Accumulating user purchases • Implementing a shopping cart • Building an online store Agenda
  • 37. Page 37Classification: Restricted • Idea: associate cookie with data on server – String sessionID = makeUniqueString(); – HashMap sessionInfo = new HashMap(); – HashMap globalTable = findTableStoringSessions(); – globalTable.put(sessionID, sessionInfo); – Cookie sessionCookie = – new Cookie("JSESSIONID", sessionID); – sessionCookie.setPath("/"); – response.addCookie(sessionCookie); • Still to be done: – Extracting cookie that stores session identifier – Setting appropriate expiration time for cookie – Associating the hash tables with each request – Generating the unique session identifiers Rolling Your Own Session Tracking: Cookies
  • 38. Page 38Classification: Restricted • Idea – Client appends some extra data on the end of each URL that identifies the session – Server associates that identifier with data it has stored about that session – E.g., http://host/path/file.html;jsessionid=1234 • Advantage – Works even if cookies are disabled or unsupported • Disadvantages – Must encode all URLs that refer to your own site – All pages must be dynamically generated – Fails for bookmarks and links from other sites Rolling Your Own Session Tracking: URL-Rewriting
  • 39. Page 39Classification: Restricted • Idea: – <INPUT TYPE="HIDDEN" NAME="session" VALUE="..."> • Advantage – Works even if cookies are disabled or unsupported • Disadvantages – Lots of tedious processing – All pages must be the result of form submissions Rolling Your Own Session Tracking: Hidden Form Fields
  • 40. Page 40Classification: Restricted • Session objects live on the server • Sessions automatically associated with client via cookies or URL-rewriting – Use request.getSession to get session • Behind the scenes, the system looks at cookie or URL extra info and sees if it matches the key to some previously stored session object. If so, it returns that object. If not, it creates a new one, assigns a cookie or URL info as its key, and returns that new session object. • Hashtable-like mechanism lets you store arbitrary objects inside session – setAttribute stores values – getAttribute retrieves values Session Tracking in Java
  • 41. Page 41Classification: Restricted • Access the session object – Call request.getSession to get HttpSession object • This is a hashtable associated with the user • Look up information associated with a session. – Call getAttribute on the HttpSession object, cast the return value to the appropriate type, and check whether the result is null. • Store information in a session. – Use setAttribute with a key and a value. • Discard session data. – Call removeAttribute discards a specific value. – Call invalidate to discard an entire session. – Call logout to log the client out of the Web/app server Session Tracking Basics
  • 42. Page 42Classification: Restricted • HttpSession session = request.getSession(); • SomeClass value = • (SomeClass)session.getAttribute("someID"); • if (value == null) { • value = new SomeClass(...); • session.setAttribute("someID", value); • } • doSomethingWith(value); – Do not need to call setAttribute again (after modifying value) if the modified value is the same object. But, if value is immutable, modified value will be a new object reference, and you must call setAttribute again. Session Tracking Basics: Sample Code
  • 43. Page 43Classification: Restricted • Session tracking code: – No change • Code that generates hypertext links back to same site: – Pass URL through response.encodeURL. • If server is using cookies, this returns URL unchanged • If server is using URL rewriting, this appends the session info to the URL • E.g.: String url = "order-page.html"; url = response.encodeURL(url); • Code that does sendRedirect to own site: – Pass URL through response.encodeRedirectURL What Changes if Server Uses URL Rewriting?
  • 44. Page 44Classification: Restricted • getAttribute – Extracts a previously stored value from a session object. Returns null if no value is associated with given name. • setAttribute – Associates a value with a name. Monitor changes: values implement HttpSessionBindingListener. • removeAttribute – Removes values associated with name. • getAttributeNames – Returns names of all attributes in the session. • getId – Returns the unique identifier. HttpSession Methods
  • 45. Page 45Classification: Restricted • isNew – Determines if session is new to client (not to page) • getCreationTime – Returns time at which session was first created • getLastAccessedTime – Returns time at which session was last sent from client • getMaxInactiveInterval, setMaxInactiveInterval – Gets or sets the amount of time session should go without access before being invalidated • invalidate – Invalidates current session • logout – Invalidates all sessions associated with user HttpSession Methods (Continued)
  • 46. Page 46Classification: Restricted • public class ShowSession extends HttpServlet { • public void doGet(HttpServletRequest request, • HttpServletResponse response) • throws ServletException, IOException { • response.setContentType("text/html"); • HttpSession session = request.getSession(); • String heading; • Integer accessCount = • (Integer)session.getAttribute("accessCount"); • if (accessCount == null) { • accessCount = new Integer(0); • heading = "Welcome, Newcomer"; • } else { heading = "Welcome Back"; • accessCount = • new Integer(accessCount.intValue() + 1); • } • session.setAttribute("accessCount", accessCount); A Servlet that Shows Per-Client Access Counts
  • 47. Page 47Classification: Restricted • PrintWriter out = response.getWriter(); • … • out.println • (docType + • "<HTML>n" + • "<HEAD><TITLE>" + title + "</TITLE></HEAD>n" + • "<BODY BGCOLOR="#FDF5E6">n" + • "<CENTER>n" + • "<H1>" + heading + "</H1>n" + • "<H2>Information on Your Session:</H2>n" + • "<TABLE BORDER=1>n" + • "<TR BGCOLOR="#FFAD00">n" + • " <TH>Info Type<TH>Valuen" + • … • " <TD>Number of Previous Accessesn" + • " <TD>" + accessCount + "n" + • "</TABLE>n" + • "</CENTER></BODY></HTML>"); A Servlet that Shows Per-Client Access Counts (Continued)
  • 48. Page 48Classification: Restricted A Servlet that Shows Per-Client Access Counts: Result 2