java servlets. agenda: what is a servlet? the advantages of servlets over "traditional"...

32
Java Servlets

Upload: shanon-stephens

Post on 23-Dec-2015

296 views

Category:

Documents


3 download

TRANSCRIPT

Page 1: Java Servlets. Agenda:  What is a servlet?  The Advantages of Servlets Over "Traditional" CGI  Servlet Architecture  The Servlet Life Cycle  Types

Java Servlets

Page 2: Java Servlets. Agenda:  What is a servlet?  The Advantages of Servlets Over "Traditional" CGI  Servlet Architecture  The Servlet Life Cycle  Types

Agenda:What is a servlet?The Advantages of Servlets Over

"Traditional" CGIServlet ArchitectureThe Servlet Life CycleTypes of ServletsHow servlets work? javax.servlet & javax.servlet.http packages

Page 3: Java Servlets. Agenda:  What is a servlet?  The Advantages of Servlets Over "Traditional" CGI  Servlet Architecture  The Servlet Life Cycle  Types

What Is a Servlet?

•Servlets are server-side Java applications, as opposed to

client-side applets or standalone  applications.

•While servlets are compatible with many different types of

servers, typically they are used in web servers, as a

replacement for CGI scripts or Active-Server Pages

(ASP).

Page 4: Java Servlets. Agenda:  What is a servlet?  The Advantages of Servlets Over "Traditional" CGI  Servlet Architecture  The Servlet Life Cycle  Types

• In generic terms, a servlet is any class that can be invoked and executed on a server, most likely on behalf of a client. Unlike applets, which do their work on the client, servlets do their work on the server

• Another way of phrasing what servlets do is "server-side Java." Since servlets are written in Java and are part of the J2EE specification, they have access to all the functionality and cross-platform portability of the Java programming language.

Page 5: Java Servlets. Agenda:  What is a servlet?  The Advantages of Servlets Over "Traditional" CGI  Servlet Architecture  The Servlet Life Cycle  Types

The Advantages of Servlets Over "Traditional" CGI Efficient

Threads instead of OS processes, one servlet copy,persistence With servlets, the Java virtual machine stays running and handles

each request with a lightweight Java thread, not a heavyweight operating system process.

Servlets, however, remain in memory even after they complete a response, so it is straightforward to store arbitrarily complex data between client requests.

Convenient Servlets have an extensive infrastructure for automatically parsing

and decoding HTML form data, reading and setting HTTP headers, handling cookies, tracking sessions, and many other such high-level utilities

Powerful Sharing data, pooling & persistence

Page 6: Java Servlets. Agenda:  What is a servlet?  The Advantages of Servlets Over "Traditional" CGI  Servlet Architecture  The Servlet Life Cycle  Types

The Advantages of Servlets Over "Traditional" CGI ……..contd

Portable Run on virtually all operatings systems and web servers

Secure No shell escapes, no buffer overflows

Inexpensive cbt:

array bounds checking and other memory protection features are a central part of the Java programming language

cbt:

array bounds checking and other memory protection features are a central part of the Java programming language

Page 7: Java Servlets. Agenda:  What is a servlet?  The Advantages of Servlets Over "Traditional" CGI  Servlet Architecture  The Servlet Life Cycle  Types

Servlets Architecture:Following diagram shows the position of

Servelts in a Web Application.

Page 8: Java Servlets. Agenda:  What is a servlet?  The Advantages of Servlets Over "Traditional" CGI  Servlet Architecture  The Servlet Life Cycle  Types

Servlets Tasks:Servlets perform the following major tasks: Read the explicit data sent by the clients (browsers). This includes an HTML form

on a Web page or it could also come from an applet or a custom HTTP client program.

Read the implicit HTTP request data sent by the clients (browsers). This includes cookies, media types and compression schemes the browser understands, and so forth.

Process the data and generate the results. This process may require talking to a database, executing an RMI or CORBA call, invoking a Web service, or computing the response directly.

Send the explicit data (i.e., the document) to the clients (browsers). This document can be sent in a variety of formats, including text (HTML or XML), binary (GIF images), Excel, etc.

Send the implicit HTTP response to the clients (browsers). This includes telling the browsers or other clients what type of document is being returned (e.g., HTML), setting cookies and caching parameters, and other such tasks.

