You are on page 1of 18

Servlet Servlet is a server side software component written in java that

dynamically extends the functionality of a server.

Advantages of Servlet:
Servlet have many advantages over competing technologies. The following are
the advantages
Same Process Space: Servlets are capable of doing or running in process that runs
in the same process space of the server.
Compiled: Java is a byte code, so it executes more quickly. It also have the
advantage of strong error type checking.
Durable: It remains in memory until destroying.
Extensible: Since Servlet is written in Java language, with third party tools it is
easy to access the new tools of java, class libraries and database drivers.
Multithreaded: It allows client requests to be handled by separate threads within
a single process.
Protocol Independent: It not supports http but also supports FTP, SMTP or POP3,
TELNET, NNTP or any other protocols.
Secure: Servlet are secure in many different ways. They use servers, security
manager and secure protocol like SSL for security in Servlets.

Development of dynamic Web content:


To develop dynamic web content, there are three technologies available
(I) CGI
(II) Servlet
(III) Server Pages
Common Gateway Interface (CGI): It is actually an external application written
by using any of the programming language like C Or C++ and this is responsible for
processing client requests and generating dynamic content.
Servlet: Servlet is a server side component that extends the functionality of the
server.
Server pages: There are technologies such as JSP (Java Server Page) from Oracle
and ASP (Active Server Pages) from Microsoft is widely used to develop dynamic
web contents.
Servlet Advantages over CGI:
Servlet advantages over servlet in the areas of
• Performance
• Portability and
• Security.
Performance: Most servlet runs in the same process space in the server and are
loaded only once and they are able to respond much more quickly and efficiently
to client requests.
In contrast CGI create a new process space to service each new request.
Portability: Unlike many CGI applications, Servlets can be used and it runs on
different servers and platform without modification.
Security: Servlet are more secure than CGI.Though CGI Scripts can be written in
java, they are often written in more error prone languages such as C.Therefore
CGI programs are less secure where as untrusted servlets can run inside a
sandbox (protected memory space) on the server.

Servlet Container: A servlet has no static main () method. Therefore, a servlet


must execute under the control of an external container called Servlet Container.
It executes and manages servlets. The servlet container calls servlet methods and
provides services that the servlet needs while executing. 
A servlet container is usually written in Java and is either part of a Web server.
The servlet container provides the servlet with easy access to properties of the
HTTP requests.
When a servlet is called, such as when it is specified by URL, the Web server
passes the HTTP request to the servlet container. The container, in turn, passes
the request to the servlet.
Life Cycle of a Servlet

Three methods are central to the life cycle of a servlet. These are init( ), service( ),
and destroy( ). They are implemented by every servlet and are invoked at specific
times by the server.
Init() method:
The server invokes the init( ) method of the servlet. This method is invoked
only when the servlet is first loaded into memory. It is possible to pass
initialization parameters to the servlet so it may configure itself.
Service() method:
The server invokes the service( ) method to process the HTTP request.It may
also formulate an HTTP response for the client.The service( ) method is called
for each HTTP request.
Destroy() method:
The server calls the destroy( ) method to relinquish any resources such as file
handles that are allocated for the servlet.
API (APPLICATION PROGRAMMING INTERFACE)
It is a set of programming instructions and standards for accessing a webpage
software application or a web tool.
Servlet API:The javax.servlet package and the javax.servlet.http package together
constitute the Servlet API.
The javax.servlet package: It contains a number of interfaces and classes
that establishes the framework in which the servlet operates.

Interfaces of javax.servlet package:


The following table summarizes the core interfaces that are provided in this
package.
Interfaces Description
Servlet Declares life cycle methods that all servlets must
implement.
ServletConfig Allows servlets to get initialization parameters
ServletContext Allows servlets to communicate with its servlet
container.
ServletRequest Provides client request information to a servlet.
ServletResponse Assist a servlet in sending a response to the
client.

Classes of javax.servlet package:


The following table summarizes the core classes that are provided in the
javax.servlet package.
Classes Description

GenericServlet Provides a basic implementation of the Servlet interface for


