1 servers a server is a computer that responds to requests from a client – typical requests:...

54
1 Servers •A server is a computer that responds to requests from a client Typical requests: provide a web page, upload or download a file, send email •A server is also the software that responds to these requests; a client could be the browser or other software making these requests Typically, your little computer is the client, and someone else’s big computer is the server However, any computer can be a server It is not unusual to have server software and client software running on the same computer

Upload: amie-webster

Post on 12-Jan-2016

227 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: 1 Servers A server is a computer that responds to requests from a client – Typical requests: provide a web page, upload or download a file, send email

1

Servers

• A server is a computer that responds to requests from a client– Typical requests: provide a web page, upload or download a file, send

email

• A server is also the software that responds to these requests; a client could be the browser or other software making these requests

• Typically, your little computer is the client, and someone else’s big computer is the server– However, any computer can be a server– It is not unusual to have server software and client software running

on the same computer

Page 2: 1 Servers A server is a computer that responds to requests from a client – Typical requests: provide a web page, upload or download a file, send email

2

Apache

• Apache is a very popular server– 66% of the web sites on the Internet use Apache

• Apache is:– Full-featured and extensible– Efficient– Robust– Secure (at least, more secure than other servers)– Up to date with current standards– Open source– Free

Page 3: 1 Servers A server is a computer that responds to requests from a client – Typical requests: provide a web page, upload or download a file, send email

3

Ports• A port is a connection between a server and a client

– Ports are identified by positive integers– A port is a software notion, not a hardware notion, so there may be

very many of them• A service is associated with a specific port

– Typical port numbers:• 21—FTP, File Transfer Protocol• 22—SSH, Secure Shell• 25—SMTP, Simple Mail Transfer Protocol• 53—DNS, Domain Name Service• 80—HTTP, Hypertext Transfer Protocol• 8080—HTTP (used for testing HTTP)• 7648, 7649—CU-SeeMe• 27960—Quake III

These are the ports of most interest to us

Page 4: 1 Servers A server is a computer that responds to requests from a client – Typical requests: provide a web page, upload or download a file, send email

4

CGI Scripts• CGI stands for “Common Gateway Interface”

Client sends a request to server

Server starts a CGI script

Script computes a result for server and quits

Another client sends a request

client server

clientscript

Server starts the CGI script again

Etc.

scriptServer returns response to client

script

Page 5: 1 Servers A server is a computer that responds to requests from a client – Typical requests: provide a web page, upload or download a file, send email

5

Servlets vs. CGI scripts• Advantages:– Running a servlet doesn’t require creating a separate

process each time– A servlet stays in memory, so it doesn’t have to be

reloaded each time– There is only one instance handling multiple

requests, not a separate instance for every request– Untrusted servlets can be run in a “sandbox”

• Disadvantage:– Servlets must be in Java (CGI scripts can be in any

language)

Page 6: 1 Servers A server is a computer that responds to requests from a client – Typical requests: provide a web page, upload or download a file, send email

6

Tomcat• Tomcat is the Servlet Engine than handles servlet requests

for Apache– Tomcat is a “helper application” for Apache– It’s best to think of Tomcat as a “servlet container”

• Apache can handle many types of web services– Apache can be installed without Tomcat– Tomcat can be installed without Apache

• It’s easier to install Tomcat standalone than as part of Apache– By itself, Tomcat can handle web pages, servlets, and JSP

• Apache and Tomcat are open source (and therefore free)

Page 7: 1 Servers A server is a computer that responds to requests from a client – Typical requests: provide a web page, upload or download a file, send email

Servlets• Servlets are Java technology’s answer to Common Gateway Interface (CGI)

programming. They are programs that run on a Web server, acting as a middle layer between a request coming from a Web browser or other HTTP client and databases or applications on the HTTP server

• Servlets are small programs that execute on the server side of a Web connection. Just as applets dynamically extend the functionality of a Web browser, servlets dynamically extend the functionality of a Web server

Servlets can respond to any type of request, they are commonly used to extend the applications hosted by Web servers.

For such applications, Java Servlet technology defines HTTP protocol

HTTP protocol is stateless protocol

Page 8: 1 Servers A server is a computer that responds to requests from a client – Typical requests: provide a web page, upload or download a file, send email

• Servlet-api-jar contins the classes and interfaces that are needed to build servelets.

• The javax.servlet and javax.servlet.http packages provide interfaces and classes for writing servlets. These packages ARE not part of the core java , these provided by the tomcat.