Page 9: Java Servlets. Agenda:  What is a servlet?  The Advantages of Servlets Over "Traditional" CGI  Servlet Architecture  The Servlet Life Cycle  Types

Types of Servlets Servlets must implement the interface

javax.servlet.Servlet.

There are two main types of servlets:  1) Generic servlets extend javax.servlet.GenericServlet.

Generic servlets are protocol independent, meaning that they contain no inherent support for HTTP or any other transport protocol. 

2) HTTP servlets extend javax.servlet.http.HttpServlet. These servlets have built-in support for the HTTP

protocol and are much more useful in an Browser

environment

Page 10: Java Servlets. Agenda:  What is a servlet?  The Advantages of Servlets Over "Traditional" CGI  Servlet Architecture  The Servlet Life Cycle  Types

Types of Servlet…contd So basically Generic Servlets are non web based

servlets and Http servlets are web based servlets

All Servlets must implement a service() method. This method is responsible for handling requests made to the Servlet. For generic Servlets, you simply override the service() method to provide routines for handling requests. HTTP Servlets provide a service method that automatically routes the request to another method in the servlet based on which HTTP transfer method is used, so for HTTP Servlets you would override doPost() to process POST requests, doGet() to process GET requests, and so on.

Page 11: Java Servlets. Agenda:  What is a servlet?  The Advantages of Servlets Over "Traditional" CGI  Servlet Architecture  The Servlet Life Cycle  Types

How servlets work? Servlets are created and managed at run time by the Servlet engine,

that runs inside the Java server. The input data on which servlets operate is encapsulated in an

object called the request object. A Servlets response to a query is encapsulated in an object called the response object.

Servlets call EJBs to perform business logic functions. Servlets call JSPs to perform page layout functions.

Servlets control user sessions in order to provide some persistence of user information between interactions.

Servlets can be a part of a particular application, or they can reside separately in order to be available to multiple applications. The latter type are said to be members of the generic ("Default") application.

Servlets can be dynamically reloaded while the server is running Servlets are addressable as URLs. The buttons on your application's

pages usually point to servlets. Servlets can also call other servlets. 

Page 12: Java Servlets. Agenda:  What is a servlet?  The Advantages of Servlets Over "Traditional" CGI  Servlet Architecture  The Servlet Life Cycle  Types

Servlets Packages: Java Servlets are Java classes run by a web server that has an

interpreter that supports the Java Servlet specification. Servlets can be created using the javax.servlet and

javax.servlet.http packages, which are a standard part of the Java's enterprise edition, an expanded version of the Java class library that supports large-scale development projects.

These classes implement the Java Servlet and JSP specifications. At the time of writing this tutorial, the versions are Java Servlet 2.5 and JSP 2.1.

Java servlets have been created and compiled just like any other Java class. After you install the servlet packages and add them to your computer's Classpath, you can compile servlets with the JDK's Java compiler or any other current compiler.

Page 13: Java Servlets. Agenda:  What is a servlet?  The Advantages of Servlets Over "Traditional" CGI  Servlet Architecture  The Servlet Life Cycle  Types

Package javax.servlet Interfaces

1) Servlet

2) ServletRequest

3) ServletResponse

4) ServletConfig

5) ServletContext

6) RequestDispatcher

7) SingleThreadModel

Classes

1) GenericServlet

2) ServletInputStream

3) ServletOutputStream

Exceptions

1) ServletException

2) UnavailableException

Page 14: Java Servlets. Agenda:  What is a servlet?  The Advantages of Servlets Over "Traditional" CGI  Servlet Architecture  The Servlet Life Cycle  Types

Interface Summary

RequestDispatcher

Defines an object that receives requests from the client and sends them to any resource (such as a servlet, HTML file, or JSP file) on the server.

Servlet Defines methods that all servlets must implement.

ServletConfigA servlet configuration object used by a servlet container used to pass information to a servlet during initialization.

ServletContext

Defines a set of methods that a servlet uses to communicate with its servlet container, for example, to get the MIME type of a file, dispatch requests, or write to a log file.

ServletRequestDefines an object to provide client request information to a servlet.

ServletResponse