protocol independent servlets
ServletlnputStream Provides an input stream for reading binary data from a
client request.
ServletOutputStream Provides an output stream for sending binary data to the
client.
ServletException Defines a general exception, a servlet can throw when it
encounters difficulty.
UnavailableException Indicates that a servlet is not available to service client
request.
ServletExample.java
import javax.servlet.*;
public class ServletExample extends GenericServlet
{
    public void service(ServletRequest req, ServletResponse res) throws
ServletException, IOException
   {
PrintWriter out = res.getWriter();
      String login= req.getParameter("loginid");
      String password= req.getParameter("password");
      out.print("You have successfully login :");
      out.println("Your login ID is: "+login);
      out.println("Your password is: " +password);
      out.close();
   }
}

index.html
<HTML>
   <BODY>
      <CENTER>
         <FORM NAME="Form1" METHOD="post"
ACTION="http://localhost:8080/ServletExample">
            <B>Login ID</B> <INPUT TYPE="text" NAME="loginid" SIZE="30">
              <P>
              <B>Password</B> <INPUT TYPE="password" NAME="password"
SIZE="30">
             </P>
             <P> <INPUT TYPE=submit VALUE="Submit">
<INPUT TYPE=reset VALUE=“Reset">
            </P>
   </BODY>
</HTML>

The javax.servlet.http package:


The second important package is javax.servlet.http , which contains APIs specific
to servlets that handle HTTP requests for web servers. 
This  package contains various interfaces and classes which are capable of
handling a specific http type of protocol.

Interfaces of javax.servlet.http package:


The following table summarizes the core interfaces that are provided in this
package.

 Interface   Description
HttpServletRequest The object of this interface is used to get the
information from the user under http protocol.

HttpServletResponse The object of this interface is used to provide the


response of the request under http protocol.

HttpSession This interface is used to track the information of users.

HttpSessionAttributeListener This interface notifies if any change occurs in


HttpSession attribute.

HttpSessionListener This interface notifies if any changes occur in


HttpSession lifecycle.
Classes of javax.servlet.http package:
The following table summarizes the core classes that are provided in the
javax.servlet.http package.

Class Description

HttpServlet This class is used to create servlet class.

Cookie This class is used to maintain the session of the state.

HttpSessionEvent This class notifies if any changes occur in the session of


web application.

HttpSessionBindingEvent This class notifies when any attribute is bound, unbound


or replaced in a session.

Program:

Index.html
<html>
<body>
<center>
<form name="form1" method="post"
action="http://localhost:8080/WebApplication5/ColorGetServlet">
<b>color:</b>
<select name="color" size="1">
<option value="Red">Red</option>
<option value="Green">Green</option>
<option value="Blue">Blue</option>
</select>
<br><br>
<input type=Submit value="Submit">
</form>
</body>
</html>
ColorGetServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ColorGetServlet extends HttpServlet
{
public void doPost(HttpServletRequest request,HttpServletResponse
response)throws ServletException,IOException
{
String color=request.getParameter("color");
response.setContentType("text/html");
PrintWriter pw=response.getWriter();
pw.println(color);
pw.close();
}}
Handling HTTP requests and HTTP responses:
The protocol used to send requests is HTTP. HTTP is a stateless protocol. The most
widely used HTTP requests are GET and POST.
In GET request, all the query data is appended to the URI itself. GET requests are
using for sending smaller amounts of data that need not be secure.
POST requests can send large amounts of data. It also hides the data from being
visible when sent to a server program.

Cookie:A cookie is a small amount of data which is stored in the web browser and
transferred between requests and responses through HTTP headers.

Cookie Class:The Cookie class encapsulates a cookie. A cookie is stored on a client


and contains state information. Cookies are valuable for tracking user activities.
For example, assume that a user visits an online store. A cookie can save the
user’s name, address, and other information. The user does not need to enter this
data each time he or she visits the store.

Creation Of Cookie Object: The Constructor for creating a cookie object is of the
form:
Cookie cookieobject = new Cookie(String name, String value)

Here, the name and value of the cookie are supplied as arguments to the
constructor.
Example: Cookie c = new Cookie("userName","Chaitanya");

Set the maximum Age:


The setMaxAge () method specifies how long the cookie is stored in user’s
computer, in seconds. If not set, the cookie is deleted when the web browser
exits.
Example: cookie.setMaxAge(7 * 24 * 60 * 60);
This sets the cookie’s life is 7 days (= 24 hours x 60 minutes x 60 seconds) and it is
still stored on the user’s computer when the browser exists.

