Download presentation
Presentation is loading. Please wait.
Published byΝαχώρ Κολιάτσος Modified over 6 years ago
1
Servlets: Servlet / Web Browser Communication II
Ethan Cerami New York University 11/19/2018 Browser/Servlet Communication II
2
Browser/Servlet Communication II
Road Map Recap and Overview Reading HTTP Request Headers Reading Standard CGI Variables Generating the Server Response Case Study 1: Search Engines Case Study 2: Basic Web Security Restricting by User Name/Password 11/19/2018 Browser/Servlet Communication II
3
Browser/Servlet Communication II
Recap and Overview 11/19/2018 Browser/Servlet Communication II
4
Browser/Servlet Communication II
Overview This lecture is the second in two lectures that discuss the interaction between web browsers and servlets. Web Browser Request Web Server Response 11/19/2018 Browser/Servlet Communication II
5
Browser/Servlet Communication II
Client Request Data When a user submits a browser request to a web server, it sends two categories of data: Form Data: Data that the user explicitly typed into an HTML form. For example: registration information. HTTP Request Header Data: Data that is automatically appended to the HTTP Request from the client. For example: cookies, browser type, etc, The last lecture examined Form Data; this lecture examines HTTP Data. 11/19/2018 Browser/Servlet Communication II
6
Reading HTTP Request Headers
11/19/2018 Browser/Servlet Communication II
7
Browser/Servlet Communication II
Sample HTTP Request As a refresher, let’s take a look at a sample 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 11/19/2018 Browser/Servlet Communication II
8
Accessing HTTP Headers
To access any of these Headers, the use the HTTPServletRequest getHeader() method. For example: String connection = req.getHeader(“Connection”); To retrieve a list of all the Header Names, use the getHeaderNames() method. getHeaderNames() returns an Enumeration object. Enumeration enum = req.getHeaderNames(); 11/19/2018 Browser/Servlet Communication II
9
Additional HTTP Information
getMethod() Indicates the request method, e.g. GET or POST. 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. getProtocol() Returns the protocol version, e.g. HTTP/1.0 or HTTP/1.1 11/19/2018 Browser/Servlet Communication II
10
Browser/Servlet Communication II
Example 1 Our first example echoes all of the HTTP Request Information. First, it outputs: Method RequestURI Protocol Version Then, it calls getHeaderNames() to retrieve a list of all HTTP Header Names. For each header name, it then calls getHeader() 11/19/2018 Browser/Servlet Communication II
11
Browser/Servlet Communication II
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) + "<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" + "<TABLE BORDER=1 ALIGN=CENTER>\n" + "<TR BGCOLOR=\"#FFAD00\">\n" + "<TH>Header Name<TH>Header Value"); Continued…. 11/19/2018 Browser/Servlet Communication II
12
Browser/Servlet Communication II
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>"); /** Let the same servlet handle both GET and POST. */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); 11/19/2018 Browser/Servlet Communication II
13
Reading Standard CGI Variables
11/19/2018 Browser/Servlet Communication II
14
Browser/Servlet Communication II
CGI Variables In addition to HTTP Request headers, you can also determine additional information about both the client and the server: IP Address of Client Host Name of Client Server Name Server Port Server Protocol Server Software Additional information is also available (see Chapter 5 for a complete list.) 11/19/2018 Browser/Servlet Communication II
15
Browser/Servlet Communication II
Example 2 Example 2 displays the most important CGI Variables. This is a slightly shorter version of Listing 5.1 from the book. I have modified the code to only show the most important variables. To see all the other CGI variables, see Listing 5.1 on page 120 of our text book. 11/19/2018 Browser/Servlet Communication II
16
Browser/Servlet Communication II
package coreservlets; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.util.*; public class ShowCGIVariables extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String[][] variables = { { "REMOTE_ADDR", request.getRemoteAddr() }, { "REMOTE_HOST", request.getRemoteHost() }, { "SERVER_NAME", request.getServerName() }, { "SERVER_PORT", String.valueOf(request.getServerPort()) }, { "SERVER_PROTOCOL", request.getProtocol() }, { "SERVER_SOFTWARE", getServletContext().getServerInfo() } }; Continued…. 11/19/2018 Browser/Servlet Communication II
17
Browser/Servlet Communication II
String title = "Servlet Example: Showing CGI Variables"; out.println(ServletUtilities.headWithTitle(title) + "<BODY BGCOLOR=\"#FDF5E6\">\n" + "<H1 ALIGN=\"CENTER\">" + title + "</H1>\n" + "<TABLE BORDER=1 ALIGN=\"CENTER\">\n" + "<TR BGCOLOR=\"#FFAD00\">\n" + "<TH>CGI Variable Name<TH>Value"); for(int i=0; i<variables.length; i++) { String varName = variables[i][0]; String varValue = variables[i][1]; if (varValue == null) varValue = "<I>Not specified</I>"; out.println("<TR><TD>" + varName + "<TD>" + varValue); } out.println("</TABLE></BODY></HTML>"); 11/19/2018 Browser/Servlet Communication II
18
Generating the Server Response
11/19/2018 Browser/Servlet Communication II
19
Browser/Servlet Communication II
Sample HTTP Response As a refresher, here’s a sample HTTP response: 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 <title>Sample Homepage</title> <img src="/images/oreilly_mast.gif"> <h1>Welcome</h2>Hi there, this is a simple web page. Granted, it may… 11/19/2018 Browser/Servlet Communication II
20
Browser/Servlet Communication II
Generating Responses Servlets can return any HTTP response they want. Useful for lots of scenarios: Redirecting to another web site. Restricting access to approved users. Return images instead of HTML. 11/19/2018 Browser/Servlet Communication II
21
Setting the HTTP Status Code
Normally, your Servlet will return an HTTP Status code of: 200 OK to indicate that everything went fine. To return a different status code, use the setStatus() method of the HttpServletResponse object. Be sure to set the status code before sending any document content to the client. 11/19/2018 Browser/Servlet Communication II
22
Browser/Servlet Communication II
Using setStatus() setStatus takes an integer value. But, it’s best to use the predefined integers in the HttpServletResponse. Here are a few: SC_BAD_REQUEST Status code (400) indicating the request sent by the client was syntactically incorrect. SC_FORBIDDEN Status code (403) indicating the server understood the request but refused to fulfill it. SC_INTERNAL_SERVER_ERROR Status code (500) indicating an error inside the HTTP server which prevented it from fulfilling the request. SC_NOT_FOUND Status code (404) indicating that the requested resource is not available. 11/19/2018 Browser/Servlet Communication II
23
Browser/Servlet Communication II
Sending Redirects 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. Because this is so common, the HttpServletResponse interface also has a sendRedirect() method. Example: res.sendRedirect( “ 11/19/2018 Browser/Servlet Communication II
24
Case Study 1: Search Engines
11/19/2018 Browser/Servlet Communication II
25
Multiple Search Engines
Our first case study enables users to submit a search query to one of four search engines. Google InfoSeek Lycos HotBot The code exploits the HTTP Response Header to redirect the user to the correct search engine. 11/19/2018 Browser/Servlet Communication II
26
Browser/Servlet Communication II
Architecture SearchEngines Servlet “I want to search for Bill Gates on Google” Web Browser “Go to Google” “I want to search for Bill Gates on Google” Google “Your results…” 11/19/2018 Browser/Servlet Communication II
27
Browser/Servlet Communication II
The Code We are only going to examine the code briefly. We will focus on the HTTP Return Status Code. For an examination of the full code, please see Listing in the Text Book. 11/19/2018 Browser/Servlet Communication II
28
Browser/Servlet Communication II
SearchSpec.java Complete code is available in Listing 6.2 For our purposes, we only need to know about one method: public String makeURL (String searchString, String numResults) You provide this method with a search string and the number of results, and it returns the URL and search query specific to Google, InfoSeek, HotBot, etc. The SearchEngines.java code has an array of these objects: one for Google, one for InfoSeek, etc. 11/19/2018 Browser/Servlet Communication II
29
Get the searchEngine Param Get the Array of SearchSpec Objects
String searchEngine=request.getParameter("searchEngine"); 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; } Iterate through the array, looking for a match. Get the Search URL and Redirect Browser
30
Case Study 2: Basic Web Security
11/19/2018 Browser/Servlet Communication II
31
Browser/Servlet Communication II
HTTP Authentication The HTTP Protocol Includes a built-in authentication mechanism. Useful for protecting web pages or servlets that require user name / password access. First, let’s examine the basic mechanism and the HTTP Headers involved. Then, let’s figure out how to build a servlet that exploits this mechanism. 11/19/2018 Browser/Servlet Communication II
32
Browser/Servlet Communication II
Basic Authentication If a web page is protected, the Web Server will issue an authentication “challenge”: HTTP/ Authorization Required Date: Sun, 27 Aug :51:25 GMT Server: Apache/ (Unix) ApacheJServ/1.1 PHP/4.0.0 mod_ssl/2.6.6 OpenSSL/0.9.5a WWW-Authenticate: BASIC realm="privileged-few" Keep-Alive: timeout=90, max=150 Connection: Keep-Alive Transfer-Encoding: chunked Content-Type: text/html 11/19/2018 Browser/Servlet Communication II
33
Browser/Servlet Communication II
WWW-Authenticate WWW-Authenticate: BASIC realm=“realm" When you issue a return status code of 401, “Authorization Required”, you need to tell the browser what type of authentication is required. You do this via the WWW-Authenticate Header. This header has two parameters: BASIC: Basic authorization requiring user name and password. Realm: you can create multiple “realms” of authentication for different users, e.g. “Admin”, “User”, “Super_User”, etc. 11/19/2018 Browser/Servlet Communication II
34
Basic Authentication Cont.
Upon receiving an authentication challenge, the browser will prompt the user with a pop-up box requesting the user name and password. Browser takes the “username:password” from the user and encrypts it using the Base 64 Encoding Algorithm. For example: if the string is “marty:martypd”, the Base 64 string is “bWFydHk6bWFydHlwdw==” We will not cover the details of Base 64, but remember that Base 64 is easy to decode. Therefore, even if your page is protected, someone can easily intercept your Base 64 string and decode it. 11/19/2018 Browser/Servlet Communication II
35
Basic Authentication Cont.
The browser reissues the request for the page. In the HTTP request, the browser indicates the Authorization string: GET /servlet/coreservlets.ProtectedPage HTTP/1.1 Accept: image/gif, */* Accept-Language: en-us Accept-Encoding: gzip, deflate User-Agent: Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt) Host: Connection: Keep-Alive Authorization: Basic bWFydHk6bWFydHlwdw== 11/19/2018 Browser/Servlet Communication II
36
Basic Authentication Cont.
Web Server checks the user name and password. If User Name/Password is correct, web server displays the protected page. If the User Name/Password is incorrect, web server issues a second authentication challenge. 11/19/2018 Browser/Servlet Communication II
37
Browser/Servlet Communication II
Almost there… Before we examine the actual servlet code, there are two pieces of Java coding we need to examine: sun.misc.BASE64Decoder. java.util.Properties 11/19/2018 Browser/Servlet Communication II
38
Browser/Servlet Communication II
Base 64 Encoding Sun provides a class called: sun.misc.BASE64Decoder. You can use the decodeBuffer() method to decode the Base 64 String sent from the user: String userInfo = “bWFydHk6bWFydHlwdw==” BASE64Decoder decoder = new BASE64Decoder(); String nameAndPassword = new String(decoder.decodeBuffer(userInfo)); After this code, nameAndPassword will be set to “marty:martypd” 11/19/2018 Browser/Servlet Communication II
39
Browser/Servlet Communication II
java.util.Properties A utility class for reading in property files. For example, suppose you have the following password.properties file: #Passwords #Sat Aug 26 11:15:42 EDT 2000 nathan=nathanpw marty=martypw lindsay=lindsaypw bj=bjpw 11/19/2018 Browser/Servlet Communication II
40
Browser/Servlet Communication II
java.util.Properties You can easily and automatically load the password file and parse its contents: passwordFile = "passwords.properties"; passwords = new Properties(); passwords.load(new FileInputStream(passwordFile)); Then, you can extract the password for a specific user name: String password = properties.getProperty ("marty“); 11/19/2018 Browser/Servlet Communication II
41
Browser/Servlet Communication II
ProtectedPage.java Here’s how the Servlet Works: Initialization: Read in a Password file of valid user names and passwords. Check for the HTTP Authorization Header. Decode the Authorization Header using Base 64 to obtain user name and password. Check the User Name and Password against the valid names list. If valid, show protected page. Else, issue another authentication challenge. 11/19/2018 Browser/Servlet Communication II
42
Browser/Servlet Communication II
The Code The Code is too long to examine via Power Point. So, let’s examine the handout. Lines 25-35: Load the Properties File Line 42: Get the Authorization Header Lines 46-53: Decode the user name and password Lines 54-55: Check the user name and password against the valid list. Lines 73-77: Send an authentication challenge. 11/19/2018 Browser/Servlet Communication II
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.