Handling the Client Request: HTTP Request Headers

Similar documents
Internet Technologies 6 - Servlets I. F. Ricci 2010/2011

Advanced Internet Technology Lab # 5 Handling Client Requests

HTTP Request Handling

In servlet, form parsing is handled automatically. You call request.getparameter to get the value of a form parameter.

Servlet Basics. Agenda

Handling Cookies. Agenda

Generating the Server Response: HTTP Response Headers

Server Side Internet Programming

Session 8. Introduction to Servlets. Semester Project

Session 9. Introduction to Servlets. Lecture Objectives

Servlet and JSP Review

core programming Servlets Marty Hall, Larry Brown

Using Java servlets to generate dynamic WAP content

Generating the Server Response: HTTP Status Codes

Web Based Solutions. Gerry Seidman. IAM Consulting

Advanced Internet Technology Lab # 4 Servlets

Handling Cookies. For live Java EE training, please see training courses at

Servlets Overview

GENERATING THE SERVER RESPONSE: HTTP STATUS CODES

Java Enterprise Edition. Java EE Oct Dec 2016 EFREI/M1 Jacques André Augustin Page 1

Handout 31 Web Design & Development

INTRODUCTION TO SERVLETS AND WEB CONTAINERS. Actions in Accord with All the Laws of Nature

JAVA SERVLET. Server-side Programming INTRODUCTION

Outline. Servlets. Functions of Servlets. Overview. The Advantages of Servlets Over. Why Build Pages Dynamically? Traditional CGI

ServletConfig Interface

Advanced Web Technology

Java4570: Session Tracking using Cookies *

Session 8. JavaBeans. Reading & Reference. Reading. Reference. Session 8 Java Beans. 2/27/2013 Robert Kelly, Head First Chapter 3 (MVC)

Java Servlets. Preparing your System

To follow the Deitel publishing program, sign-up now for the DEITEL BUZZ ON-

WHITE LABELING IN PROGRESS ROLLBASE PRIVATE CLOUD

JAVA SERVLET. Server-side Programming PROGRAMMING

Generating the Server Response:

Berner Fachhochschule Haute cole spcialise bernoise Berne University of Applied Sciences 2

Servlets and JSP (Java Server Pages)

Enterprise Java Unit 1- Chapter 4 Prof. Sujata Rizal Servlet API and Lifecycle

Servlets1. What are Servlets? Where are they? Their job. Servlet container. Only Http?

Lab session Google Application Engine - GAE. Navid Nikaein

Servlets. An extension of a web server runs inside a servlet container

CHAPTER 2: A FAST INTRODUCTION TO BASIC SERVLET PROGRAMMING

Unit-4: Servlet Sessions:

First Servlets. Chapter. Topics in This Chapter

HTTP status codes. Setting status of an HTTPServletResponse

Servlet Fudamentals. Celsina Bignoli

UNIT-VI. HttpServletResponse It extends the ServletResponse interface to provide HTTP-specific functionality in sending a response.

AJP. CHAPTER 5: SERVLET -20 marks

1.264 Lecture 15. Web development environments: JavaScript Java applets, servlets Java (J2EE) Active Server Pages

Database Applications Recitation 6. Project 3: CMUQFlix CMUQ s Movies Recommendation System

SERVLETS INTERVIEW QUESTIONS

Lecture Notes On J2EE

Java servlets CSCI 470: Web Science Keith Vertanen Copyright 2013

HTTP and the Dynamic Web

CIS 3952 [Part 2] Java Servlets and JSP tutorial

Introduction. Literature: Steelman & Murach, Murach s Java Servlets and JSP. Mike Murach & Associates Inc, 2003

Advanced Topics in Operating Systems. Manual for Lab Practices. Enterprise JavaBeans

Session 9. Deployment Descriptor Http. Reading and Reference. en.wikipedia.org/wiki/http. en.wikipedia.org/wiki/list_of_http_headers

Introduction. This course Software Architecture with Java will discuss the following topics:

Web based Applications, Tomcat and Servlets - Lab 3 -

