1 CS6320 – Servlet Request and Response L. Grewe.

Slides:



Advertisements
Similar presentations
 2002 Prentice Hall. All rights reserved. Chapter 9: Servlets Outline 9.1 Introduction 9.2 Servlet Overview and Architecture Interface Servlet and.
Advertisements

Server Side Programming Common Gateway Interface (CGI): Scripts generate Web pages or other files dynamically by processing form data and returning documents.
HTTP Requests & Responses1 Servlets: HTTP Request Header Contents and Responses.
J.Sant Servlets Joseph Sant Sheridan Institute of Technology.
HTTP HyperText Transfer Protocol. HTTP Uses TCP as its underlying transport protocol Uses port 80 Stateless protocol (i.e. HTTP Server maintains no information.
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.
An introduction to Java Servlet Programming
CS320 Web and Internet Programming Handling HTTP Requests Chengyu Sun California State University, Los Angeles.
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.
Core Servlets chapter 5: HTTP request headers. Requesting header information It is possible that information the servlet needs is not in the form data.
1 Servlets Part 1 Representation and Management of Data on the Web.
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.
1 Servlets Representation and Management of Data on the Web.
June 1, 2000 Object Oriented Programming in Java (95-707) Advanced Topics 1 Lecture 10 Object Oriented Programming in Java Advanced Topics Servlets.
1 Web Search Interfaces. 2 Web Search Interface Web search engines of course need a web-based interface. Search page must accept a query string and submit.
1 Handling the Client Request: HTTP Request Headers Parts of this presentation was provided by Vijayan Sugumaran Department of DIS.
HTTP Overview Vijayan Sugumaran School of Business Administration Oakland University.
Hypertext Transport Protocol CS Dick Steflik.
Client, Server, HTTP, IP Address, Domain Name. Client-Server Model Client Bob Yahoo Server yahoo.com/finance.html A text file named finance.html.
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.
Definition Servlet: Servlet is a java class which extends the functionality of web server by dynamically generating web pages. Web server: It is a server.
Servlets Written by Dr. Yaron Kanza, Edited by permission from author by Liron Blecher.
Servlets. Our Project 3-tier application Develop our own multi-threaded server Socket level communication.
Gayle J Yaverbaum, PhD Professor of Information Systems Penn State Harrisburg.
Web technologies and programming cse hypermedia and multimedia technology Fanis Tsandilas April 3, 2007.
J2EE training: 1 TODO Replace Netscape examples with Firefox. In later two sections also.
COMP3016 Web Technologies Introduction and Discussion What is the Web?
FTP (File Transfer Protocol) & Telnet
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.
Maryam Elahi University of Calgary – CPSC 441.  HTTP stands for Hypertext Transfer Protocol.  Used to deliver virtually all files and other data (collectively.
Servlets. - Java technology for Common Gateway Interface (CGI) programming. - It is a Java class that dynamically extends the function of a web server.
J2EE training: 1 Course Material Usage Rules PowerPoint slides for use only in full-semester, for-credit courses at degree-granting.
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.
CS320 Web and Internet Programming Handling HTTP Requests Chengyu Sun California State University, Los Angeles.
Servlet Lifecycle Lec 28. Servlet Life Cycle  Initialize  Service  Destroy Time.
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.
1 Servlets Modified slides from Dr.Sagiv. 2 Introduction.
SKT-SSU IT Training Center Servlet and JSP. Chapter Five: Handling the Client Request: HTTP Request Headers.
1 Handling the Client Request: HTTP Request Headers.
20-Nov-15introServlets.ppt Intro to servlets. 20-Nov-15introServlets.ppt typical web page – source Hello Hello.
Introduction to Server-Side Web Development Introduction to Server-Side Web Development Session II: Introduction to Server-Side Web Development with Servlets.
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.
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.
1 Introduction to Servlets. Topics Web Applications and the Java Server. HTTP protocol. Servlets 2.
® IBM Software Group © 2007 IBM Corporation Servlet API (Part II)
Representation and Management of Data on the Web
Advanced Java Session 6 New York University School of Continuing and Professional Studies.
Overview of Servlets and JSP
Server-Side Programming 1cs What is a Servlet A Java application that is being run by a Web server Can receive parameters in an HTTP request Generates.
HTTP protocol Java Servlets. HTTP protocol Web system communicates with end-user via HTTP protocol HTTP protocol methods: GET, POST, HEAD, PUT, OPTIONS,
LURP Details. LURP Lab Details  1.Given a GET … call a proxy CGI script in the same way you would for a normal CGI request  2.This UDP perl.
1 Servlets Sun tutorial to servletstutorial to servlets.
Introduction To HTML Dr. Magdi AMER. HTML elements.
How CGI and Java Servlets are Run By David Stein 14 November 2006.
S ERVLETS Form Data 19-Mar-16. F ORM P ROCESSING You must have come across many situations when you need to pass some information from your browser to.
Simple Web Services. Internet Basics The Internet is based on a communication protocol named TCP (Transmission Control Protocol) TCP allows programs running.
Servlets: HTTP Request Header Contents and Responses
Building Web Apps with Servlets
JDBC & Servlet CSE 4504/6504 Lab.
HTTP request message two types of HTTP messages: request, response
Servlet.
Generating the Server Response: HTTP Status Codes
Servlets: Servlet / Web Browser Communication II
Servlet APIs Every servlet must implement javax.servlet.Servlet interface Most servlets implement the interface by extending one of these classes javax.servlet.GenericServlet.
Servlets: Servlet / Web Browser Communication I
Presentation transcript:

1 CS6320 – Servlet Request and Response L. Grewe

2 Recall Servlet Invocation Servlet operates on Request/Response. Servlet operates on Request/Response. Web Browser service(request,response) MyServlet (HTTP) request (HTTP) response

3 Client Request Data When a user submits a browser request to a web server, it sends two categories of data: When a user submits a browser request to a web server, it sends two categories of data: HTTP Request Header Data: Data that is automatically appended to the HTTP Request from the client.HTTP Request Header Data: Data that is automatically appended to the HTTP Request from the client. For example: cookies, browser type, etc, For example: cookies, browser type, etc, Data: Data sent by client. Example: the user explicitly typed into an HTML form.Data: Data sent by client. Example: the user explicitly typed into an HTML form. i.e.: login and password i.e.: login and password

4 An HTTP Header Request Example GET /default.asp HTTP/1.0 Accept: image/gif, image/x-xbitmap, image/jpeg, image/png, */* Accept-Language: en Connection: Keep-Alive Host: magni.grainger.uiuc.edu User-Agent: Mozilla/4.04 [en] (WinNT; I ;Nav) Cookie: SITESERVER=ID=8dac8e0455f4890da220ada8b76f; ASPSESSIONIDGGQGGGAF=JLKHAEICGAHEPPMJKMLDEM Accept-Charset: iso ,*,utf-8 See also class website module for further examples/information

5 Reading HTTP Request Headers

6 Sample HTTP Request Example of a HTTP Request to Yahoo.com Example of a HTTP Request to Yahoo.com GET / HTTP/1.1 Accept: */* Accept-Language: en-us Accept-Encoding: gzip, deflate User-Agent: Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt) Host: Connection: Keep-Alive Cookie: B=2td79o0sjlf5r&b=2 Tip: Check out:

7 Accessing HTTP Headers To access any of these Headers, the use the HTTPServletRequest getHeader() method. To access any of these Headers, the use the HTTPServletRequest getHeader() method. For example: For example: String connection = req.getHeader(“Connection”);String connection = req.getHeader(“Connection”); To retrieve a list of all the Header Names, use the getHeaderNames() method. To retrieve a list of all the Header Names, use the getHeaderNames() method. getHeaderNames() returns an Enumeration object.getHeaderNames() returns an Enumeration object. For example: For example: Enumeration enum = req.getHeaderNames();Enumeration enum = req.getHeaderNames();

8 Additional HTTP Information getMethod() getMethod() Indicates the request method, e.g. GET or POST.Indicates the request method, e.g. GET or POST. getRequestURI() getRequestURI() Returns the part of the URL that comes after the host and port. For example, for the URL: the request URI would be /servlet/search.Returns the part of the URL that comes after the host and port. For example, for the URL: the request URI would be /servlet/search. getProtocol() getProtocol() Returns the protocol version, e.g. HTTP/1.0 or HTTP/1.1Returns the protocol version, e.g. HTTP/1.0 or HTTP/1.1 Methods for specific request information: getCookies, getContentLength, getContentType, getMethod, getProtocol, etc. See api and class website for more Methods for specific request information: getCookies, getContentLength, getContentType, getMethod, getProtocol, etc. See api and class website for more

9 Example 1 Our first example echoes all of the HTTP Request Information. Our first example echoes all of the HTTP Request Information. First, it outputs: First, it outputs: MethodMethod RequestURIRequestURI Protocol VersionProtocol Version Then, it calls getHeaderNames() to retrieve a list of all HTTP Header Names. Then, it calls getHeaderNames() to retrieve a list of all HTTP Header Names. For each header name, it then calls getHeader() For each header name, it then calls getHeader()

10 package coreservlets; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.util.*; public class ShowRequestHeaders extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String title = "Servlet Example: Showing Request Headers"; out.println(ServletUtilities.headWithTitle(title) + " \n" + " " + title + " \n" + " Request Method: " + request.getMethod() + " \n" + " Request URI: " + request.getRequestURI() + " \n" + " Request Protocol: " + request.getProtocol() + " \n" + " \n" + " Header Name Header Value"); Continued….

11 Enumeration headerNames = request.getHeaderNames(); while(headerNames.hasMoreElements()) { String headerName = (String)headerNames.nextElement(); out.println(" " + headerName); out.println(" " + request.getHeader(headerName)); } out.println(" \n "); } /** Let the same servlet handle both GET and POST. */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); }