Defines an object to assist a servlet in sending a response to the client.

SingleThreadModel

Ensures that servlets handle only one request at a time.

Interface Summary

RequestDispatcher

Defines an object that receives requests from the client and sends them to any resource (such as a servlet, HTML file, or JSP file) on the server.

Servlet Defines methods that all servlets must implement.

ServletConfigA servlet configuration object used by a servlet container used to pass information to a servlet during initialization.

ServletContext

Defines a set of methods that a servlet uses to communicate with its servlet container, for example, to get the MIME type of a file, dispatch requests, or write to a log file.

ServletRequestDefines an object to provide client request information to a servlet.

ServletResponse

Defines an object to assist a servlet in sending a response to the client.

SingleThreadModel

Ensures that servlets handle only one request at a time.

Page 15: Java Servlets. Agenda:  What is a servlet?  The Advantages of Servlets Over "Traditional" CGI  Servlet Architecture  The Servlet Life Cycle  Types

Class Summary

GenericServlet Defines a generic, protocol-independent servlet.

ServletInputStream

Provides an input stream for reading binary data from a client request, including an efficient readLine method for reading data one line at a time.

ServletOutputStream

Provides an output stream for sending binary data to the client.

  Exception Summary

ServletExceptionDefines a general exception a servlet can throw when it encounters difficulty.

UnavailableException

Defines an exception that a servlet throws to indicate that it is permanently or temporarily unavailable.

Page 16: Java Servlets. Agenda:  What is a servlet?  The Advantages of Servlets Over "Traditional" CGI  Servlet Architecture  The Servlet Life Cycle  Types

Package javax.servlet.http Interfaces

1) HttpServletRequest

2) HttpServletResponse

3) HttpSession

4) HttpSessionBindingListener

5) HttpSessionContext

6) SingleThreadModel

Classes

1) HttpServlet

2) HttpUtils

3) Cookie

4) HttpSessionBindingEvent

Page 17: Java Servlets. Agenda:  What is a servlet?  The Advantages of Servlets Over "Traditional" CGI  Servlet Architecture  The Servlet Life Cycle  Types

Interface Summary

HttpServletRequestExtends the ServletRequest interface to provide request information for HTTP servlets.

HttpServletResponseExtends the ServletResponse interface to provide HTTP-specific functionality in sending a response.

HttpSessionProvides a way to identify a user across more than one page request or visit to a Web site and to store information about that user.

HttpSessionBindingListener

Causes an object to be notified when it is bound to or unbound from a session.

HttpSessionContextDeprecated. As of Java(tm) Servlet API 2.1 for security reasons, with no replacement.

 

Class Summary

CookieCreates a cookie, a small amount of information sent by a servlet to a Web browser, saved by the browser, and later sent back to the server.

HttpServletProvides an abstract class to be subclassed to create an HTTP servlet suitable for a Web site.

HttpSessionBindingEvent

Sent to an object that implements HttpSessionBindingListener when the object is bound to or unbound from the session

HttpUtilsProvides a collection of methods that are useful in writing HTTP servlets.

Page 18: Java Servlets. Agenda:  What is a servlet?  The Advantages of Servlets Over "Traditional" CGI  Servlet Architecture  The Servlet Life Cycle  Types

ServletContext Interface ServletContext interface is a window for a servlet to view it's

environment. A servlet can use this interface to get information such as initialization parameters for the web application or servlet container's version. Every web application has one and only one ServletContext and is accessible to all active resource of that application