Jawaharlal Nehru Engineering College

Servlets by Example. Joe Howse 7 June 2011

AN OVERVIEW OF SERVLET AND JSP TECHNOLOGY

Servlet. Web Server. Servlets are modules of Java code that run in web server. Internet Explorer. Servlet. Fire Fox. Servlet.

HttpServlet ( Class ) -- we will extend this class to handle GET / PUT HTTP requests

Database Systems Lab. 11. JSP I 충남대학교컴퓨터공학과 데이타베이스시스템연구실

JavaServer Pages (JSP)

Web Programming. Lecture 11. University of Toronto

********************************************************************

CSC309: Introduction to Web Programming. Lecture 8

Servlet for Json or CSV (or XML) A servlet serving either Json or CSV (or XML) based on GET parameter - This version uses org.json

Integrating Servlets and JavaServer Pages Lecture 13

HTTP Protocol and Server-Side Basics

ICOM 5016 Database Systems. Database Users. User Interfaces and Tools. Chapter 8: Application Design and Development.

Connecting the RISC Client to non-javascriptinterfaces

Servlet 5.1 JDBC 5.2 JDBC

CSC309: Introduction to Web Programming. Lecture 11

Session 10. Form Dataset. Lecture Objectives

How does the Web work? HTTP and the Dynamic Web. Naming and URLs. In Action. HTTP in a Nutshell. Protocols. The canonical example in your Web browser

Servlets Basic Operations

SESM Components and Techniques

JdbcResultSet.java. import java.sql.*;

Kamnoetvidya Science Academy. Object Oriented Programming using Java. Ferdin Joe John Joseph. Java Session

2. Follow the installation directions and install the server on ccc. 3. We will call the root of your installation as $TOMCAT_DIR

Session 8. Reading and Reference. en.wikipedia.org/wiki/list_of_http_headers. en.wikipedia.org/wiki/http_status_codes

JAVA SERVLET. Server-side Programming ADVANCED FEATURES

CSC309: Introduction to Web Programming. Lecture 10

Introduction to Web applications with Java Technology 3- Servlets

&' () - #-& -#-!& 2 - % (3" 3 !!! + #%!%,)& ! "# * +,

This tutorial will teach you how to use Java Servlets to develop your web based applications in simple and easy steps.

CE212 Web Application Programming Part 3

Get the cookies from the service request: Cookie[] HttpServletRequest.getCookies() Add a cookie to the service response:

Session 20 Data Sharing Session 20 Data Sharing & Cookies

Backend. (Very) Simple server examples

CH -7 RESPONSE HEADERS

why? Give an app access to a resource managed by someone else, without giving the app your password. A valet key for the web Allen I.

Servlet. 1.1 Web. 1.2 Servlet. HTML CGI Common Gateway Interface Web CGI CGI. Java Applet JavaScript Web. Java CGI Servlet. Java. Apache Tomcat Jetty

Module 4: SERVLET and JSP

Introduction to Java Servlets. SWE 432 Design and Implementation of Software for the Web

Session 11. Ajax. Reading & Reference

Module 3 Web Component

SERVLET AND JSP FILTERS

Transcription:

Handling the Client Request: HTTP Request Headers 1 Agenda Reading HTTP request headers Building a table of all the request headers Understanding the various request headers Reducing download times by compressing pages Differentiating among types of browsers 2

