Professional Documents
Culture Documents
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.
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.
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>
Interface Description
HttpServletRequest The object of this interface is used to get the
information from the user under http protocol.
Class Description
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.
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");
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
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”>
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.
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.
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);
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());
}
}