Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 54

SERVLETS

Abhishek Mane February 8th 2013

REQUEST-RESPONSE MODEL

HTTP REQUEST AND HTTP RESPONSE

HTTP Request : Key elements of HTTP request file are


HTTP method [Action to be performed] The page to access [A Url] Form Parameter

HTTP Response :
Status Code [Whether request was successful] Content type [text, html, picture, Jar] The content [the actual content]

GMAIL LOGIN PAGE

WHERE DOES SERVLETS FITS INTO PICTURE?


I can Serve Only Static HTML Page

I can
handle dynamic

Helper Application

request

WHAT IS A WEB CONTAINER

WHAT IS THE ROLE OF A CONTAINER ?


Communication Management Lifecycle Management Multi-threading Support Security JSP Support

SERVLET CONTAINER
A servlet is a part of java web application. A servlet container may run multiple application at the same time, each having multiple servlets running inside it Container provide runtime environment for servlets and used to manage lifecycle of a servlets

WHAT IS SERVLETS ?
Servlets is a server-side java program that is platform independent Servlets, written in java dynamically extend the functionality of java enabled web server Web server cannot talk to a databases. This is where servlets help extend the functionality of web server. Web server use the servlets ability to access a database table, execute table data and convert to format acceptable to a web server for delivery to a client via interface Even though servlets written in java, their client may not be written in java.

WHAT IS SERVLETS ?
This means that servlets used in the middle tiers of the distributed application. Servlets can in turn be the client to any other services Servlets are not tied to specific client-server protocol but they are most commonly used with HTTP. The word servlet is often represented as HTTP Servlets Servlets run within web server namespace they do not display graphical user interface. A servlet work is done behind the scenes

WHY SERVLETS ?
Efficient Invocation : Are loaded into memory once and run from memory thereafter Are spawned as a thread not as a process Are portable across multiple web servers and platform Are robust, scalable and secure Service clients request efficiently

WHAT SERVLETS CAN DO?


Servlets can be used as a plug-in, that features a search engine or semi-customize application such as web based banking system Servlets can be used to process the data submitted using an HTML form and do some validation Servlets can handle multiple request concurrently and these requests can be synchronize to support systems Servlets can forward request to other servlets and servers Servlet can maintain and track sessions Servlets can pass data between themselves

SERVLETS V/S CGI


With CGI, a new process is started for each HTTP request , The initialization of CGI takes longer time than its execution time, whereas for each servlet request thread is started If there are N CGI program, then the code for the CGI program is loaded into memory N times. However there are N thread for N request for single instance of a servlets Servlets can talk directly to web server whereas CGI cannot

SERVLET ARCHITECTURE OVERVIEW

SERVLET ARCHITECTURE (CONT.)

The central abstraction in servlet API is servlet interface. All of the classes required to create and execute are contained within following two packages
Javax.Servlet.Servlet Javax.Servlet.Http

Servlets in general is an instance of a class which implements servlet interface. However, servlets commonly used by extending specific implementation of servlets such as Javax.Servlet.GenericServlets and Javax.servlet.Http.HttpServlets

SERVLET ARCHITECTURE (CONT..)


Servlet interface has methods which manage servlets and communication with clients. For developing servlets programmer use some or all of those methods. Following are the commonly used classes and interfaces

Generic Servlet class HttpServlet class ServletRequest class HttpServletRequest class ServletResponse class HttpServletResponse class

GENERIC SERVLET
Generic Servlets implements servlet and servlet config interface. Generic Servlet may be directly extended by a servlet. Although, its most common to extend protocol specific servlets such HttpServlet. Generic Servlets make writing servlet easier. It provides simple version of init() and destroy() method and of the methods in servlet config interface. Generic Servlet also implement Log() method from the servlet context interface

HTTPSERVLET CLASS
Http Servlet class inherits basic servlet functionality by extending GenericServlet HttpServlet class is an abstract class that resides in Javax.Servlet.http package. Because it is abstract it cannot be instantiated. Rather, when building an HTTP servlet. This class must be extended and override at least one of the method implemented. A functional Http Servlet must override at least one of the methods typically service(), doGet(), doPost().HttpServlet doesn't provide the implementation of most of the method, it does provide framework for supporting the HTTP protocol.

