Slides © Marty Hall, book © Sun Microsystems Press 1 Generating the HTTP Response Core Servlets & JSP book:

Slides:



Advertisements
Similar presentations
JLab Lattice Portal – Data Grid Web Service Ying Chen, Chip Watson Thomas Jefferson National Accelerator Facility.
Advertisements

Cookie in a servlet. Cookies are small bits of textual information that a Web server sends to a browser and that the browser returns unchanged when visiting.
Web Application: Java Servlets INE2720 Web Application Software Development Essential Materials.
Introduction to Servlets Based on: Hall, Brown, Core Servlets and JavaServer Pages.
Objectives Ch. D - 1 At the end of this chapter students will: Know the general architecture and purpose of servlets Understand how to create a basic servlet.
Core servlets chapter 6 Generating server response: http status codes.
HTTP – HyperText Transfer Protocol
CS320 Web and Internet Programming Generating HTTP Responses
16-Jun-15 HTTP Hypertext Transfer Protocol. 2 HTTP messages HTTP is the language that web clients and web servers use to talk to each other HTTP is largely.
J2EE Servlets and JSP Advanced topics Presented by Bartosz Sakowicz.
HTTP Hypertext Transfer Protocol. HTTP messages HTTP is the language that web clients and web servers use to talk to each other –HTTP is largely “under.
Core Servlets Chapter 3 Link for Core Servlets code: om/archive/ om/archive/
HTTP Response Headers Vijayan Sugumaran Department of DIS Oakland University Parts of this presentation was provided by
Hypertext Transfer Protocol Information Systems 337 Prof. Harry Plantinga.
1 Handling the Client Request: HTTP Request Headers Parts of this presentation was provided by Vijayan Sugumaran Department of DIS.
2/9/2004 Web and HTTP February 9, /9/2004 Assignments Due – Reading and Warmup Work on Message of the Day.
Hypertext Transport Protocol CS Dick Steflik.
CSC 2720 Building Web Applications Servlet – Getting and Setting HTTP Headers.
Slides © Marty Hall, book © Sun Microsystems Press 1 Handling the Client Request: HTTP Request Headers Core Servlets & JSP.
Servlets Compiled by Dr. Billy B. L. Lim. Servlets Servlets are Java programs which are invoked to service client requests on a Web server. Servlets extend.
Servlets. Our Project 3-tier application Develop our own multi-threaded server Socket level communication.
A Servlet’s Job Read explicit data sent by client (form data) Read implicit data sent by client (request headers) Generate the results Send the explicit.
Java Servlets. What Are Servlets? Basically, a java program that runs on the server Basically, a java program that runs on the server Creates dynamic.
Gayle J Yaverbaum, PhD Professor of Information Systems Penn State Harrisburg.
FALL 2005CSI 4118 – UNIVERSITY OF OTTAWA1 Part 4 Web technologies: HTTP, CGI, PHP,Java applets)
J2EE training: 1 TODO Replace Netscape examples with Firefox. In later two sections also.
Simple Web Services. Internet Basics The Internet is based on a communication protocol named TCP (Transmission Control Protocol) TCP allows programs running.
CSC 2720 Building Web Applications Getting and Setting HTTP Headers (With PHP Examples)
1 Lecture #7-8 HTTP – HyperText Transfer Protocol HAIT Summer 2005 Shimrit Tzur-David.
1 Chapter 1: Overview of Servlets and JavaSerevr Pages.
J2EE training: 1 Course Material Usage Rules PowerPoint slides for use only in full-semester, for-credit courses at degree-granting.
CP476 Internet Computing Lecture 5 : HTTP, WWW and URL 1 Lecture 5. WWW, HTTP and URL Objective: to review the concepts of WWW to understand how HTTP works.
Rensselaer Polytechnic Institute Shivkumar Kalvanaraman, Biplab Sikdar 1 The Web: the http protocol http: hypertext transfer protocol Web’s application.
Generating the Server Response: HTTP Response Headers.
Slides © Marty Hall, book © Sun Microsystems Press 1 Including Files & Applets in JSP Documents Core Servlets & JSP book:
J2EE training: 1 Course Material Usage Rules PowerPoint slides for use only in full-semester, for-credit courses at degree-granting.
SKT-SSU IT Training Center Servlet and JSP. Chapter Three: Servlet Basics.
Li Tak Sing COMPS311F. Static attributes in Servlets Since Servlets are also Java classes, you can also use static attributes to store values that can.
COMP 321 Week 7. Overview HTML and HTTP Basics Dynamic Web Content ServletsMVC Tomcat in Eclipse Demonstration Lab 7-1 Introduction.
J2EE training: 1 Course Material Usage Rules PowerPoint slides for use only in full-semester, for-credit courses at degree-granting.
Chapter 5 HTTP Request Headers. Content 1.Request headers 2.Reading Request Headers 3.Making a Table of All Request Headers 4.Sending Compressed Web Pages.
Slides © Marty Hall, book © Sun Microsystems Press 1 JSP Scripting Elements Core Servlets & JSP book:
Chapter 3 Servlet Basics. 1.Recall the Servlet Role 2.Basic Servlet Structure 3.A simple servlet that generates plain text 4.A servlet that generates.
Java Servlets. Servlets When we run small Java programs within a browser these are referred to as Applets... And when we run small Java programs within.
Slides © Marty Hall, book © Sun Microsystems Press 1 Handling the Client Request: Form Data Core Servlets & JSP book:
SKT-SSU IT Training Center Servlet and JSP. Chapter Five: Handling the Client Request: HTTP Request Headers.
CIS679: Lecture 13 r Review of Last Lecture r More on HTTP.
Saving Client State Session Tracking: Maintain state about series of requests from same client over time Using Cookies: Clients hold small amount of their.
1-1 HTTP request message GET /somedir/page.html HTTP/1.1 Host: User-agent: Mozilla/4.0 Connection: close Accept-language:fr request.
1 Handling the Client Request: HTTP Request Headers.
S ERVLETS Cookies Handling 5-Dec-15. S ERVLETS - C OOKIES H ANDLING Cookies are text files stored on the client computer and they are kept for various.
Slides © Marty Hall, book © Sun Microsystems Press 1 Handling Cookies Core Servlets & JSP book: More.
Li Tak Sing COMPS311F. A web page that counts the number of times that you have visited the page. You can try the page at:
Appendix E: Overview of HTTP ©SoftMoore ConsultingSlide 1.
Operating Systems Lesson 12. HTTP vs HTML HTML: hypertext markup language ◦ Definitions of tags that are added to Web documents to control their appearance.
CITA 310 Section 2 HTTP (Selected Topics from Textbook Chapter 6)
CSI 3125, Preliminaries, page 1 SERVLET. CSI 3125, Preliminaries, page 2 SERVLET A servlet is a server-side software program, Responds oriented other.
© Marty Hall, Larry Brown Web core programming 1 Using Applets as Front Ends to Server-Side Programs.
HTTP Here, we examine the hypertext transfer protocol (http) – originally introduced around 1990 but not standardized until 1997 (version 1.0) – protocol.
Slides © Marty Hall, book © Sun Microsystems Press 1 Session Tracking Core Servlets & JSP book: More.
SKT-SSU IT Training Center Servlet and JSP. Chapter Seven: Generating the Server Response: HTTP Response Headers.
® IBM Software Group © 2007 IBM Corporation Servlet API (Part II)
Servlets 4 Lec 30 Web Design and Development. Looking Back… Response Redirection  Sending a standard redirect  Sending a redirect to an error page Request.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 21 Java Servlets Wed. 11/22/00 based on material.
Java Servlets and Java Server Pages
HTTP protocol Java Servlets. HTTP protocol Web system communicates with end-user via HTTP protocol HTTP protocol methods: GET, POST, HEAD, PUT, OPTIONS,
Using Applets as Front Ends to Server-Side Programs.
Simple Web Services. Internet Basics The Internet is based on a communication protocol named TCP (Transmission Control Protocol) TCP allows programs running.
CS320 Web and Internet Programming Generating HTTP Responses
Generating the Server Response: HTTP Status Codes
Presentation transcript:

Slides © Marty Hall, book © Sun Microsystems Press 1 Generating the HTTP Response Core Servlets & JSP book: More Servlets & JSP book: Servlet and JSP Training Courses: courses.coreservlets.com

HTTP Response2 Agenda Idea of HTTP status codes Setting status codes from servlets Common HTTP 1.1 status codes A common front end to various Web search engines Idea of HTTP response headers Setting response headers from servlets Common HTTP 1.1 response headers Persistent servlet state and auto-reloading pages

HTTP Response3 Generating the Server Response: HTTP Status Codes Example HTTP 1.1 Response HTTP/ OK Content-Type: text/html... Changing the status code lets you perform a number of tasks not otherwise possible –Forward client to another page –Indicate a missing resource –Instruct browser to use cached copy Set status before sending document

HTTP Response4 Setting Status Codes 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) –Relative URLs permitted in 2.2 and later –Sets Location header also

HTTP Response5 Common HTTP 1.1 Status Codes 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.

HTTP Response6 Common HTTP 1.1 Status Codes (Continued) 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. See example in book. 404 (Not Found) –No such page. Servlets should use sendError to set this. –Problem: Internet Explorer 5.0. –Fun and games:

HTTP Response7 A Front End to Various Search Engines: Code public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String searchString = request.getParameter("searchString"); if ((searchString == null) || (searchString.length() == 0)) { reportProblem(response, "Missing search string."); return; } searchString = URLEncoder.encode(searchString); String numResults = request.getParameter("numResults");... String searchEngine = request.getParameter("searchEngine");