12 Reading Browser Types The User-Agent HTTP header indicates the browser and operating system. The User-Agent HTTP header indicates the browser and operating system. For example: For example: user-agent Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)user-agent Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1) You can use this header to differentiate browser types or simply log browser requests. You can use this header to differentiate browser types or simply log browser requests.

13 Example User-Agents Internet Explorer: Internet Explorer: user-agent Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)user-agent Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1) Mozilla Mozilla Mozilla/5.0 (Windows; U; Windows NT 5.1; en- US; rv:1.4) Gecko/ Mozilla/5.0 (Windows; U; Windows NT 5.1; en- US; rv:1.4) Gecko/ For strange historical reasons, IE identifies itself as “Mozilla” For strange historical reasons, IE identifies itself as “Mozilla” To differentiate between the two, use “MSIE”, not “Mozilla”. To differentiate between the two, use “MSIE”, not “Mozilla”.

14 CGI Variables In addition to HTTP Request headers, you can also determine additional information about both the client and the server: In addition to HTTP Request headers, you can also determine additional information about both the client and the server: IP Address of ClientIP Address of Client Host Name of ClientHost Name of Client Server NameServer Name Server PortServer Port Server ProtocolServer Protocol Server SoftwareServer Software

15 Getting Request Data

16 Data from HTML form Using HTML forms, we can pass parameters to Web applications Using HTML forms, we can pass parameters to Web applications … comprises a single form … comprises a single form action: the address of the application to which the form data is sentaction: the address of the application to which the form data is sent method: the HTTP method to use when passing parameters to the application (e.g. get or post )method: the HTTP method to use when passing parameters to the application (e.g. get or post )