HTTP SERVLET

Methods in Http Servlet are :


Service() : The server calls this method when servlet request is received .For Http Servlet usually method is not overridden . doGet() : This method is called in response to Http Get request doPost() : This method is called in response to Http Post request doHead() : This method is called in response to HttpHead request doPut() : This method is called in response to http put request. If put request are supported this method should be overridden doDelete() : This method is called in response to http Delete request

REQUEST AND RESPONSE


When a servlet accepts a request from a client, it receives two objects such as, ServletRequest and ServletResponse. Servlet Request encapsulate communication from client to server. Servlet response encapsulate communication from server to client ServletResponse interface allow the servlet to access information such as, names of the parameter passed by the request, protocol being used by the client , names of the remote host that made the request and name of the server that received it

REQUEST AND RESPONSE


Servlet Request also have been provided access to the input stream such as Servlet Input Stream Subclasses of ServletRequest allow the Servlet to retrieve more protocol specific data. HttpServlet contains method for accessing http protocol specific data Servlet Response interface provides the method to the servlet for replying to the client. It allow the servlet to set the content length and mime type and provide and output stream such as ServletOutput Stream

WEB.XML DEPLOYMENT DESCRIPTOR


A web application deployment descriptor describes classes , resources and configuration of the application and how web server uses them to serve the web request When web server receives a request for the application, it uses the deployment descriptor to map the URL of the request to the code that ought to handle the request. Deployment descriptor file name is web.xml, it resides in WEB-INF directory

SERVLETCONFIG INTERFACE
A servlet config object used by the servlet container in order to pass information to servlet during initialization The configuration information contains initialization parameters, which are set of name/value pairs and a ServletContextObject which gives the servlet information about the server A servlet Config object is created by the web container for each servlet

SERVLETCONTEXT INTERFACE

ServletContext is contained within the ServletConfig object, object of this type is created by the web container. This object can be used to get the configuration information from web.xml There is only one servletContext per web application. WorkFlow
First of all web container reads web.xml file and creates name/value pair for each <Context-param> tag. After creating name/value pair it creates a new instance of ServletContext Web container pass the reference of init parameters to object of servlet context

SERVLET LIFECYCLE

In order to initialize a servlet, the servlet engine first locate its class. Then servlet engine uses the usual java class loading facilities to load the servlet class into the JVM. Once loaded, servlet engine instantiates an instance of that servlet class [and probably other classes which are referenced by the servlet] The init() method is called immediately after the server constructs the servlet instance. This process happens only once in servlet lifecycle i.e. when,

Server Starts When first Servlet request received System Administrator manually initialize it

During initialization servlet has access to two key objects i.e. ServletConfig and ServletContext. Init () method help read the configuration data from configuration file Following are the common task that can be implemented by overriding init() method

SERVLET LIFECYCLE
Reading initialization parameters using ServletConfig objects Opening a JDBC connection Writing log information to a network resources

After the server loads and initialize the servlet, the servlet is able to handle client request.it process them in its service() method. Each client request is run in separate servlet thread and pass and two objects such as servletRequest and ServletResponse are passed in as a parameters When instructed to unload the servlet by the administrator or programmatically , servlet engine calls destroy() method. The servlet is then eligible for garbage collection

SERVLET LIFECYCLE

The common task implemented in destroy() method are


Synchronizing the clean up tasks such as closing up any open resources, closing up database connection. Informing other application that servlet be no longer in service

HELLO WORLD SERVLET


The Focus : The servlet code spec that follows does nothing more than returning a simple sentence Hello World along with the number of time it has been requested

MODEL VIEW CONTROLLER


It is a software architecture pattern that separate the representation of information from the users interaction with it MVC1 was a first generation approach that used JSP pages and java bean component architecture to implement the MVC architecture for web. HTTP request are sent to a JSP/Servlet page that implements controller logic and calls out to model for the data to update the view. MVC architecture is used for simple development