HTTP Response8 A Front End to Various Search Engines: Code (Continued) SearchSpec[] commonSpecs = SearchSpec.getCommonSpecs(); for(int i=0; i<commonSpecs.length; i++) { SearchSpec searchSpec = commonSpecs[i]; if (searchSpec.getName().equals(searchEngine)) { String url = searchSpec.makeURL(searchString, numResults); response.sendRedirect(url); return; } reportProblem(response, "Unrecognized search engine.");

HTTP Response9 A Front End to Various Search Engines: Code (Continued) private void reportProblem(HttpServletResponse response, String message) throws IOException { response.sendError(response.SC_NOT_FOUND, message); }

HTTP Response10 Front End to Search Engines: Result of Legal Request

HTTP Response11 Front End to Search Engines: Result of Illegal Request Fix: Tools, Internet Options, deselect "Show 'friendly' HTTP error messages" Not a real fix -- doesn't help unsuspecting users of your pages

HTTP Response12 Generating the Server Response: HTTP Response Headers Purposes –Give forwarding location –Specify cookies –Supply the page modification date –Instruct the browser to reload the page after a designated interval –Give the document size so that persistent HTTP connections can be used –Designate the type of document being generated –Etc.

HTTP Response13 Setting Arbitrary Response Headers 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. Servlets 2.2/2.3 only.

HTTP Response14 Setting Common Response Headers 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).

HTTP Response15 Common MIME Types

HTTP Response16 Common HTTP 1.1 Response Headers Cache-Control (1.1) and Pragma (1.0) –A no-cache value prevents browsers from caching page. Send both headers or check HTTP version. Content-Encoding –The way document is encoded. Browser reverses this encoding before handling document. See compression example earlier. 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 and detailed example in book.

HTTP Response17 Common HTTP 1.1 Response Headers (Continued) 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 example in CSAJSP Chapter 2.

HTTP Response18 Common HTTP 1.1 Response Headers (Continued) 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 example in CSAJSP Section 4.5.

HTTP Response19 Persistent Servlet State and Auto-Reloading Pages Idea: generate list of large (e.g., 150-digit) prime numbers –Show partial results until completed –Let new clients make use of results from others Demonstrates use of the Refresh header. Shows how easy it is for servlets to maintain state between requests. –Very difficult in traditional CGI. Also illustrates that servlets can handle multiple simultaneous connections –Each request is in a separate thread.

HTTP Response20 Generating Prime Numbers: Source Code public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { int numPrimes = ServletUtilities.getIntParameter(request, "numPrimes", 50); int numDigits = ServletUtilities.getIntParameter(request, "numDigits", 120); // findPrimeList is synchronized PrimeList primeList = findPrimeList(primeListVector, numPrimes, numDigits); if (primeList == null) { primeList = new PrimeList(numPrimes, numDigits, true);

HTTP Response21 Generating Prime Numbers: Source Code (Continued) synchronized(primeListVector) { if (primeListVector.size() >= maxPrimeLists) primeListVector.removeElementAt(0); primeListVector.addElement(primeList); } Vector currentPrimes = primeList.getPrimes(); int numCurrentPrimes = currentPrimes.size(); int numPrimesRemaining = (numPrimes - numCurrentPrimes); boolean isLastResult = (numPrimesRemaining == 0); if (!isLastResult) { response.setHeader("Refresh", "5"); } response.setContentType("text/html"); PrintWriter out = response.getWriter(); // Show List of Primes found...

HTTP Response22 Prime Number Servlet: Front End

HTTP Response23 Prime Number Servlet: Initial Result

HTTP Response24 Prime Number Servlet: Final Result

HTTP Response25 Summary Many servlet tasks can only be accomplished through use of HTTP status codes and headers sent to the browser Two parts of the response –Status line In general, set via response.setStatus In special cases, set via response.sendRedirect and response.sendError –Response headers In general, set via response.setHeader In special cases, set via response.setContentType, response.setContentLength, response.addCookie, and response.sendRedirect

HTTP Response26 Summary (Continued) Most important status codes –200 (default) –302 (forwarding; set via sendRedirect) –401 (password needed) –404 (not found; set via sendError) Most important headers you set directly –Cache-Control and Pragma –Content-Encoding –Content-Length –Expires –Refresh –WWW-Authenticate

Slides © Marty Hall, book © Sun Microsystems Press 27 Questions? Core Servlets & JSP book: More Servlets & JSP book: Servlet and JSP Training Courses: courses.coreservlets.com