Sunteți pe pagina 1din 29

Servlets

A Day In A Typical Restaurant


A customer enters the restaurant A Waiter Accept the order and then serves food Bill ----------Then the money is paid

Exit The customer leaves the restaurant

The customer asks for the bill

This system runs smoothly runs with a few customer


17

An example - McDonalds a Chain of Restaurants


Back end Chef He goes to the counter... A customer enters the restaurant Food Counter

Order

Collects the items and leaves

Pays the bill He places the order


18

A Typical Restaurant

The restaurant may need to be expanded Greater Investment Increased cost


This can be a solution but incase customers want to place orders from a remote location, then the web can come to rescue
Passes it

Places order

Client

Serves

Waiter

Sends back the processed order

Chef

19

The Web Based Solution - New way of doing business - Ecommerce

Places order

HTTP request

Web Server receives request (Waiter) Servlets act as Chefs Dish Ready

Information sent back to client as an HTTP response Client Browser

Items are Present


Checks the restaurant database

Requests for Items


20

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

Completely protocol independent

Faster than common scripting languages


22

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

Advantages of using Java Servlets


Efficient: threads instead of OS processes, one servlet copy, persistence Convenient: lots of high level utilities Powerful: talking to server, sharing data, pooling, persistence Portable: run on virtually all operating systems and servers Secure: no buffer overflows Inexpensive: inexpensive plug-ins if servlet support not bundled

26

Basic Servlet architecture


Servlet Life cycle HTTP Servlet

27

Servlet Life Cycle

28

Servlet Life Cycle


GenericServlet
GenericServlet

HttpServlet

Servlet

29

Servlet Life Cycle


init() Marks the beginning of a servlets life Called only when the servlet is first loaded Takes one parameter, ServletConfig which has the servlets startup configuration and initialization parameters Does not return any value service() Executed after the servlets init() method is executed successfully Takes two parameters - HttpServletRequest and HttpServletResponse Does not return any value GenericServlets service() method is abstract HTTPServlet: There are 2 service methods in this class. Public service() method dispatches the request to the protected service() method which in turn sends the request to the doGet() or doPost() methods defined in the class destroy() Marks the end of a servlets life Called only when the servlet is unloadeded Does not return any value

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

import import import import

java.io.*; java.net.*; javax.servlet.*; javax.servlet.http.*;

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

Significant Entities in Servlets technology


Request Response Servletcontext Session & Session Tracking

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>");

} catch (IOException e) { e.printStackTrace(); } } }

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

S-ar putea să vă placă și