DRAWBACKS OF MVC1

Maintenance issues

Doesnt support reusability of application In MVC1, Business and presentation logic is combined so the web developer and web designer cant work simultaneously Tight coupling between page and model

MVC1

MVC2 ARCHITECTURE
Model : The model contains applications data and business rules. It responds to the request from the view and it also responds to the request from the controller to update itself Controller : The controller is responsible for responding to the user inputs and perform interactions on the data model objects. The controller receives the input, validate the input and perform business processing which modifies the state of the data model View : View layer present the data which is passed to it by the controller. Controller take that data from model layer of the application

ADVANTAGE OF USING MVC2


Reusability of component Easier to debug Presentation logic separate from business logic it allow developer and designer to work together

READING HTML FORM DATA USING SERVLET


We Will be using HTTPRequest object for this task. Key method of request objects are

getParameter() : you call the request.getParameter() to get the value of a form parameter. getParameterValues() : call this method if the parameter appears more than once and return multiple values, for example checkbox getParameterNames () : get the complete list of all the parameters in the current reques

PROBLEM STATEMENT

Read the Username, Password and subject that user wish to choose. Process it using the servlet and display it.

CONFIGURING AND MAPPING SERVLET

Servlet should be registered with the servlet container. You should add entry in deployment descriptor in web.xml. It is located under WEB-INF directory of the web application.

<servlet> <Servlet-name>HelloWorld</Servlet-name> <Servlet-class>com.VJTI.TYBTECH.HelloForm</ServletClass> </servlet> <servlet-mapping> <servlet-name>HelloWorld</servlet-name> <url-pattern>/HelloWorld</url-pattern> </servlet-mapping>

CONFIGURING AND MAPPING SERVLET


