Top Banner
03/26/22 L.MARIA MICHAEL VISUWASAM UNIT-4 1 SERVLET
38
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: 12/1/2015 L.MARIA MICHAEL VISUWASAM UNIT-4 1 SERVLET.

04/18/23L.MARIA MICHAEL

VISUWASAM UNIT-4

1

SERVLET

Page 2: 12/1/2015 L.MARIA MICHAEL VISUWASAM UNIT-4 1 SERVLET.

WHERE ARE WE?

1. Intro toJava, Course

2. Java lang.basics

3. Arrays

5. Encapsulation

4. ObjectClasses 7. Inheritance

8. Polymorphism

10. JDBC

6. ExceptionHandling

Introduction Object-oriented design Advanced topics

Newbie Programmers Developers ProfessionalsDesigners

JAVA

9. Abstract classes and Interfaces

13. Servlets

14. JSP

Server-side coding

12. Networking

11.Streams

Page 3: 12/1/2015 L.MARIA MICHAEL VISUWASAM UNIT-4 1 SERVLET.

OUTLINE

• Concepts• Features• javax.servlet.Servlet• javax.servlet.http.HttpServlet• Example: get and send a page to client• Example: post• Session tracking

• Cookie, HttpSession

• Practical examples

Page 4: 12/1/2015 L.MARIA MICHAEL VISUWASAM UNIT-4 1 SERVLET.

TODAY’S BUZZWORDS

• Applets• Java programs capable of running within a web

browser

• Servlets• Java code running on server side

• Session tracking• Keeping context information during a session of

browsing related web pages

Page 5: 12/1/2015 L.MARIA MICHAEL VISUWASAM UNIT-4 1 SERVLET.

WHAT IS JAVA SERVLET ?

1. A servlet is a small java program that runs within a web server. A servlet is a small java program that runs within a web server. 2. Servlets receive and respond to requests from web clients, usually 2. Servlets receive and respond to requests from web clients, usually across HTTP. across HTTP. 3. Servlet is an opposite of applet as a server-side applet. Applet is an 3. Servlet is an opposite of applet as a server-side applet. Applet is an application running on client while servlet is running on server. application running on client while servlet is running on server.

Client Server

Request

Response

Servlet

Page 6: 12/1/2015 L.MARIA MICHAEL VISUWASAM UNIT-4 1 SERVLET.

WHAT IS JAVA SERVLETS?

• Servlet• module run inside request/response-oriented server

BrowserJava-enabledWeb Server

Servlet DatabaseHTML form

ServerServlet =

BrowserApplet

Servlets are to Servers what Applets are to Browsers

Page 7: 12/1/2015 L.MARIA MICHAEL VISUWASAM UNIT-4 1 SERVLET.

EXAMPLE USE OF SERVLET

• Processing data POST over HTTPs using HTML form as purchase order or credit card data

• Allowing collaborative between people such as on-line conferencing

• Many servlet can chain together among Web servers to reduce load on one Web server.

Page 8: 12/1/2015 L.MARIA MICHAEL VISUWASAM UNIT-4 1 SERVLET.

WHY USE SERVLETS ?

• One of the reasons that Java became popular is Applets.• but there are problems with Applets

• Browser compatibility• Download bandwidth

• Server-side Java• the code is executed on the server side not the client

side• a dynamically loaded module that services requests from

a Web server

Page 9: 12/1/2015 L.MARIA MICHAEL VISUWASAM UNIT-4 1 SERVLET.

SERVLETS (CONTD.)

• vs. Common Gateway Interface (CGI)• create new process for each request

• most platform independent CGI language - Perl• start a new instance of interpreter for every

request• CGI runs in a completely separate process from the

Web server• vs. Server-Side JavaScript

• only available on certain web servers• vs. Active Server Pages (ASP)

• only available on certain web servers

Page 10: 12/1/2015 L.MARIA MICHAEL VISUWASAM UNIT-4 1 SERVLET.

SERVLET COMMUNICATION

Client

HTMLForm

Java-EnabledWeb Server

callServlet

Servlet

• Web browser request servlet by specified URL as http://www.host.com/servlet/servletName

• Web server call service() method in ServletLoader class which will dynamically load a specified servlet name from a special directory call servlet.

Page 11: 12/1/2015 L.MARIA MICHAEL VISUWASAM UNIT-4 1 SERVLET.

SERVLET VS CGI

Servlet run as light weight thread in process.CGI run as heavy weight process.

Page 12: 12/1/2015 L.MARIA MICHAEL VISUWASAM UNIT-4 1 SERVLET.