17 The Tag Inside a form, INPUT tags define fields for data entry Inside a form, INPUT tags define fields for data entry Standard input types include: buttons, checkboxes, password fields, radio buttons, text fields, image-buttons, text areas, hidden fields, etc. Standard input types include: buttons, checkboxes, password fields, radio buttons, text fields, image-buttons, text areas, hidden fields, etc. They all associate a single (string) value with a named parameter They all associate a single (string) value with a named parameter

18 GET Example <form method="get" action="

19 Getting the Parameter Values To get the value of a parameter named x: To get the value of a parameter named x: req.getParameter(" x ")req.getParameter(" x ") where req is the service request argument If there can be multiple values for the parameter: If there can be multiple values for the parameter: req.getParameterValues(" x ")req.getParameterValues(" x ") To get parameter names: To get parameter names: req.getParameterNames()req.getParameterNames()

20 Example HTML Form that asks users for colors, etc. HTML Form that asks users for colors, etc. Uses these colors to control the response’s background and foreground colors. Uses these colors to control the response’s background and foreground colors.

21 Sending Parameters p{display:table-row} span{display:table-cell; padding:0.2em} Please enter the parameters Background color: Font color: Font size: parameters.html

22 public class SetColors extends HttpServlet { public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String bg = request.getParameter("bgcolor"); String fg = request.getParameter("fgcolor"); String size = request.getParameter("size"); An Example (cont) SetColors.java

23 out.println(" Set Colors Example" +" "); out.println("<body style=\"color:" + fg + ";background-color:" + bg + ";font-size:"+ size + "px\">"); out.println(" Set Colors Example "); out.println(" You requested a background color " + bg + " "); out.println(" You requested a font color " + fg + " "); out.println(" You requested a font size " + size + " "); out.println(" "); } An Example (cont) SetColors.java

24 Servlet Response