Servlet Mapping has two child tags , url-pattern and servlet name. url-pattern specify type of url, for which servlet given in servlet name should be called. Be aware that, container will use case sensitive for string matching for servlet matching. Mapping rule : A string beginning with a / character and ending with a /* suffix is used for path mapping. A string beginning with a *. prefix is used as an extension mapping.

SERVLET LOAD ON START UP


The <servlet> element has a subelement called <load-on-startup> which you can use to control when the servlet container should load the servlet. If you do not specify a <load-on-startup> element, the servlet container will typically load your servlet when the first request arrives for it. By setting a <load-on-startup> element, you can tell the servlet container to load the servlet as soon as the servlet container starts. Remember, the servlets init() method is called when the servlet is loaded.

LOAD ON START UP
The number inside the <load-on-startup>1</loadon-startup> element tells the servlet container in what sequence the servlets should be loaded. The lower numbers are loaded first. If the value is negative, or unspecified, the servlet container can load the servlet at any time. Context Parameters :

You can also set some context parameters which can be read from all servlets in your application. Here is how you configure a context parameter:

THREAD SAFE SERVLET

The init() method is called once per servlet, when the servlet is loaded. You dont have to worry about the thread safety inside this method.it is only called by a single thread. Web server will wait before until this method exits before sending requests to service() method. Every new client requests generates the new thread, which calls service() method (which may in turn call doGet() or doPost() or both) Under most circumstances, there is only one instance of your servlet no matter how many client request are in process. That means at any given instance, there may be many thread running inside service() method , all sharing same instance data. That means you should be careful to synchronize shared data using synchronize keyword.

THREAD SAFE SERVLET


We do not need to synchronize on synchronize on local data or parameters. We should not synchronize service() , doGet() or doPost(). Simple solution to synchronizing is to synchronize on servlet instance itself, However, this will degrade the performance. You can also implement singleThreadModel interface. Empty interface tells container to send only one request at a time. This ensure no two thread will be executing service() method. But this is not an ideal solution since performance may suffer.

THREAD SAFE SERVLET?

The destroy() method is not as clean as the init() method. The server calls destroy () either after all calls have been completed or when certain number of seconds have passed. This means thread might be running service() method at the same as your destroy () method is called. So you be sure to synchronize the calls to destroy().

CONNECTING TO A DATABASE USING JDBC


JDBC stands for Java Database Connectivity . Its actually an API which consists of Java classes , interfaces and exceptions bound to a specification. JDBC driver and vendor must adhere to specification when developing an application. Application developed with Java and JDBC are platform and vendor independent. The latest release of JDBC technology is JDBC 4.0

JDBC ARCHITECTURE

JDBC is an API specification developed by Sun Microsystems, which defines an uniform sets of rule via an interface for accessing different relational databases. The purpose of the JDBC is to provide resources to developers via which they can issue SQL statements and process result in consistent, platform dependent way. JDBC API makes use of driver manager bound database specific drivers. This combination provides consistent, transparent DB connectivity to all database. JDBC driver manager is capable of supporting multiple concurrent drivers connected to multiple heterogeneous databases.

JDBC ARCHITECTURE (CONTD..)

A JDBC driver translate standard JDBC calls into a call native to a database, which enable an application module to communicate with the database it is the interpretation layer that provides the database independent JDBC application. If the backend database changes then very little code modification is required. The JDBC API is available mainly in two packages.
Java.sql package : This API is core API that is compatible with any driver that uses JDBC technology. Javax.sql package : This package is an optional package which extends the functionality of JDBC API from a client side API to server side API

IMPORTANT JDBC CLASSES, INTERFACE AND EXCEPTIONS

DriverManager : when driver manager runs , the driver manager loads all the driver found in memory. When opening a connection to a database the driverManager selects most appropriate driver from the previously loaded drivers. Connection: The connection interface represents connection with a data source. Statement : statement interface represents static sql statement that can be used to retrieve result set object. ResultSet : A result set is a database result set generated from currently executed SQL statement.

JDBC DRIVERS

JDBC consists of two parts:

JDBC API, a purely Java-based API JDBC Driver Manager,which communicates with vendor-specific drivers that perform the real communication with the database.

Java Application
JDBC API

JDBC Driver Manager


JDBC Driver API
JDBC-ODBC Bridge Vendor Specific JDBC Driver

Point: translation to vendor format is performed on the client No changes needed to server Driver (translator) needed on client

Vendor Specific ODBC Driver

Database

Database

IMPORTANT JDBC CLASSES, INTERFACE AND EXCEPTIONS (CONTD)


PreparedStatement : prepared statement object is an sql statement that is precompile and stored. This object can be executed multiple times much more efficiently than preparing and issuing same statement each time it is needed. Callable Statement : the callableStatement represents a stored procedure. It can be used to execute stored procedure in RDBMS that supports them. SQLException : it encapsulate database access errors.

CONFIGURING JDBC DRIVER

The first step to establish a database connection using JDBC driver involves loading the specific driver into applications JVM. This makes the driver available later required for opening database connection. Class.forName(com.mysql.jdbc.Driver)

The static method Class.forName trying to load and initialize the mysql driver object associated with the class specified in the parameter

ESTABLISH CONNECTION

Once you have registered the driver , you can establish the connection using DriverManager.getConnection() method. There are three overloaded getConnection() method.
getConnection(String url) getConnection(String url, Properties prop) getConnection(String url , String username , String password )

each getConnection requires database url. A database url is an address points to your database.

CLOSING THE DATABASE CONNECTION


At the end of your JDBC call, it is required to explicitly close all the connection to end each database session. However, if you forget garbage collector will close the connection when it cleans up stale objects. Relying on garbage collection, especially in database programming is very poor programming practice. You should always close the connection using close() method on connection object.

CREATING AND USING STATEMENT OBJECT

In order to execute SQL statement, we need to create statement object using connection objects createStatement() method. Statement stmt = null; try { stmt = conn.createStatement( ); . . . } catch (SQLException e) { . . . } finally { . . . }

CREATING AND USING STATEMENT

Once you have created statement object , you can use it to execute SQL statement with one of its three execute method.
boolean execute(String SQL) : use this method when you want to execute SQL DDL statements. int executeUpdate(String sql) : return the number of row affected by execution of this method.it is used for insert, update and delete statements. ResultSet executeQuery(String sql) : returns resultset object. Use this with SELECT statement.

You might also like