Professional Documents
Culture Documents
Ervlets: Abhishek Mane February 8 2013
Ervlets: Abhishek Mane February 8 2013
REQUEST-RESPONSE MODEL
HTTP Response :
Status Code [Whether request was successful] Content type [text, html, picture, Jar] The content [the actual content]
I can
handle dynamic
Helper Application
request
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
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
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
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
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
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.
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.
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:
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.
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().
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.
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
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 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
Point: translation to vendor format is performed on the client No changes needed to server Driver (translator) needed on client
Database
Database
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.
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 { . . . }
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.