ADVANTAGE OF SERVLET OVER CGI

• PlatForm Independence

Servlets can run on any platform. PERL also can be moved from platform to platform while CGI such as C are not portable.

• Performance

Servlets only needs be loaded once, while CGI programs needs to be load for every request so that servlet should performs faster than CGI

• Security

While CGI can do many insecure things, java provided security in language level.

Page 13: 12/1/2015 L.MARIA MICHAEL VISUWASAM UNIT-4 1 SERVLET.

SERVLET LIFECYCLE

Server loads Servlets- run init method

Servlets Accept Request fromClients and return Data back

- run service method

Server removes Servlets- run destroy method

No Concurrency IssueServer runs init only once, not per request

service must be thread-safe- multiple service method at a timeif that is impossible, servlet must

implement SingleThreadModel interface

Server reloads Servlets- run init method

destroy must be thread-safe- when server runs destroy, other threads

might be accessing shared resources

Page 14: 12/1/2015 L.MARIA MICHAEL VISUWASAM UNIT-4 1 SERVLET.

METHODS OF THE SERVLET INTERFACE

Method Description

destroy( )Called by the servlet container to indicate to a servlet that the servlet is being taken out of service.

getServletConfig( )Returns a ServletConfig object, which contains initialization and startup parameters for this servlet.

getServletInfo( )Returns information about the servlet, such as author, version, and copyright.

init( )Called by the servlet container to indicate to a servlet that the servlet is being placed into service.

service( )Called by the servlet container to allow the servlet to respond to a request.

Page 15: 12/1/2015 L.MARIA MICHAEL VISUWASAM UNIT-4 1 SERVLET.

SERVLET OVERVIEW AND ARCHITECTURE (CONT.)

• We’ll look at servlets that implement the request-response model between clients and servers using the HTTP protocol. This architecture is shown in the diagram above.

WebBrowser

WebServer

Servlet Servlet

Servlet Container

Database

HTTP request HTTP request

HTTP responseHTTP response

Page 16: 12/1/2015 L.MARIA MICHAEL VISUWASAM UNIT-4 1 SERVLET.

SERVLET OVERVIEW AND ARCHITECTURE (CONT.)

Explanation of the architecture diagram on previous page

• A client application sends an HTTP request to the server.

• The servlet container receives the request and directs it to be processed by the appropriate servlet.

• The servlet does its processing, which may include interacting with a database or other server-side components, such as other servlets or JSPs.

• The servlet returns its results to the client – normally in the form of an HTML, XHTML, or XML document to display in a browser.

Page 17: 12/1/2015 L.MARIA MICHAEL VISUWASAM UNIT-4 1 SERVLET.

SERVLET CLASSES EXAMPLE

Servlet class

GenericServletclass

HttpServletclass

• Interface Servlet Define the standard way in which a network server

will access a servlet. All servlet classes must (fundamentally) implement this interface.

• GenericServlet Defines a generic, protocol-independent servlet. For servlet that is not intended to use with Web server. To write an HTTP servlet for use on the Web, extend HttpServlet instead.

• HttpServletFor Servlet that is intended to use with Web server. This class adds HTTP-specific to work with a Web server context

Page 18: 12/1/2015 L.MARIA MICHAEL VISUWASAM UNIT-4 1 SERVLET.

SERVLET STRUCTURE

•All servlet classes and interfaces that form the API are found in the javax.servlet package.•All servlets, no matter what type of server they are destined to be used with, implement the javax.servlet.Servlet interface. This interface defines the basic functionality that a servlet must possess

Page 19: 12/1/2015 L.MARIA MICHAEL VISUWASAM UNIT-4 1 SERVLET.

SERVLET INTERFACE

• The servlet packages define two abstract classes that implement interface Servlet – class GenericServlet (from the package javax.servlet) and class HttpServlet (from the package javax.servlet.http).

• These classes provide default implementations of some Servlet methods.

• Most servlets extend either GenericServlet or HttpServlet and override some or all of their methods.

• The GenericServlet is a protocol-indpendent servlet, while the HttpServlet uses the HTTP protocol to exchange information between the client and server.

• We’re going to focus exclusively on the HttpServlet used on the Web.

Page 20: 12/1/2015 L.MARIA MICHAEL VISUWASAM UNIT-4 1 SERVLET.

SERVLET INTERFACE (CONT.)

• HttpServlet defines enhanced processing capabilities for services that extend a Web server’s functionality.

• The key method in every servlet is service, which accepts both a ServletRequest object and a ServletResponse object. These object provide access to input and output streams that allow the servlet to read data from and send data to the client.