Place the Cookie in HTTP response header: A servlet can write a cookie to a
user’s machine via the addCookie( ) method of the HttpServletResponse
interface. The data for that cookie is then included in the header of the HTTP
response that is sent to the browser.
Syntax: response.addCookie(cookieobject);
Example: response.addCookie(c);
Index.html
<html>
<body>
<center>
<form name="form1" method="post"
action="http://localhost:8080/WebApplication7/AddCookieServlet">
<B>enter a value for my cookie:</B>
<input type=textbox name="data" size="25" value="">
<input type=submit value="submit">
</form>
</body>
</html>
AddCookieServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class AddCookieServlet extends HttpServlet
{
public void doPost(HttpServletRequest req,HttpServletResponse res)throws
ServletException,IOException
{
String data=req.getParameter("data");
Cookie cookie=new Cookie("mycookie",data);
res.addCookie(cookie);
res.setContentType("text/html");
PrintWriter pw=res.getWriter();
pw.println("<B>my cookie has been set to");
pw.println(data);
pw.close();
}
}

Session Tracking:
Session is basically a time frame and tracking means maintaining user data for
certain period of time frame. Session Tracking is a mechanism used by the web
container to store session information for a particular user. It is used to
recognize a particular user.
Methods of Session Tracking: There are four techniques used in Session
tracking
1) Cookies
2) Hidden Form Field
3) URL Rewriting
4) HttpSession
1)Cookies: Cookies are small piece of information sent by web server in
response header and gets stored in browser side. A web server can assign a
unique session ID to each web client. The cookies are used to maintain the
session. The client can disable the cookies.
The source code snippet to create a cookie:
Cookie cookie = new Cookie(“userID”, “7456”);
res.addCookie(cookie);
2) Hidden Form Field: The hidden form field is used to insert the
information in the webpages and this information is sent to the server.
These fields are not viewable to the user directly.
For example:
<input type = hidden'  name = 'session' value = '12345' >
is a hidden form field which will not displayed to the user but its value will be
send to the server and can be retrieved using
 request.getParameter(“session”)  in servlet.
3)URL Rewriting: URL rewriting is a technique used for session management. In
this approach, a web container generates a unique identifier called as SESSIONID
and appends to every URL in the page. When the URL is clicked, the browser
sends the SESSIONID back to the server which it uses to identify the client.

Original URL: http://server:port/servlet/ServletName
Rewritten URL: http://server:port/servlet/ServletName?sessionid=7456

4) HttpSession Object: The HttpSession object represents a user session.


The HttpSession interface creates a session between an HTTP client and HTTP
server. A user session contains information about the user across multiple
HTTP requests.

For example:
HttpSession session = request.getSession( );
session.setAttribute("username", "password");

HTML Forms
HTML is just a markup language, it has some basic elements and GUI components,
such as buttons, text fields, check boxes, and dropdown lists, that allow users to
enter data, make some selections, and submit requests to a remote server. For
example, the HTML <FORM> tag enables users to enter and submit data from a
Web page.
A <FORM> tag has important attributes such as action and method. The action
attribute contains the uniform resource locator (URL) of the server program to
which the browser should send the user’s input. The method attribute tells the
browser how to send the data; this attribute is usually either Get or Post, as
shown in the following example:
<form action= “http://www.mymagpublisher.com/servlet/LoginServlet”
method=Get>
A text field can be created as follows:
<input type=Text name=”id” >
The name of the text field will be passed by the browser to the servlet as a
parameter name.
The button that sends the data is of type Submit, and the button that clears all
fields is of type Reset:
<input type=”Submit”>
<input type=”Reset”>

JDBC is an application programming interface (JDBC API) that defines a set of


standard operations for interacting with relational database management
systems (DBMSs). JDBC drivers enable to open database connections and to
interact with it by sending SQL or database commands then receiving results
with Java.
JDBC Drivers Types:JDBC driver implementations vary because of the wide variety
of operating systems and hardware platforms in which Java operates. Sun has
divided the implementation types into four categories, Types 1, 2, 3, and 4.
Type 1: JDBC-ODBC Bridge Driver:In a Type 1 driver, a JDBC bridge is used to access
ODBC drivers installed on each client machine.