• All servlets must implement the Servlet interface, which defines life-cycle methods

• When implementing a generic service, you can use or extend the GenericServlet class provided with the Java Servlet API. The HttpServlet class provides methods, such as doGet and doPost, for handling HTTP-specific services.

Page 9: 1 Servers A server is a computer that responds to requests from a client – Typical requests: provide a web page, upload or download a file, send email

Main function of servelet• Consider a request for a static Web page. A user enters a

Uniform Resource Locator (URL) into a browser. The browser generates an HTTP request to the appropriate Web server.

• The Web server maps this request to a specific file. That file is returned in an HTTP

• response to the browser. The HTTP header in the response indicates the type of the content.

• The Multipurpose Internet Mail Extensions (MIME) are used for this purpose.

• The Hypertext Markup Language (HTML) source code of a Web page has a MIME type of text/html.

Page 10: 1 Servers A server is a computer that responds to requests from a client – Typical requests: provide a web page, upload or download a file, send email

MIME types

• application/*• audio/*• image/*– image/jpeg– image/tiff

• text/*– text/xml– text/rtf– text/html– text/plain

• video/*– video/quicktime– video/mpeg– video/x-msvideo

Page 11: 1 Servers A server is a computer that responds to requests from a client – Typical requests: provide a web page, upload or download a file, send email

Disadvantages of CGI• In the early days of the Web, a server could dynamically

construct a page by creating a separate process to handle each client request. The process would open connections to one or more databases in order to obtain the necessary information. It communicated with the Web server via an interface known as the Common Gateway Interface (CGI).

• CGI allowed the separate process to read data from the HTTP request and write data to the HTTP response. A variety of different languages were used to build CGI programs. These included C, C++, and Perl.

Page 12: 1 Servers A server is a computer that responds to requests from a client – Typical requests: provide a web page, upload or download a file, send email

• CGI suffered serious performance problems. It was expensive in terms of processor and memory resources to create a separate process for each client request.

• It was also expensive to open and close database connections for each client request.

• The CGI programs were not platform-independent.

• ADV . Java Servlets Instead of CGI : Efficient, Convenient, Powerful, Portable, Secure,

Inexpensive

Page 13: 1 Servers A server is a computer that responds to requests from a client – Typical requests: provide a web page, upload or download a file, send email

13

What does a servlet do?1. Read any data sent by the user2. Look up any information about the request

that is embedded in the HTTP request3. Generate the results4. Format the results inside a document5. Set the appropriate HTTP parameters6. Send the document back to the client

From: Core Servlets and JavaServerPages, by Marty Hall

Page 14: 1 Servers A server is a computer that responds to requests from a client – Typical requests: provide a web page, upload or download a file, send email

Servlet Jobs• Read any data sent by the user.This data is usually entered in a form on a Web page, but could also

come from a Java applet or a custom HTTP client program.• Look up any other information about the request that is

embedded in the HTTP request.This information includes details about browser capabilities,cookies, the host name of the requesting client, and so forth.

• Generate the results.This process may require talking to a database, executing anRMI or CORBA call, invoking a legacy application, or computingthe response directly.

Page 15: 1 Servers A server is a computer that responds to requests from a client – Typical requests: provide a web page, upload or download a file, send email

Cont..• Format the results inside a document.In most cases, this involves embedding the information inside an HTML page.

• Set the appropriate HTTP response parameters.This means telling the browser what type of document is being

returned (e.g., HTML), setting cookies and caching parameters, and other such tasks.

• Send the document back to the client.This document may be sent in text format (HTML), binary format (GIF images), or

even in a compressed format like gzip that is layered on top of some other underlying format.

Page 16: 1 Servers A server is a computer that responds to requests from a client – Typical requests: provide a web page, upload or download a file, send email

Advantages of Servlets

1.performance is significantly better Servlets execute within the address space of a Web server It is not necessary to create a separate process to handle each client request.

2.Servlets are platform-independent because they are written in Java. A number of Web servers from different vendors offer the Servlet API. Programs developed for this API can be moved to any of these environments without recompilation.

Page 17: 1 Servers A server is a computer that responds to requests from a client – Typical requests: provide a web page, upload or download a file, send email

3. The Java security manager on the server enforces a set of restrictions to protect the resources on a server mechine. You will see that some servlets are trusted and others are untrusted.

4. the full functionality of the Java class libraries is available to a servlet. It can communicate with applets, databases, or other software via the sockets and RMI mechanisms

Page 18: 1 Servers A server is a computer that responds to requests from a client – Typical requests: provide a web page, upload or download a file, send email

18

Important servlet methods, I• When a servlet is first started up, its init(ServletConfig config)

method is called – init should perform any necessary initializations– init is called only once, and does not need to be thread-safe

• Every servlet request results in a call toservice(ServletRequest request, ServletResponse response)– service calls another method depending on the type of service requested– Usually you would override the called methods of interest, not service

itself– service handles multiple simultaneous requests, so it and the methods it

calls must be thread safe• When the servlet is shut down, destroy() is called

– destroy is called only once, but must be thread safe (because other threads may still be running)

Page 19: 1 Servers A server is a computer that responds to requests from a client – Typical requests: provide a web page, upload or download a file, send email

19

HTTP requests• When a request is submitted from a Web page, it is almost

always a GET or a POST request• The HTTP <form> tag has an attribute action, whose

value can be "get" or "post"• The "get" action results in the form information being put

after a ? in the URL– Example:

http://www.google.com/search?hl=en&ie=UTF-8&oe=UTF-8&q=servlets

– The & separates the various parameters– Only a limited amount of information can be sent this way

• "post" can send large amounts of information– The information is in the body of the HTTP request

Page 20: 1 Servers A server is a computer that responds to requests from a client – Typical requests: provide a web page, upload or download a file, send email

20

Important servlet methods, II• The service method dispatches (sends to another method) the following kinds

of requests: DELETE, GET, HEAD, OPTIONS, POST, PUT, and TRACE– A GET request is dispatched to

doGet(HttpServletRequest request, HttpServletResponse response)– A POST request is dispatched to

doPost(HttpServletRequest request, HttpServletResponse response)– These are the two methods you will usually override

• Regardless of whether the client sends a GET or a POST request, the information it sends is in the HttpServletRequest parameter– doGet and doPost typically do the same thing, so usually you do the real work in

one, and have the other just call it– public void doGet(HttpServletRequest request,

HttpServletResponse response) { doPost(request, response);}

Page 21: 1 Servers A server is a computer that responds to requests from a client – Typical requests: provide a web page, upload or download a file, send email

21

Less important requests• HEAD

– Asks for only the header part of what a GET would return• TRACE

– Asks to send the received request message back (for debugging)• PUT

– Says to put the body at the requested URL• DELETE

– Says to delete the resource or file at the requested URL• OPTIONS

– Asks for a list of the HTTP methods to which the thing at the requested URL can respond

• CONNECT– Says to connect for purposes of tunneling

• Each of these (except CONNECT) an associated doXXX method

Page 22: 1 Servers A server is a computer that responds to requests from a client – Typical requests: provide a web page, upload or download a file, send email

Free Servlet and JSP Engines• Apache Tomcat

http://jakarta.apache.org/tomcat/ See http://archive.coreservlets.com/Using-Tomcat.html

• Allaire/Macromedia JRun http://www.allaire.com/products/jrun/

• New Atlanta ServletExec http://www.servletexec.com/

• Gefion Software LiteWebServer http://www.gefionsoftware.com/LiteWebServer/

• Caucho's Resin http://www.caucho.com/

Page 23: 1 Servers A server is a computer that responds to requests from a client – Typical requests: provide a web page, upload or download a file, send email

Life Cycle of a Servlet• Three methods are central to the life cycle of a servlet.

init( ), service( ), and destroy( )

• They are implemented by every servlet and are invoked at specific times by the server

Page 24: 1 Servers A server is a computer that responds to requests from a client – Typical requests: provide a web page, upload or download a file, send email

Working of life cycle

1. a user enters a Uniform Resource Locator (URL) to a Web browser. The browser then generates an HTTP request for this URL. This request is then sent to the appropriate server.

2. This HTTP request is received by the Web server. The server maps this request to a particular servlet. The servlet is dynamically retrieved and loaded into the address space of the server.

3. The server invokes the init( ) method of the servlet. This method is invoked only when the servlet is first loaded into memory. It is possible to pass initialization parameters to the servlet so it may configure itself.

Page 25: 1 Servers A server is a computer that responds to requests from a client – Typical requests: provide a web page, upload or download a file, send email

4. the server invokes the service( ) method of the servlet. This method is called to process the HTTP request. You will see that it is possible for the servlet to read data that has been provided in the HTTP request. It may also formulate an HTTP response for the client.

• The servlet remains in the server’s address space and is available to process any other HTTP requests received from clients. The service( ) method is called for each HTTP request.

• 5. The server may decide to unload the servlet from its memory. The algorithms by which this determination is made are specific to each server. The server calls the destroy( ) method to relinquish any resources such as file handles that are allocated for the servlet. Important data may be saved to a persistent store. The memory allocated for the servlet and its objects can then be garbage collected.

Page 26: 1 Servers A server is a computer that responds to requests from a client – Typical requests: provide a web page, upload or download a file, send email

Compiling and invoking servlets

• Set your class path Servlet JAR file (e .g ., install_dir/lib/servlet.jar)Top your package hierarchy

• Put your servlet classes in proper locationLocation vary from server to server

• tomcat_install_dir/webapps/ROOT/WEB-INF/classes See http://archive.coreservlets.com/Using-Tomcat.html• jrun_install_dir/servers/default/default-app/WEB_INF/Classes

• Invoke your servletshttp://host/servlet/ServletNameCustom URL – to – servlet mapping (via – web.xml)

Page 27: 1 Servers A server is a computer that responds to requests from a client – Typical requests: provide a web page, upload or download a file, send email

Compilation

• javac HelloServlet.java -classpath "C:\Program Files\Apache Tomcat 4.0 \common\ lib\ servlet.jar"

Page 28: 1 Servers A server is a computer that responds to requests from a client – Typical requests: provide a web page, upload or download a file, send email

Differnce • HttpServlet is a protocol dependent whereas GenericServlet is

protocol independent• Generic Servlet:- A GenericServlet has a service() method to handle

requests. It is protocol independent.

Http Servlet:- The HttpServlet extends GenericServlet and adds support for HTTP protocol based methods like doGet(), doPost(), doHead() etc. It is protocol dependent.

• HttpServlet belongs to javax.servlet.http package This is an abstract class which extends GenericServlet and implements java.io.Serializable A subclass of HttpServlet must override at least one method of doGet(), doPost(),doPut(), doDelete(), init(), destroy(), getServletInfo()

Page 29: 1 Servers A server is a computer that responds to requests from a client – Typical requests: provide a web page, upload or download a file, send email

Servlet Iplimentation

The following basic steps are needed for executing the servelets.

1. Create and compile the servlet source code.2. Start Tomcat.

To start Tomcat, select Start Tomcat in the Start | Programs menu, or run startup.bat from the

3. Start a Web browser and request the servlet. http://localhost:8080/examples/servlet/HelloServlet

Page 30: 1 Servers A server is a computer that responds to requests from a client – Typical requests: provide a web page, upload or download a file, send email

HelloServlet.javaimport java.io.*;import javax.servlet.*;public class HelloServlet extends GenericServlet {

public void service(ServletRequest request,ServletResponse response)

throws ServletException, I Exception {response.setContentType("text/html");PrintWriter pw = response.getWriter();pw.println("<B>Hello Word !");pw.close();}

}

Page 31: 1 Servers A server is a computer that responds to requests from a client – Typical requests: provide a web page, upload or download a file, send email

Web.xml

Page 32: 1 Servers A server is a computer that responds to requests from a client – Typical requests: provide a web page, upload or download a file, send email

32

A “Hello World” servlet(from the Tomcat installation documentation)

public class HelloServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String docType = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " + "Transitional//EN\">\n"; out.println(docType + "<HTML>\n" + "<HEAD><TITLE>Hello</TITLE></HEAD>\n" + "<BODY BGCOLOR=\"#FDF5E6\">\n" + "<H1>Hello World</H1>\n" + "</BODY></HTML>"); }} Don’t worry, we’ll take this a little at a time!

Page 33: 1 Servers A server is a computer that responds to requests from a client – Typical requests: provide a web page, upload or download a file, send email

A simple servlet that generates plain textimport java.io.*;import javax.servlet.*;import javax.servlet.http.*;public class SimpleServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); out.println(“Hello world”);}}

Page 34: 1 Servers A server is a computer that responds to requests from a client – Typical requests: provide a web page, upload or download a file, send email

A servlet that generates HTMLpublic class HelloWWW extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType(“text/html”); PrintWriter out = response.getWriter(); String docType = “<! DOCTYPE HTML PUBLIC \ “- // W3C / DTD HTML 4.0 “ + “ Transitional // EN \ “>/n”;out.println(docType + “<HTML>/n”+ “<HEAD><TITLE>Hello WWW</TITLE></HEAD>\n”+ “<BODY> \n”+ “<H1><Hello WWW></H1>\n” + “</BODY></HTML>”);}}

Page 35: 1 Servers A server is a computer that responds to requests from a client – Typical requests: provide a web page, upload or download a file, send email

Servlet API• Two packages contain the classes and interfaces that

are required to build servlets. These are javax.servlet and javax.servlet.http. They constitute the Servlet API.

• These packages are not part of the Java core packages• They are not included in the Java Software

Development Kit. You must download Tomcat to obtain their functionality.

• The Servlet API has been in a process of ongoing development and enhancement.

• The current servlet specification is version is 2.3• The Servlet API is supported by most Web servers,

Page 36: 1 Servers A server is a computer that responds to requests from a client – Typical requests: provide a web page, upload or download a file, send email

The javax.servlet Package

Interfaces• Servlet : Declares life cycle methods for a servlet.• ServletConfig :Allows servlets to get initialization

parameters.• ServletContext : Enables servlets to log events and access

information about their environment.• ServletRequest : Used to read data from a client request.• ServletResponse : Used to write data to a client response.• SingleThreadModel : Indicates that the servlet is thread safe.

Page 37: 1 Servers A server is a computer that responds to requests from a client – Typical requests: provide a web page, upload or download a file, send email

Classes • GenericServlet : Implements the Servlet and ServletConfig

interfaces.• ServletInputStream : Provides an input stream for reading

requests from a client.

• ServletOutputStream : Provides an output stream for writing responses to a client.

• ServletException : Indicates a servlet error occurred.• UnavailableException : Indicates a servlet is unavailable.

Page 38: 1 Servers A server is a computer that responds to requests from a client – Typical requests: provide a web page, upload or download a file, send email

Servlet Interface methods

• All servlets must implement the Servlet interface. It declares the init( ), service( ), and destroy( ) methods that are called by the server during the life cycle of a servlet.

• A method is also provided that allows a servlet to obtain any initialization parameters. The methods defined by Servlet methods.

• void destroy( )Called when the servlet is unloaded.

• ServletConfig getServletConfig( ) : Returns a ServletConfig object that contains any initialization parameters.

String getServletInfo( ) : Returns a string describing the servlet.

Page 39: 1 Servers A server is a computer that responds to requests from a client – Typical requests: provide a web page, upload or download a file, send email

• void service(ServletRequest req,ServletResponse res) throws ServletException,IOException

Called to process a request from a client. The request from the client can be read from req. The response to the client can be written to res. An exception is generated if a servlet or IO problem occurs.

• void init(ServletConfig sc) throws ServletException Called when the servlet is initialized. Initialization parameters for the

servlet can be obtained from sc. An Unavailable Exception should be thrown if the servlet cannot be initialized.

****The getServletConfig( ) method is called by the servlet to obtain initialization parameters. A servlet developer overrides the getServletInfo( ) method to provide a string with useful information (for example, author, version, date, copyright). This method is also invoked by the server.

Page 40: 1 Servers A server is a computer that responds to requests from a client – Typical requests: provide a web page, upload or download a file, send email

ServletContext Interface Methods• The ServletContext interface is implemented by the server. It

enables servlets to obtain information about their environment

• Object getAttribute(String attr) : Returns the value of the server attribute named attr.

• String getMimeType(String file)Returns the MIME type of file.

• String getRealPath(String vpath) Returns the real path that corresponds to the virtual path

vpath.

Page 41: 1 Servers A server is a computer that responds to requests from a client – Typical requests: provide a web page, upload or download a file, send email

• String getServerInfo( )Returns information about the server.

• void log(String s) Writes s to the servlet log.

• void log(String s, Throwable e)Write s and the stack trace for e to the servlet log.

• void setAttribute(String attr, Object val)Sets the attribute specified by attr to the value passed in val.

Page 42: 1 Servers A server is a computer that responds to requests from a client – Typical requests: provide a web page, upload or download a file, send email

ServletRequest Interface methods

• Object getAttribute(String attr)• String getCharacterEncoding( )• int getContentLength( )• String getContentType( )• ServletInputStream getInputStream( ) throws

IOException• String getParameter(String pname)• Enumeration getParameterNames( )• String[ ] getParameterValues(String name )• String getProtocol( )• BufferedReader getReader( ) throws IOException

Page 43: 1 Servers A server is a computer that responds to requests from a client – Typical requests: provide a web page, upload or download a file, send email

Cont ..

• String getRemoteAddr( )• String getRemoteHost( )• String getScheme( )• String getServerName( )• int getServerPort( )

Page 44: 1 Servers A server is a computer that responds to requests from a client – Typical requests: provide a web page, upload or download a file, send email

ServletResponse Interface Methods• The ServletResponse interface is implemented by the

server. It enables a servlet to formulate a response for a client.

• String getCharacterEncoding( )• ServletOutputStream getOutputStream( ) throws

IOException• PrintWriter getWriter( ) throws IOException• void setContentLength(int size)• void setContentType(String type)

Page 45: 1 Servers A server is a computer that responds to requests from a client – Typical requests: provide a web page, upload or download a file, send email

Reading Servlet Parameters

• The ServletRequest class includes methods that allow you to read the names and values of parameters that are included in a client request

– EXAMPLE

• The example contains two files. A Web page is defined in• PostParameters.htm and a servlet is defined in

PostParametersServlet.java.

• It defines a table that contains two labels and two text fields. One of the labels is Employee and the other is Phone.

Page 46: 1 Servers A server is a computer that responds to requests from a client – Typical requests: provide a web page, upload or download a file, send email

<html><body><center><form name="Form1"method="post"action="http://localhost:8080/examples/servlet/PostParametersServlet"><table><tr><td><B>Employee</td><td><input type=textbox name="e" size="25" value=""></td></tr><tr><td><B>Phone</td><td><input type=textbox name="p" size="25" value=""></td></tr></table><input type=submit value="Submit"></body></html>The source code for PostParametersServlet.

Page 47: 1 Servers A server is a computer that responds to requests from a client – Typical requests: provide a web page, upload or download a file, send email

import java.io.*;import java.util.*;import javax.servlet.*;public class PostParametersServlet extends GenericServlet {public void service(ServletRequest request, ServletResponse response)throws ServletException, IOException {// Get print writer.

PrintWriter pw = response.getWriter();// Get enumeration of parameter names.

Enumeration e = request.getParameterNames();// Display parameter names and values.

while(e.hasMoreElements()) {String pname = (String)e.nextElement();pw.print(pname + " = ");String pvalue = request.getParameter(pname);pw.println(pvalue);

}pw.close();

}}

Page 48: 1 Servers A server is a computer that responds to requests from a client – Typical requests: provide a web page, upload or download a file, send email

• Compile the servlet and perform these steps to test this example:

• 1. Start Tomcat (if it is not already running).• 2. Display the Web page in a browser.• 3. Enter an employee name and phone number

in the text fields.• 4. Submit the Web page.• After following these steps, the browser will

display a response that is dynamically generated by the servlet.

Page 49: 1 Servers A server is a computer that responds to requests from a client – Typical requests: provide a web page, upload or download a file, send email
Page 50: 1 Servers A server is a computer that responds to requests from a client – Typical requests: provide a web page, upload or download a file, send email
Page 51: 1 Servers A server is a computer that responds to requests from a client – Typical requests: provide a web page, upload or download a file, send email

Web App with Servlets

HEADERS

BODY

Servlet

doGet()……

GET …

Servlet Container

Page 52: 1 Servers A server is a computer that responds to requests from a client – Typical requests: provide a web page, upload or download a file, send email

52

The superclass• public class HelloServlet extends

HttpServlet {

• Every class must extend GenericServlet or a subclass of GenericServlet– GenericServlet is “protocol independent,” so you could

write a servlet to process any protocol– In practice, you almost always want to respond to an HTTP

request, so you extend HttpServlet

• A subclass of HttpServlet must override at least one method, usually one doGet, doPost, doPut, doDelete, init and destroy, or getServletInfo

Page 53: 1 Servers A server is a computer that responds to requests from a client – Typical requests: provide a web page, upload or download a file, send email

5 Simple Steps for Java Servlets

1. Subclass off HttpServlet2. Override doGet(....) method3. HttpServletRequest– getParameter("paramName")

4. HttpServletResponse– set Content Type– get PrintWriter– send text to client via PrintWriter

5. Don't use instance variables

Page 54: 1 Servers A server is a computer that responds to requests from a client – Typical requests: provide a web page, upload or download a file, send email

HTTP Server Response Codes• 200 OK• 3XX -- Minor Client Error

– 301 -- File Moved Permanently– 302 -- Moved Temporarily– 304 -- Not Modified

• 4XX -- Major Client Error– 400 -- Syntax Error– 401 -- Unauthorized– 403 -- Forbidden, Permission Denied– 404 -- Not Found!

• 5XX -- Server Errors– 500 -- Internal Server Error– 503 -- Service Unavailable