• If a problem occurs during the execution of a servlet, either ServletExceptions or IOExceptions are thrown to indicate the problem.

Page 21: 12/1/2015 L.MARIA MICHAEL VISUWASAM UNIT-4 1 SERVLET.

HTTPSERVLET CLASS

• Servlets typically extend class HttpServlet, which overrides method service to distinguish between the various requests received from a client web browser.

• The two most common HTTP request types (also known as request methods) are get and post.

• A get request retrieves information from a server. Typically, an HTML document or image.

• A post request sends data to a server. Typically, post requests are used to pass user input to a data-handling process, store or update data on a server, or post a message to a news group or discussion forum.

• Class HttpServlet defines methods doGet and doPost to respond to get and post requests from a client.

Page 22: 12/1/2015 L.MARIA MICHAEL VISUWASAM UNIT-4 1 SERVLET.

HTTPSERVLET CLASS (CONT.)

• Methods doGet and doPost are invoked by method service, which is invoked by the servlet container when a request arrives at the server.

• Method service first determines the request type, the invokes the appropriate method for handling such a request.

• In addition to methods doGet and doPost, the following methods are defined in class HttpServlet:

• doDelete (typically deletes a file from the server)

• doHead (client wants only response headers no entire body)

• doOptions (returns HTTP options supported by server)

• doPut (typically stores a file on the server)

• doTrace (for debugging purposes)

Page 23: 12/1/2015 L.MARIA MICHAEL VISUWASAM UNIT-4 1 SERVLET.

HTTPSERVLETREQUEST INTERFACE

• Every invocation of doGet or doPost for an HttpServlet receives an object that implements interface HttpServletRequest.

• The servlet container creates an HttpServletRequest object and passes it to the servlet’s service method, which in turn, passes it to doGet or doPost.

• This object contains the clients’ request and provides methods that enable the servlet to process the request.

Page 24: 12/1/2015 L.MARIA MICHAEL VISUWASAM UNIT-4 1 SERVLET.

HTTPSERVLETREQUEST METHODS

• Cookie[] getCookies() – returns an array of Cookie objects stored on the client by the server. Cookies are used to uniquely identify clients to the server.

• String getLocalName() – gets the host name on which the request was received.

• String getLocalAddr() – gets the IP address on which the request was received.

• int getLocalPort() – gets the IP port number on which the request was received.

• String getParameter( String name) – gets the value of a parameter set to the servlet as part of a get or post request.

Page 25: 12/1/2015 L.MARIA MICHAEL VISUWASAM UNIT-4 1 SERVLET.

HTTPSERVLETRESPONSE METHODS

• void addCookie (Cookie cookie) – adds a Cookie to the header of the response to the client.

• ServletOutputStream getOutputStream() – gets a byte-based output stream for sending binary data to the client.

• PrintWriter getWriter() – gets a character-based output stream for sending text data (typically HTML formatted text) to the client.

• void SetContentType (String type) – specifies the content type of the response to the browser to assist in displaying the data.

• void getContentType() – gets the content type of the response.

Page 26: 12/1/2015 L.MARIA MICHAEL VISUWASAM UNIT-4 1 SERVLET.

EXAMPLE OF AN HTTP SERVLET - GET/HEAD METHODS