Type 2: JDBC-Native API:In a Type 2 driver, JDBC API calls are converted into native
C/C++ API calls, which are unique to the database. These drivers are typically
provided by the database vendors and used in the same manner as the JDBC-
ODBC Bridge. The vendor-specific driver must be installed on each client machine.
Type 3: JDBC-Net pure Java:In a Type 3 driver, a three-tier approach is used to
access databases. The JDBC clients use standard network sockets to communicate
with a middleware application server. The socket information is then translated
by the middleware application server into the call format required by the DBMS,
and forwarded to the database server.

Type 4: 100% Pure Java


In a Type 4 driver, a pure Java-based driver communicates directly with the
vendor's database through socket connection. This is the highest performance
driver available for the database and is usually provided by the vendor itself.
Using JDBC to Access Databases 
Using JDBC to access databases can be described in six steps.
i)load the JDBC driver for the DBMS
ii) to connect to the database;
iii)to create a statement
iv) to query the database using SQL Select statements;
v)to insert/delete/update data in the database.
vi)close all the resources, including ResultSet, Statement, and Connection, which
should be the last step of using JDBC.

Step 1: Load the JDBC drivers 


A Java program can load several JDBC drivers at time. This allows the program to
interact with more one database running under different DBMSs. The following
line of code loads the JDBC driver for PostgreSQL,     
    Class.forName("org.postgresql.Driver");  

Step 2: Connect to the database 


A connection to a database can be established via the getConnection method of
the DriverManager class. The getConnection method accepts three parameters --
the database, user name, and password.
   Connection db = DriverManager.getConnection( Url+dbname, usernm, passwd); 

Here, the url variable contains which JDBC driver is to used for this connection
and also which machine, by IP address, hosts the DBMS and the database.  

Step 3: Create a statement


A Statement object has the ability to parse SQL statements, send the SQL
statements to the DBMS, and accept the results returned from the DBMS.

    Statement st = db.createStatement(); 

Step 4 and 5: Interact with the database         


Normally, two operations of Statement are needed to interact with a database.
One is executeQuery(sql_select), which takes a SQL Select statement as its
argument, sends the Select to the DBMS, and returns the results as an object
of ResultSet. The other operation is executeUpdate(sql_insert_delete_update),
which takes a SQL statement (Insert, Delete, or Update), sends it to the DBMS.
Both operations throw a SQLException if the statement cannot be executed by
the DBMS successfully.

 String sql = "SELECT name, title " + "FROM faculty f, course c " +  "WHERE f.id =
c.instructor"; 
  ResultSet rs = st.executeQuery(sql);
String faculty = '123456';
  String sql = "INSERT INTO faculty VALUES (" + '" + faculty +    "', 'Dave Letterman',
'Estate 1942', '941-6108')";
 st.executeUpdate(sql);    

Step 6: Disconnect from the database


When the application completes or no further database interaction is needed,
you should return JDBC resources back to the system, which include, objects of
Statement, ResultSet, and Connection.

    rs.close();
    st.close(); 
Applet To Servlet Communication:
The java.net.URLConnection and java.net.URL classes are used to open a
standard HTTP connection and "tunnel" to the web server.
The server then passes this information to the servlet in the normal way.
Basically, the applet pretends to be a web browser, and the servlet doesn't know
the difference.
As far as the servlet is concerned, the applet is just another HTTP client.
The URLConnection contains both an input and an output stream. These streams
can then be used by the applet to transmit data to the servlet and receive data
back from it.
Apps.java
import java.awt.*;
import java.net.*;
import java.io.*;
import java.awt.event.*;
import java.applet.*;
import java.lang.*;
/*<applet code="Apps" width=400 height=460>
</applet>*/
public class Apps extends Applet implements
ActionListener
{
Button b;
TextField tf;
public void init()
{
b=new Button("call Servlet");
b.addActionListener(this);
add(b);tf=new TextField(25);
add(tf);
}
public void actionPerformed(ActionEvent ae)
{
try
{
URL u=new URL("http://localhost:8080/WebApplication11/Serv");
URLConnection urlc=u.openConnection();
InputStream isr=urlc.getInputStream();
BufferedReader br=new BufferedReader(new InputStreamReader(isr));
tf.setText(br.readLine());
}
catch (Exception e)
{
showStatus(e.toString());
}
}
}
Serv.java
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Serv extends HttpServlet
{
public void doGet(HttpServletRequest req,HttpServletResponse res)throws
IOException,ServletException
{
Date d=new Date();
PrintWriter out=res.getWriter();
out.println(d.toString());
}
}

You might also like