A Typical HTTP Request GET /servlet/search?keywords=servlets+jsphttp/1.1 Accept: image/gif, image/jpg, */* Accept-Encoding: gzip Connection: Keep-Alive Cookie: userid=id456578 Host: www.somebookstore.com Referer: http://www.somebookstore.com/ findbooks.html User-Agent: Mozilla/4.0(compatible; MSIE 6.0; Windows NT 5.0) It shouldn't take a rocket scientist to realize that you need to understand HTTP to be effective with servlets and JSP 3 Reading Request Headers (Methods in HttpServletRequest) General getheader (header name is not case sensitive) getheaders getheadernames Specialized getcookies getauthtype and getremoteuser getcontentlength getcontenttype getdateheader getintheader Related info getmethod, getrequesturi, getquerystring, getprotocol 4

Reading The Main Request Line getmothod getrequesturi getquerystring getprotocol 5 Checking For Missing Headers HTTP 1.0 All request headers are optional HTTP 1.1 Only Host is required Conclusion Always check that request.getheader is non-null before trying to use it String val = request.getheader("some-name"); if (val!= null) { 6

Making a Table of All Request Headers public class ShowRequestHeaders extends HttpServlet { public void doget(httpservletrequest request, HttpServletResponse response) throws ServletException, IOException { out.println (doctype + "<HTML>\n" + "<HEAD><TITLE>"+title+"</TITLE></HEAD>\n"+ "<BODY BGCOLOR=\"#FDF5E6\">\n" + "<H1 ALIGN=\"CENTER\">" + title + "</H1>\n" + "<B>Request Method: </B>" + request.getmethod() + "<BR>\n" + "<B>Request URI: </B>" + request.getrequesturi() + "<BR>\n" + "<B>Request Protocol: </B>" + request.getprotocol() + "<BR><BR>\n" + 7 Making a Table of All Request Headers (Continued) "<TABLE BORDER=1 ALIGN=\"CENTER\">\n" + "<TR BGCOLOR=\"#FFAD00\">\n" + "<TH>Header Name<TH>Header Value"); Enumeration headernames = request.getheadernames(); while(headernames.hasmoreelements()) { String headername = (String)headerNames.nextElement(); out.println("<tr><td>" + headername); out.println(" <TD>"+request.getHeader(headerName)); out.println("</table>\n</body></html>"); /** Since this servlet is for debugging, have it * handle GET and POST identically. */ 8 public void dopost(httpservletrequest request, HttpServletResponse response) throws ServletException, IOException { doget(request, response);

Making a Table of All Request Headers (Result 1) 9 Making a Table of All Request Headers (Result 2) 10

11 Common HTTP 1.1 Request Headers Accept Indicates MIME types browser can handle Can send different content to different clients. For example, PNG files have good compression characteristics but are not widely supported in browsers. A servlet could check to see if PNG is supported, sending <IMG SRC="picture.png"...> if it is supported, and <IMG SRC="picture.gif"...> if not. Warning: IE incorrectly sets this header when you hit the Refresh button. It sets it correctly on original request. Accept-Encoding Indicates encodings (e.g., gzipor compress) browser can handle. See following example Common HTTP 1.1 Request Headers (Continued) Authorization User identification for password-protected pages. See upcoming example. Instead of HTTP authorization, use HTML forms to send username/password and store info in session object. This approach is usually preferable because standard HTTP authorization results in a small, terse dialog box that is unfamiliar to many users. Servers have high-level way to set up password-protected pages without explicit programming in the servlets. For details, see Chapter 7 (Declarative Security) and Chapter 8 (Programmatic Security) of More Servlets and JavaServer Pages 12

Common HTTP 1.1 Request Headers (Continued) Connection In HTTP 1.0, keep-alive means browser can handle persistent connection. In HTTP 1.1, persistent connection is default. Persistent connections mean that the server can reuse the same socket over again for requests very close together from the same client (e.g., the images associated with a page, or cells within a framed page). Servlets can't do this unilaterally; the best they can do is to give the server enough info to permit persistent connections. So, they should set Content-Length with setcontentlength (using ByteArrayOutputStream to determine length of output). Cookie Gives cookies previously sent to client. Use getcookies, not getheader. See chapter 8. 13 Common HTTP 1.1 Request Headers (Continued) Host Indicates host given in original URL This is a required header in HTTP 1.1. This fact is important to know if you write a custom HTTP client (e.g., WebClient used in book) or telnet to a server and use the HTTP/1.1 version. If-Modified-Since Indicates client wants page only if it has been changed after specified date Don t handle this situation directly; implement getlastmodified instead. See lottery-number example in book (Chapter 3). 14

15 Common HTTP 1.1 Request Headers (Continued) Referer URL of referring Web page Useful for tracking traffic; logged by many servers Can also be used to let users set preferences and then return to the page they came from Can be easily spoofed; don't let this header be sole means of deciding how much to pay sites that show your banner ads. Some browsers (Opera), ad filters (Web Washer), and personal firewalls (Norton) screen out this header See example in book User-Agent Best used for identifying category of client Web browser vs. I-mode cell phone, etc. For Web applications, use other headers if possible Again, can be easily spoofed See following example Sending Compressed Web Pages Dilbert used with permission of United Syndicates Inc. 16

Sending Compressed Pages: GzipUtilities.java public class GzipUtilities { public static boolean isgzipsupported (HttpServletRequest request) { String encodings = request.getheader("accept-encoding"); return((encodings!= null) && (encodings.indexof("gzip")!= -1)); public static boolean isgzipdisabled (HttpServletRequest request) { String flag = request.getparameter("disablegzip"); return((flag!= null)&& (!flag.equalsignorecase("false"))); 17 public static PrintWriter getgzipwriter (HttpServletResponse response) throws IOException { return(new PrintWriter (new GZIPOutputStream (response.getoutputstream()))); Sending Compressed Pages: LongServlet.java public class LongServlet extends HttpServlet { public void doget(httpservletrequest request, HttpServletResponse response) throws ServletException, IOException { response.setcontenttype("text/html"); // Change the definition of "out" depending on // whether or not gzip is supported. PrintWriter out; if (GzipUtilities.isGzipSupported(request) &&!GzipUtilities.isGzipDisabled(request)) { out = GzipUtilities.getGzipWriter(response); response.setheader("content-encoding", "gzip"); else { out = response.getwriter(); 18

Sending Compressed Pages: LongServlet.java (Continued) out.println (doctype + "<HTML>\n" + "<HEAD><TITLE>" + title + "</TITLE></HEAD>\n" + "<BODY BGCOLOR=\"#FDF5E6\">\n" + "<H1 ALIGN=\"CENTER\">" + title + "</H1>\n"); String line = "Blah, blah, blah, blah, blah. " + "Yadda, yadda, yadda, yadda."; for(int i=0; i<10000; i++) { out.println(line); out.println("</body></html>"); out.close(); 19 Sending Compressed Pages: Results Uncompressed (28.8K modem), Netscape and Internet Explorer: > 50 seconds Compressed (28.8K modem), Netscape and Internet Explorer: < 5 seconds Caution: be careful about generalizing benchmarks 20

Differentiating Among Different Browser Types Use User-Agent only when necessary. Otherwise, you will have difficult-to-maintain code that consists of tables of browser versions and associated capabilities. Check for null. The header is not required by the HTTP 1.1 specification, some browsers let you disable it (e.g., Opera), and custom clients (e.g., Web spiders or link verifiers) might not use the header at all. To differentiate between Netscape and Internet Explorer, check for MSIE, not Mozilla. Both Netscape and Internet Explorer say Mozilla at the beginning of the header. For JavaScript compatability. Note that the header can be faked. If a client fakes this header, the servlet cannot tell the difference. 21 22 Differentiating Among Different Browser Types (Code) public class BrowserInsult extends HttpServlet { public void doget(httpservletrequest request, HttpServletResponse response) throws ServletException, IOException { response.setcontenttype("text/html"); PrintWriter out = response.getwriter(); String title, message; // Assume for simplicity that Netscape and IE are // the only two browsers. String useragent = request.getheader("user-agent"); if ((useragent!= null) && (useragent.indexof("msie")!= -1)) { title = "Microsoft Minion"; message = "Welcome, O spineless slave to the " + "mighty empire."; else { title = "Hopeless Netscape Rebel"; message = "Enjoy it while you can. " + "You <I>will</I> be assimilated!";

Differentiating Among Browser Types (Result) 23 Summary 24 Many servlet tasks can only be accomplished by making use of HTTP headers coming from the browser Use request.getheader for arbitrary header Remember to check for null Cookies, authorization info, content length, and content type have shortcut methods Most important headers you read directly Accept Accept-Encoding Connection Referer User-Agent