Documente Academic
Documente Profesional
Documente Cultură
Order
A Typical Restaurant
Places order
Client
Serves
Waiter
Chef
19
Places order
HTTP request
Web Server receives request (Waiter) Servlets act as Chefs Dish Ready
Servlets-defined
Java servlet is a server side application written in java language. It dynamically generated HTML pages. Java virtual machine and package javax.servlet is needed to run java servlet.
21
Advantages of Servlets
Advantages Loaded in the same process space as the web server More secure and almost crash proof,no bufferoverflow
Inexpensive
Servlets Introduction
A servlet is a Java class used to extend the capabilities of servers that host applications accessed via a requestresponse programming model
Other Applications
23
Servlets Introduction
Servlets are not tied to a specific client-server protocol but they are most commonly used with HTTP Typical uses for HTTP Servlets include:
Read explicit data sent by client (form data) Read implicit data sent by client (request headers) Generate the results Send the explicit data back to client (HTML) Send the implicit data to client (status codes and response headers) Managing state information on top of the stateless HTTP
24
Servlet Engine
A servlet engine provides the runtime environment in which a servlet executes The servlet engine manages the life-cycle of servlets from when they are first created through to their imminient destruction The servlet engine executes within a Java Virtual Machine Servlet engines come in two flavours: Stand -alone and Add-on A standalone servlet engine is a fully functioning web server with support for servlets. For example WebSphere, Java Web Server and Iplanet An add-on servlet engine is a plug-in that can be added to a web server to give it the servlet support it was probably never designed to have. For example ServletExec and Tomcat
25
26
27
28
HttpServlet
Servlet
29
30
HTTP Servlet
The general rules to be followed while writing a HTTP Servlet: Extend HttpServlet class, which implements the Servlet interface Must call super.init(config) in the servlets init() method, in order to store configuration information provided by the servlet container, to be accessible in the servlet for later use. This super call saves the ServletConfig object, which would not be available otherwise. Override doGet() - to handle GET requests. Override doPost() method to handle POST requests. Within the doGet/Post method, user's request is represented by an HttpServletRequest object and response to the user is represented by an HttpServletResponse object. The response can be written to the user through PrintWriter object obtained from the HttpServletResponse object.
31
HTTP Servlet
doGet() Called by the server (via the service method) to allow a servlet handle a GET request Parameters are passed to the doGet() method through the URL There is a limitation of data (say 255 characters) that can be sent through GET method
doPost() Called by the server (via the service method) to allow a servlet to handle a POST request. The request body contains the parameters and values POST method doesnt have limitation on the amount of data being sent through.
32
public class NewServlet extends HttpServlet { protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try { } finally { out.close(); } } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); try { out.println("<HTML><HEAD><TITLE>Hello Client!</TITLE>"+ "</HEAD><BODY>Hello My First java Client!</BODY></HTML>"); out.close(); } finally { out.close(); } }
33
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } public String getServletInfo() { return "Short description"; } }
34
35
Request
Request object encapsulates all information from the client request Request parameters are strings sent by the client to a servlet container as part of a request When the request is a HttpServletRequest, the attributes are populated from the URI query string or possibly posted form data Parameters are stored by the servlet container as a set of namevalue pairs The following methods of the ServletRequest interface are available to access parameters:
getParameter getParameterNames getParameterValues
A servlet can access the headers of an HTTP request through the following methods of the HttpServletRequest interface:
getHeader getHeaders getHeaderNames
Request object can have attributes associated with it. Attributes may be set by a servlet to communicate information to another servlet Attributes are accessed with the methods of the ServletRequest interface:
getAttribute getAttributeNames setAttribute
36
Request
RequestSample.html
<html> <head> <META HTTP-EQUIV="Content-Type" CONTENT="text/html; "> <title>Data Entry Page</title> </head> <body> <form method="post" action="FormHandlerServlet"> <table cellpadding="0" cellspacing="0" border="0"> <tr> <td>Please enter your name:</td> <td><input type="text" name="enteredValue" /> </td> </tr> <tr> <td><input name="options" type="checkbox" value=" graduate " /> graduate </td> </tr> <tr> <td><input name="options" type="checkbox" value=" post-graduate " /> post-graduate</td> </tr> <tr> <td><input name="options" type="checkbox" value=" doctrate " /> doctrate </td> </tr> <tr> <td></td> <td><input type="submit" value="Submit"> </td> </tr> </table> </form></body></html>
37
Request:FormHandlerServlet.java
import javax.servlet.*;
import javax.servlet.http.*; import java.io.*; public class RequestSample extends HttpServlet { public void doGet(HttpServletRequest objRequest, HttpServletResponse objResponse) throws IOException, ServletException { doPost(objRequest, objResponse);
38
public void doPost(HttpServletRequest Request, HttpServletResponse Response) throws IOException, ServletException { objResponse.setContentType("text/html"); PrintWriter out = Response.getWriter(); String enteredValue; // gets all the selected options from the client browser String[] selectedOptions = request.getParameterValues("options"); // gets the enteredValue fields value enteredValue = request.getParameter("enteredValue"); PrintWriter printWriter; try { // get a printwriter from the HttpServletResponse objects ref. printWriter = response.getWriter();
39
// return on the HttpServletResponse objects ref. requested values printWriter.println("<p>"); printWriter.print("You entered: "); printWriter.print(enteredValue); printWriter.print("</p>"); printWriter.println("<p>"); printWriter.print("The following options were selected:"); printWriter.println("<br/>"); if (selectedOptions != null) { for (int i=0;i< selectedOptions.length;i++) { printWriter.print(selectedOptions[i]); printWriter.println("<br/>"); } } else { printWriter.println("None"); } printWriter.println("</p>");
40
Response
Response object encapsulates all information to be returned from the server to the client Information is transmitted from the server to the client either by HTTP headers or the message body of the request in HTTP protocol A servlet can set headers of an HTTP response via the following methods of the HttpServletResponse interface:
setHeader addHeader setHeader method sets a header with a given name and value. If a previous header exists, it is replaced by the new header addHeader method adds a header value to the set of headers with a given name. If there are no headers already associated with the given name, this method will create a new set
41
Response
HttpServletResponse supplies a number of methods for specifying common headers setContentType method Sets the Content-Type header that specifies the MIME type of the document that servlet is going to output Default MIME type for servlets is text/plain, but they usually explicitly specify text/html
Example: response.setContentType("text/html")
MIME (Multi-Purpose Internet Mail Extensions) was originally developed to allow Internet email to contain something other than just simple ASCII characters When a server sends a file to a client application, it specifies the MIME type in the header and the browser either displays it with its built in players or plug-ins addCookie method sets a cookie getWriter/ getOutputStream - Retrieves an output stream to send data to the client To send character data, use the PrintWriter returned by the response's getWriter method To send binary data in a MIME body response, use the ServletOutputStream returned by getOutputStream
42
Response
Sample
ResponseSample.java import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class ResponseSample extends HttpServlet { public void doGet (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { ServletOutputStream out = res.getOutputStream(); res.setContentType("text/html"); out.println("<HEAD><TITLE> ResponseSample Output </TITLE></HEAD><BODY>"); out.println("<h1> ResponseSample Output </h1>"); out.println("<P>This is output from ResponseSample."); out.println("</BODY>"); out.close(); } }
43
Exercise
1. Write a servlet with doGet and doPost methods to process the following html form elements: "Email -TextField "Name TextField Sex -Checkbox "Company-TextField "Street -TextField "City -TextField "State - Dropdown "Zipcode - TextField "Country - TextField "Phone - TextField doGet method handles the initial invocation of the servlet. It responds with a form, that will use the "POST" method to submit data. doPost method responds to the "POST" query from the original form supplied by the doGet() method
44