25 HTTP Response The response includes: The response includes:  Status line: version, status code, status message  Response headers  Empty line  Content HTTP/ OK Content-Type: text/html Content-Length: 89 Server: Apache-Coyote/1.1 HELLO WORLD Hello World

26 Sample HTTP Response Another example Another example HTTP/ OK Date: Mon, 06 Dec :54:26 GMT Server: Apache/1.3.6 (Unix) Last-Modified: Fri, 04 Oct :06:11 GMT Content-length: 327 Connection: close Content-type: text/html Sample Homepage Sample Homepage Welcome Hi there, this is a simple web page. Granted, it may… Welcome Hi there, this is a simple web page. Granted, it may…

27 Generating Responses Servlets can return any HTTP response they want. Servlets can return any HTTP response they want. Useful for lots of scenarios: Useful for lots of scenarios: Redirecting to another web site.Redirecting to another web site. Restricting access to approved users.Restricting access to approved users. Specifying content-type other than text/html.Specifying content-type other than text/html. Return images instead of HTML.Return images instead of HTML.

28 Setting the Response Status See other class material for details. See other class material for details. Use the following HttpServletResponse methods to set the response status: Use the following HttpServletResponse methods to set the response status: -setStatus(int sc) Use when there is no error, like 201 (created) Use when there is no error, like 201 (created) -sendError(sc), sendError(sc, message) Use in erroneous situations, like 400 (bad request) Use in erroneous situations, like 400 (bad request) The server may return a formatted message The server may return a formatted message -sendRedirect(String location) Redirect to the new location Redirect to the new location

29 Setting the HTTP Status Code Be sure to set the status code before sending any document content to the client. Be sure to set the status code before sending any document content to the client.

30 Using setStatus() setStatus takes an integer value. But, it’s best to use the predefined integers in the HttpServletResponse. Here are a few: setStatus takes an integer value. But, it’s best to use the predefined integers in the HttpServletResponse. Here are a few: SC_BAD_REQUEST SC_BAD_REQUEST SC_BAD_REQUEST Status code (400) indicating the request sent by the client was syntactically incorrect.Status code (400) indicating the request sent by the client was syntactically incorrect. SC_FORBIDDEN SC_FORBIDDEN SC_FORBIDDEN Status code (403) indicating the server understood the request but refused to fulfill it.Status code (403) indicating the server understood the request but refused to fulfill it. SC_INTERNAL_SERVER_ERROR SC_INTERNAL_SERVER_ERROR SC_INTERNAL_SERVER_ERROR Status code (500) indicating an error inside the HTTP server which prevented it from fulfilling the request.Status code (500) indicating an error inside the HTTP server which prevented it from fulfilling the request. SC_NOT_FOUND SC_NOT_FOUND SC_NOT_FOUND Status code (404) indicating that the requested resource is not available.Status code (404) indicating that the requested resource is not available.

31 Sending Redirects You can redirect the browser to a different URL by issuing a Moved Temporarily Status Code: You can redirect the browser to a different URL by issuing a Moved Temporarily Status Code: SC_MOVED_TEMPORARILY: Status code (302) indicating that the resource has temporarily moved to another location.SC_MOVED_TEMPORARILY: Status code (302) indicating that the resource has temporarily moved to another location.SC_MOVED_TEMPORARILY Because this is so common, the HttpServletResponse interface also has a sendRedirect() method. Because this is so common, the HttpServletResponse interface also has a sendRedirect() method. Example:Example: res.sendRedirect( “

32 package coreservlets; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; 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(" } else { response.sendRedirect(" }

33 Setting Response Headers Use the following HTTPServletResponse methods to set the response headers: Use the following HTTPServletResponse methods to set the response headers: -setHeader(String hdr, String value), setIntHeader(String hdr, int value) Override existing header value Override existing header value -addHeader(String hdr, String value), addIntHeader(String hdr, int value) The header is added even if another header with the same name exists The header is added even if another header with the same name exists

34 Specific Response Headers Class HTTPServletResponse provides setters for some specific headers: Class HTTPServletResponse provides setters for some specific headers: -setContentType -setContentLength automatically set if the entire response fits inside the response buffer automatically set if the entire response fits inside the response buffer -setDateHeader -setCharacterEncoding

35 More Header Methods containsHeader(String header)containsHeader(String header) Check existence of a header in the responseCheck existence of a header in the response addCookie(Cookie)addCookie(Cookie) sendRedirect(String url)sendRedirect(String url) automatically sets the Location headerautomatically sets the Location header Do not write into the response after sendError or sendRedirect Do not write into the response after sendError or sendRedirect