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

PDF
Tuning Web Performance
PDF
CTU June 2011 - Things that Every ASP.NET Developer Should Know
 
PDF
Please dont touch-3.5
PDF
C fowler azure-dojo
PDF
Please Don't Touch the Slow Parts V3
PPTX
Varnish Cache and its usage in the real world!
PPTX
IBM Connect 2016 - Break out of the Box
PPTX
Break out of The Box - Part 2
Tuning Web Performance
CTU June 2011 - Things that Every ASP.NET Developer Should Know
 
Please dont touch-3.5
C fowler azure-dojo
Please Don't Touch the Slow Parts V3
Varnish Cache and its usage in the real world!
IBM Connect 2016 - Break out of the Box
Break out of The Box - Part 2

What's hot (20)

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

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

PDF
06 response-headers
PDF
04 request-headers
PDF
05 status-codes
PPTX
Http - All you need to know
PPTX
Session 26 - Servlets Part 2
PDF
Servlets http-status-codes
PPTX
HTTP
PPTX
Introduction to HTTP protocol
PPTX
HTTP fundamentals for developers
PDF
Servlet sessions
PPT
Java servlet life cycle - methods ppt
PPTX
Web technologies: HTTP
PPTX
Advance java session 7
PPTX
SCWCD : The web client model
PPTX
Http-protocol
PPTX
Jsp server response
PPTX
Session 29 - Servlets - Part 5
PDF
Servlets
PPTX
general protocol basics
06 response-headers
04 request-headers
05 status-codes
Http - All you need to know
Session 26 - Servlets Part 2
Servlets http-status-codes
HTTP
Introduction to HTTP protocol
HTTP fundamentals for developers
Servlet sessions
Java servlet life cycle - methods ppt
Web technologies: HTTP
Advance java session 7
SCWCD : The web client model
Http-protocol
Jsp server response
Session 29 - Servlets - Part 5
Servlets
general protocol basics
Ad

More from DeeptiJava (13)

PPTX
Java Generics
PPTX
Java Collection
PPTX
Java Exception Handling
PPTX
Java OOPs
PPTX
Java Access Specifier
PPTX
Java JDBC
PPTX
Java Thread
PPTX
Java Inner Class
PPT
JSP Part 2
PPT
JSP Part 1
PPTX
Java I/O
PPT
Java Hibernate Basics
PPTX
Introduction to Java
Java Generics
Java Collection
Java Exception Handling
Java OOPs
Java Access Specifier
Java JDBC
Java Thread
Java Inner Class
JSP Part 2
JSP Part 1
Java I/O
Java Hibernate Basics
Introduction to Java

Recently uploaded (20)

PDF
Event Presentation Google Cloud Next Extended 2025
PDF
Smarter Business Operations Powered by IoT Remote Monitoring
PPTX
breach-and-attack-simulation-cybersecurity-india-chennai-defenderrabbit-2025....
PDF
CIFDAQ's Market Wrap: Ethereum Leads, Bitcoin Lags, Institutions Shift
 
PDF
SparkLabs Primer on Artificial Intelligence 2025
PPTX
CroxyProxy Instagram Access id login.pptx
PDF
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
PDF
Test Bank, Solutions for Java How to Program, An Objects-Natural Approach, 12...
PDF
Building High-Performance Oracle Teams: Strategic Staffing for Database Manag...
PDF
NewMind AI Weekly Chronicles - July'25 - Week IV
PPTX
The-Ethical-Hackers-Imperative-Safeguarding-the-Digital-Frontier.pptx
PDF
Transforming Manufacturing operations through Intelligent Integrations
PDF
GamePlan Trading System Review: Professional Trader's Honest Take
PDF
Top Generative AI Tools for Patent Drafting in 2025.pdf
PDF
A Day in the Life of Location Data - Turning Where into How.pdf
PDF
DevOps & Developer Experience Summer BBQ
 
PDF
Orbitly Pitch Deck|A Mission-Driven Platform for Side Project Collaboration (...
PDF
REPORT: Heating appliances market in Poland 2024
 
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PDF
Using Anchore and DefectDojo to Stand Up Your DevSecOps Function
Event Presentation Google Cloud Next Extended 2025
Smarter Business Operations Powered by IoT Remote Monitoring
breach-and-attack-simulation-cybersecurity-india-chennai-defenderrabbit-2025....
CIFDAQ's Market Wrap: Ethereum Leads, Bitcoin Lags, Institutions Shift
 
SparkLabs Primer on Artificial Intelligence 2025
CroxyProxy Instagram Access id login.pptx
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
Test Bank, Solutions for Java How to Program, An Objects-Natural Approach, 12...
Building High-Performance Oracle Teams: Strategic Staffing for Database Manag...
NewMind AI Weekly Chronicles - July'25 - Week IV
The-Ethical-Hackers-Imperative-Safeguarding-the-Digital-Frontier.pptx
Transforming Manufacturing operations through Intelligent Integrations
GamePlan Trading System Review: Professional Trader's Honest Take
Top Generative AI Tools for Patent Drafting in 2025.pdf
A Day in the Life of Location Data - Turning Where into How.pdf
DevOps & Developer Experience Summer BBQ
 
Orbitly Pitch Deck|A Mission-Driven Platform for Side Project Collaboration (...
REPORT: Heating appliances market in Poland 2024
 
Understanding_Digital_Forensics_Presentation.pptx
Using Anchore and DefectDojo to Stand Up Your DevSecOps Function

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