public class SimpleServlet extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { // set header field first res.setContentType("text/html"); // then get the writer and write the response data PrintWriter out = res.getWriter(); out.println("<HEAD><TITLE> SimpleServlet</TITLE></HEAD> <BODY>"); out.println("<h1> SimpleServlet Output </h1>"); out.println("</BODY>"); out.close(); } public String getServletInfo() { return "A simple servlet"; } }

Page 27: 12/1/2015 L.MARIA MICHAEL VISUWASAM UNIT-4 1 SERVLET.

ACCESSING WEB-BASED SERVLETS

• Assume the servlets' class file has been placed in the server's servlets directory. The servlet can be called by including /servlet/ before the servlet name in the URL.

• For example, if you set the class name of the sample servlet to TestServlet, then it could be accessed using http://<hostname>/servlet/TestServlet

Page 28: 12/1/2015 L.MARIA MICHAEL VISUWASAM UNIT-4 1 SERVLET.

The most basic web application in Tomcat will require the creation of a directory inside the webapps directory to hold the web application. For this first example, we’ll create a subdirectory called first-examples.

CREATING A WEB APPLICATION (CONT.)

Create this directory inside the webapps directory of Tomcat.

Page 29: 12/1/2015 L.MARIA MICHAEL VISUWASAM UNIT-4 1 SERVLET.

Within the first-examples directory we need to create a directory that will hold the configuration and all of the resources for the web application. This directory must be called WEB-INF.

The most important and only required element in WEB-INF is the file web.xml. The web.xml file controls everything specific to the current web application. We’ll look at this file in more detail later as we add to it, but for now we’ll look only at the components of this file that are essential for a very simple web application.

The next page illustrates our initial web.xml file.

CREATING A WEB APPLICATION (CONT.)

Page 30: 12/1/2015 L.MARIA MICHAEL VISUWASAM UNIT-4 1 SERVLET.

CREATING A WEB APPLICATION (CONT.) The web-app

tag

Optional display-name tag. Used by administrator tools.

Optional description for reading the xml file.

Servlet declaration. Specifies the name of the servlet, the implementing class file, and any initialization parameters.

Servlet mapping associates a servlet name with a class of URLs. One servlet may be configured to handle multiple sets of URLs, however, only one servlet can handle any given URL.

Page 31: 12/1/2015 L.MARIA MICHAEL VISUWASAM UNIT-4 1 SERVLET.

With these directories and files in place, Tomcat will be able to respond to a request for the page from a client athttp://localhost:8080/first-examples/WelcomeServlet.html.

Other HTML and JSP pages can be added at will, along with images, MP3 files, and just about anything else.

Although what we have just seen is all that is required to create a minimal web application, much more is possible with a knowledge of how web applications are arranged and we will see this as we progress through this technology.

The next few slides illustrate the execution of our simple web application (a welcome servlet).

CREATING A WEB APPLICATION (CONT.)

Page 32: 12/1/2015 L.MARIA MICHAEL VISUWASAM UNIT-4 1 SERVLET.

EXECUTION OF THE WELCOMESERVLET

This is the XHTML file that generates the output shown above which informs the client how to invoke the servlet.

Client invokes the WelcomeServlet page from the web application named first-examples.

Page 30

Page 33: 12/1/2015 L.MARIA MICHAEL VISUWASAM UNIT-4 1 SERVLET.

Execution of the WelcomeServlet servlet

Page 31

Page 34: 12/1/2015 L.MARIA MICHAEL VISUWASAM UNIT-4 1 SERVLET.

The XHTML document shown on page 30 provides a form that invokes the servlet defined on page 23.

The form’s action attribute (/first-examples/welcome1) specifies the URL path that invokes the servlet.

The form’s method attribute indicates that the browser sends a get request to the server, which results in a call to the servlet’s doGet method.

We’ll look at how to set-up the URL’s and deployment structure in the next set of notes.

AN XHTML DOCUMENT

Page 35: 12/1/2015 L.MARIA MICHAEL VISUWASAM UNIT-4 1 SERVLET.

The exact set-up you need to use for setting up your web application in Tomcat is summarized on the next couple of pages.

1. In the Tomcat webapps folder create a directory named first-examples.

2. In the top level of first-examples copy the WelcomeServlet.html file from the course code page.

3. In the top level of first-examples create a directory named WEB-INF.

4. When steps 2 and 3 are complete the top level of first-examples should look like the picture at the top of the next page.

SET-UP FOR FIRST WEB APPLICATION

Page 36: 12/1/2015 L.MARIA MICHAEL VISUWASAM UNIT-4 1 SERVLET.

Copy the web.xml configuration file from the course code page into the WEB-INF directory.

At the top level of the WEB-INF directory create a directory named classes.

When steps 5 and 6 are complete, the WEB-INF directory should look like the picture on the top of the next page.

SET-UP FOR FIRST WEB APPLICATION (CONT.)

Top level of first-examples.

Page 37: 12/1/2015 L.MARIA MICHAEL VISUWASAM UNIT-4 1 SERVLET.

8. Copy the WelcomeServlet.java file from the course code page into the classes directory and compile it to produce the WelcomeServlet.class file which should also reside in the classes directory. (The .java file does not need to reside in this directory for a servlet, but it is handy to keep the source in the same place.)

SET-UP FOR FIRST WEB APPLICATION (CONT.)

Top level of WEB-INF.

Page 38: 12/1/2015 L.MARIA MICHAEL VISUWASAM UNIT-4 1 SERVLET.

9. Once the classes directory looks like the one shown above. You are ready to invoke the servlet from a web browser. Start Tomcat and enter the URL http://localhost:8080/WelcomeServlet.html. Tomcat and the servlet will do the rest. If all goes well you should see the output that was shown on page 31.

SET-UP FOR FIRST WEB APPLICATION (CONT.)

The classes directory