ServletContext is an Interface that defines a set of methods that a servlet uses to communicate with its servlet container, for example, to get the MIME type of a file, dispatch requests, or write to a log file. There is one context per "web application" per Java Virtual Machine. (A "web application" is a collection of servlets and content installed under a specific subset of the server's URL namespace such as /catalog and possibly installed via a .war file.)

Page 19: Java Servlets. Agenda:  What is a servlet?  The Advantages of Servlets Over "Traditional" CGI  Servlet Architecture  The Servlet Life Cycle  Types

ServletConfig Interface A servlet configuration object used by a servlet

container to pass information to a servlet during initialization.

All of its initialization parameters can ONLY be set in deployment descriptor

The ServletContext object is contained within the ServletConfig object, which the Web server provides the servlet when the servlet is initialized.

Page 20: Java Servlets. Agenda:  What is a servlet?  The Advantages of Servlets Over "Traditional" CGI  Servlet Architecture  The Servlet Life Cycle  Types

ServletContext

The ServletContext parameters are specified for an entire application outside of any particular servlet and are available to all the servlets within that application.

ServletContext has a APPLICATION SCOPE .. [GLOBALLY ACCESSIBLE ACROSS THE PAGES]

ServletConfig

The ServletConfig parameters are specified for a particular servlet and are unknown to other servlets.

ServletConfig has a SESSION SCOPE.. [LOCAL SCOPE......which is mostly used for initialising purpose]. javax.servlet.ServletConfig has page scope

Page 21: Java Servlets. Agenda:  What is a servlet?  The Advantages of Servlets Over "Traditional" CGI  Servlet Architecture  The Servlet Life Cycle  Types

Difference between ServletConfig and ServletContext Signature: public interface ServletContext

ServletContext is implemented by the servlet container for all servlet to communicate with its servlet container, for example, to get the MIME type of a file, to get dispatch requests, or to write to a log file. That is to get detail about its execution environment. It is applicable only within a single Java Virtual Machine. If a web application is distributed between multiple JVM this will not work. For understanding, this is like a application global variable mechanism for a single web application deployed in only one JVM.

The ServletContext object is contained within the ServletConfig object. That is, the ServletContext can be accessed using the ServletConfig object within a servlet. You can specify param-value pairs for ServletContext object in <context-param> tags in web.xml file.

Example code:<context-param><param-name>globalVariable</param-name><param-value>javapapers.com</param-value></context-param>

Page 22: Java Servlets. Agenda:  What is a servlet?  The Advantages of Servlets Over "Traditional" CGI  Servlet Architecture  The Servlet Life Cycle  Types

Difference between ServletConfig and ServletContext Signature: public interface ServletConfig

ServletConfig is implemented by the servlet container to initialize a single servlet using init(). That is, you can pass initialization parameters to the servlet using the web.xml deployment descriptor. For understanding, this is similar to a constructor in a java class.

Example code:<servlet><servlet-name>ServletConfigTest</servlet-name><servlet-class>com.javapapers.ServletConfigTest</servlet-class><init-param><param-name>topic</param-name><param-value>Difference between ServletConfig and ServletContext</param-value></init-param></servlet>

Page 23: Java Servlets. Agenda:  What is a servlet?  The Advantages of Servlets Over "Traditional" CGI  Servlet Architecture  The Servlet Life Cycle  Types

Steps to Write a Basic Servlet1. Import the appropriate packages and classes, including:

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

2. Extend javax.servlet.http.HttpServlet.

public class HelloWorldServlet extends HttpServlet{

3. Implement a service() method. The main function of a servlet is to accept an HTTP request from a Web Browser, and return an HTTP response. This work is done by your servlet's service() method. The service methods include response objects that you use to create output and request objects used to receive data from the client.

public void service(HttpServlet Request req,HttpServletResponse res) throws IOException{

Page 24: Java Servlets. Agenda:  What is a servlet?  The Advantages of Servlets Over "Traditional" CGI  Servlet Architecture  The Servlet Life Cycle  Types

Steps to Write a Basic Servlet…..contd4. Set the content type.

res.setContentType("text/html");

5. Obtain a PrintWriter object to use for output.

PrintWriter out = res.getWriter();

6. Create some HTML using the PrintWriter object

out.println("<html><head><title>Hello World!</title></head>");out.println("<body><h1>Hello World!</h1></body></html>");}}

7. Compile the servlet

Page 25: Java Servlets. Agenda:  What is a servlet?  The Advantages of Servlets Over "Traditional" CGI  Servlet Architecture  The Servlet Life Cycle  Types

Program - 1import javax.servlet.*;

import java.io.*;

public class HelloServlet extends GenericServlet

{

public void service(ServletRequest req, ServletResponse res)

{

try{

PrintWriter output=res.getWriter();

output.println("<html><body bgcolor=blue text=red>");

output.println("<b> HELLO WORLD</b>");

output.println("</body></html>");

}catch(Exception e){}

}

}

Page 26: Java Servlets. Agenda:  What is a servlet?  The Advantages of Servlets Over "Traditional" CGI  Servlet Architecture  The Servlet Life Cycle  Types

Servlets are Java classes which service HTTP requests and implement the javax.servlet.Servlet interface. Web application developers typically write servlets that extend javax.servlet.http.HttpServlet, an abstract class that implements the Servlet interface and is specially designed to handle HTTP requests.

Sample Code for Hello World:

Following is the sample source code structure of a servlet example to write Hello World:

// Import required java libraries import java.io.*; import javax.servlet.*; import javax.servlet.http.*;

Program - 2

Page 27: Java Servlets. Agenda:  What is a servlet?  The Advantages of Servlets Over "Traditional" CGI  Servlet Architecture  The Servlet Life Cycle  Types

// Extend HttpServlet classpublic class HelloWorld extends HttpServlet { private String message;

public void init() throws ServletException { // Do required initialization message = "Hello World"; } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Set response content type response.setContentType("text/html");

// Actual logic goes here. PrintWriter out = response.getWriter(); out.println("<html><head><title>Hello World!</title></head>"); out.println("<body><h1>” +message+ “</h1></body></html>"); } public void destroy() { // do nothing. }}

Page 28: Java Servlets. Agenda:  What is a servlet?  The Advantages of Servlets Over "Traditional" CGI  Servlet Architecture  The Servlet Life Cycle  Types

Compiling a Servlet: Let us put above code of HelloWorld.java file and put this file in C:\ServletDevel

(Windows) then you would need to add these directories as well in CLASSPATH.

Assuming your environment is setup properly, go in ServletDevel directory and compile HelloWorld.java as follows:

C:\ServletDevel> javac HelloWorld.java

If the servlet depends on any other libraries, you have to include those JAR files on your CLASSPATH as well. I have included only servlet-api.jar JAR file because I'm not using any other library in Hello World program.

This command line uses the built-in javac compiler that comes with the Sun Microsystems Java Software Development Kit (JDK). For this command to work properly, you have to include the location of the Java SDK that you are using in the PATH environment variable.

If everything goes fine, above compilation would produce HelloWorld.class file in the same directory.

Page 29: Java Servlets. Agenda:  What is a servlet?  The Advantages of Servlets Over "Traditional" CGI  Servlet Architecture  The Servlet Life Cycle  Types

Servlet Deployment: By default, a servlet application is located at the path <Tomcat-installation-

directory>/webapps/ROOT and the class file would reside in <Tomcat-installation-directory>/webapps/ROOT/WEB-INF/classes.

If you have a fully qualified class name of com.myorg.MyServlet, then this servlet class must be located in WEB-INF/classes/com/myorg/MyServlet.class.

For now, let us copy HelloWorld.class into <Tomcat-installation-directory>/webapps/ROOT/WEB-INF/classes and create following entries in web.xml file located in <Tomcat-installation-directory>/webapps/ROOT/WEB-INF/

Note: Instead of ROOT, you can also create your own directory and create the WEB-INF structure in it and place your program there.

Page 30: Java Servlets. Agenda:  What is a servlet?  The Advantages of Servlets Over "Traditional" CGI  Servlet Architecture  The Servlet Life Cycle  Types

<web-app> <servlet> <servlet-name>HelloWorld</servlet-name> <servlet-class>HelloWorld</servlet-class> </servlet>

<servlet-mapping> <servlet-name>HelloWorld</servlet-name> <url-pattern>/HelloWorld</url-pattern> </servlet-mapping></web-app>

Above entries to be created inside web.xml file. There could be various entries in this table already available, but never mind.

You are almost done, now let us start tomcat server using <Tomcat-installation-directory>\bin\startup.bat (on windows) and finally type http://localhost:8080/HelloWorld in browser's address box.

Page 31: Java Servlets. Agenda:  What is a servlet?  The Advantages of Servlets Over "Traditional" CGI  Servlet Architecture  The Servlet Life Cycle  Types

If everything goes fine, you would get following result:

Page 32: Java Servlets. Agenda:  What is a servlet?  The Advantages of Servlets Over "Traditional" CGI  Servlet Architecture  The Servlet Life Cycle  Types

THANK YOU……