Vous êtes sur la page 1sur 80

Web Servers and Servelets

Unit-IV

Servlets
Servlets are simple java programs
that run on servers.
Commonly used with HTTP, hence
the name HTTP Servlet
Make use of Java standard extension
classes in packages
- javax.servlet
- javax.servlet.http

Uses of Servlets
Process and store data submitted by HTML
form
Useful for retrieving and updating databases
Working is based on Request-Response
Used in Cookies and Session tracking
- Cookies are a message given to a Web
browser by a Web server. The browser stores the
message in a text file.
- Session tracking keeps track of all previously
accessed web pages

How Servlet Works?

How Servlet Works?


Client makes a request for some servlet
using Web Browser
The Web Browser then sends the request to
Web Server. The Web Server finds the
requested servlet
The obtained servlet gathers the relevant
information by clients request and builds a
Web Page
The Web page is displayed by clients
request

Web Servers
Communication with web servers
established with the help of web
browser
Examples of web browsers:
IE,Mozilla
Examples of web servers: Apache
web server, Microsoft IIS(Internet
Information Services)server

Web server Role

Web server Role


Client makes a request to web server by sending a
Uniform Resource Locator(URL)
URL is divided into 3 parts:
(a)First part of URL is Protocol Name(HTTP or FTP)
(b)Second part, name of web server is mentioned
Example: www.university.com
(c) Third part, Request for webpage is displayed.
Typically it is .html file
Web browser sends the GET request to web server.
Web Server sends HTML page to the Web browser

Deployment of Servlets
Writing the servlets is best choice for server side
programming
Servlets need a special environment for execution
i.e., Tomcat, a servlet container & open-source
product is recommended which contains class
libraries, documentation and runtime support which
is useful for executing and testing the servlets.
For execution of servlets,following software must be
installed
- JDK: As servlets are basically java files,JDK must be
installed
- Tomcat: servlet can be executed

JDSK
The Java Development Standard Edition Kit(JDSK) is
available from Sun Microsystems in order to develop
and deploy Java applications on desktop and servers
Installation : http://www.java.sun.com/j2se
After installation, important task is setting up of
environment variables
Steps: Control panel Click System Click Advanced
System Settings-Click Environment Variables
Set the path variable by mentioning the directory
C:\jdk1.06_4(your jdk directory)\bin.Click OK to save
settings.
Finally, go to cmd prompt and type javac

Tomcat Webserver

Tomcat installation : http://tomcat.apache.org


In configuration window, under Configuration Options setup, we can set the
connector port.
By default ,the port is 8080
We can also set the username and password for administrator login
After installation, we need to configure with environment variables
- Go to control panel-System Advanced tab
- Set the environmental variable i.e., Variable name : JAVA_HOME
- Set the environmental variable i.e., Variable value : your_jdk_directory
(
C: \jdk1.6.0_04 )
Again , Set the environmental variable i.e., Variable name : CATALINA_HOME
Set the environmental variable i.e., Variable value : your_tomcat_bin
directory
C:\Tomcat5.5\apache-tomcat-5.5.27\bin)
Now,you can start tomcat server by clicking on startup.bat batch file
in( C:\Tomcat5.5\apache-tomcat-5.5.27\bin)

The Servlet API


Servlet API consists of Classes and
Interfaces
Classes and Interfaces come in two
packages
- javax.servlet Protocol independent
classes and interfaces exist
- javax.servlet.http HTTP specific
classes and interfaces exist

The javax.servlet package


Interfaces
Interface

Description

Servlet

It defines all life cycle methods.


The method such as
init(),service() and destroy() are
called by server in servlet
interface

ServletConfig

It obtains the initialization


parameters i.e., When the servlet
is loaded, the related
configuration is acquired

ServletContext

Events Can be logged using this


interface

ServletRequest

It is useful in reading data from


client request

ServletResponse

It is useful to make response to


the client

The Servlet Interface


Method

Description

Void init(ServletConfig s) Throws


ServletException

This method is called for


initialising the servlet
It can be obtained from
ServletConfig interface.
If the servlet is not initialized,
then an Exception is thrown

Void destroy()

This method is called when the


servlet has to be unloaded

ServletConfig getServletConfig()

This method is used to obtain the


initialisation parameters

Void Service(ServletRequest
req,Servlet Response res) Throws
Servlet Exception,IO Exception

This method is called to respond


to a request that is sent by client.
An Exception is thrown, whenever
a servlet problem occurs

String getServletInfo()

This method is used to obtain


description of servlet

The ServletConfig Interface


Method

Description

String getServletName()

This method is used to obtain the


name of servlet

String getInitParameter(String p)

This method returns the


initilization parameter value p

Enumeration
getinitParamernames()

This method returns the names of


initialisation parameters

ServletContext
getServletContext()

This method returns the available


context for the servlet

The ServletContext
Interface
Method

Description

Object getAttribute(String
Attribute_name)

This method returns the attribute


value

Void setAttribute(String
attribut_name,object value)

The attribute_name is passed to


the object value

String getServerInfo()

This method returns the


information about the server

String log(String str)

Writes the str to the servlet log

String getMimeType(String file)

It returns the MIME type of file

The ServletRequest
Interface
Method

Description

Object getAttribute(String
Attribute_name)

This method returns the attribute


value

Int getContentlength()

It returns the content size of


request

String getContentType()

It returns the type of request and


if not determined,null value is
returned

getInputStream()

This method is used to read the


binary data from the request

getProtocol()

Returns the name of the protocol


used

getReader()

Useful for reading the text from


request

getServerName()

Returns the name of server on


which servlet is running

The ServletResponse
Interface
Method

Description

String getCharacterEncoding()

This method returns the character


encoding

ServletOutput Stream get


OutputStream()

Returns output stream which is


used to write data for responding

PrintWriter getWriter()

This method is used to write the


character data to the response

void setContentLength(int size)

Sets the length of the content to


equal size

void setContentType(String Type)

Sets the type of content

javax.servlet package
Classes
Class

Package

GenericServlet

This class implements the


Servlet and ServletConfig
interfaces

ServletContextAttribute Event

This class is an event class for


notifying the changes that occur
in ServletContext attribute
(a)getName() This method
returns the changed name of
ServletContext attribute
(b)getValue() This method
returns the changed value of
ServletContext attribute

javax.servlet package
Classes
Class

Description

ServletInputStream

This class provides the input


stream for reading the clients
request

ServletOutputStream

This class provides the output


stream for writing the clients
response

ServletException

This class is used to raise the


exception which indicates that a
servlet error has occurred

Unavailable Exception

This class returns the exception


when a servlet is unavailable

javax.servlet.http package
Interfaces
Interface

Description

HttpSession

The session data can be read or


written using this interface

HttpServerRequest

The servlet can read the


information from the HTTP
request using this interface

HttpServerResponse

The servlet can write the data to


HTTP response using this
interface

HttpSessionBindingListener

This interface tells the object


about its binding with the
particular session

The Http Session

The servlet can read or write the information using


HTTPSession interface
Various
methods used by this interface:
Method
Description
String getId()

This method returns session ID

Object getAttribute(String
attribute_name)

Attribute_name value is
returned

Enumeration
getAttributeNames()

Returns the attribute names

The HttpServlet Request

The HttpServlet Request is used to obtain the information


from clients HTTP request
Various Methods:
Method

Description

String getMethod()

It returns HTTP method for client


request

String getPathInfo()

Returns the path information


about servlet path

HttpSession getSession()

Returns the current session

String getHeader(string fields)

It returns the value of header


fields

Cookie [ ] getCookies()

It returns the information in the


cookies in the request made

String getAuth Type()

It returns the type of


Authentication

The HttpServlet Response

The HTTPServlet Response is used to formulate an HTTP


response to client.
Various methods:
Method

Description

Void addCookie(Cookie cookie)

Used to add cookie in the


response

String encodeURL(String url)

Used to encode the specified


URL

Boolean containsHeader(String Returns true if the resonse


f)
header contains f
Void sendError(int code)

Sends error code to the client

void setContentType(String
Type)

Sets the type of content

The HttpSessionBinding
Listener

When particular listener gets bound or unbound from a


value within HttpSession object,then this class is required
Various Methods:
Method

Description

Object getValue()

This function returns the value


of bounded or unbounded
attribute

String getName()

This function returns the name


being bounded or unbounded

HttpSession getSession()

This function returns the


session to which the listener
can be bound or unbound

javax.servlet.http package
Classes
Class
Description
Cookie

Used to write cookies

HttpServlet

Used when developing servlets


that receive and process HTTP
requests

HttpSessionEvent

Used to handle the session


events

HttpSessionBindingEvent

When a listener is bound to a


value

The Cookie class

Cookie is small piece of information that is stored in clients


machine
Sometimes cookies are useful to keep track of the user
using client machine
Various
ClassMethods:
Description
String getValue()

Returns a value of cookie

Void setValue(String s)

Sets tha value to the cookie

String getName()

Returns the name

The HttpServlet Class

The HttpServlet class extends GenericServlet


Used when developing servlets that receive and process
HTTP requests
Various methods:
Class

Description

Void doGet(HttpServletRequest
req,HttpServletResponse res)

Performs HTTP get request

Void doPost(HttpServletRequest
req,HttpServletResponse res)

Performs HTTP Post request

Void doPut(HttpServletRequest
req,HttpServletResponse res)

Performs HTTP Put request

Void service(HttpServletRequest Invoked for processing HTTP


req,HttpServletResponse res)
request and response

Http Session Event &


HttpSessionBindingEvent Classes
The HttpSessionEvent:
Used to encapsulate the session event

HttpSessionBindingEvent:
Same as HttpSessionBindingListener

When particular listener gets bound or unbound


from a value within HttpSession object,then this
class is required

Architecture of Servlet
I/O Operations
import java.io.*;
import javax.servlet.*;
Contains Interfaces and
import javax.servlet.http.*;
Classes for Servlet Operation
public class FirstServlet extends HttpServlet
Used when developing servlets
{
that receive and process HTTP
requests
public void doGet(HttpServletRequest request,HttpServletResponse
response)
throws ServletException,IOException
Performs HTTP Get
{
request
Commonly Used Basic
response.setContentType("text/html");
Exceptions for servlets
PrintWriter out=response.getWriter();
servlet contains data in text
form and browser should
out.println("<html>");
interpret the contents as
out.println("<head>");
HTML source code
out.println("<title>My First Servlet</title>");
out.println("<body>");
getwriter()method which
out.println("<h1>Hello</h1>");
helps to display messages
out.println("<h2>How are You</h2>");
out.println("</body>");
out.println("</html>");
}
}

Architecture of Servlet

java.io package I/O Operations


javax.servlet & javax.servlet.http packages Contains
Interfaces and Classes required for operation of servlet
Servlet class Firstservlet is inherited from class
HttpServlet as it supports the methods like doGet and
doPost
Commonly Used Basic Exceptions for servlets are
IOException and ServletException
setContentType specifies that the servlet contains data in
text form and browser should interpret the contents as
HTML source code. So, text/html is specified
Output stream is created using PrintWriter() & The
getwriter()method which helps to display messages

Architecture of Servlet

Most Commonly Used Interfaces from java.servlet


package are Servlet,ServletRequest and
ServletResponse
Most Commonly Used Class from java.servlet
package is GenericServlet
Most Commonly Used Interfaces from
java.servlet.http package are
HttpServletRequest and HttpServletResponse
Most Commonly Used Classes from
java.servlet.http package are Cookie and
HttpServlet

How to Execute Servlet


Set the CLASSPATH using environmental
variable
Type javac FirstServlet.java n cmd prompt
The class file FirstServlet.class gets generated
by this method
Copy FirstServlet.class file to directory
Example - C:\Tomcat 5.5\apache-tomcat5.5.27\webapps\servlets-examples\WEB-INF\classes

Open the web.xml file present in the directory


Example - C:\Tomcat 5.5\apache-tomcat5.5.27\webapps\servlets-examples\WEB-INF

How to Execute Servlet


Add the following statements in web.xml file
<servlet>
<servlet-name>FirstServlet</servlet-name>
<servlet-class>FirstServlet</servlet-class>
<servlet>
...
<servlet-mapping>
<servlet-name>FirstServlet</servlet-name>
<url-pattern>/servlet/FirstServlet</url-pattern>
<servlet-mapping>
Start the Tomcat by clicking on startup.bat
Open web browser and type URL:
http://localhost:4040/servletsexamples/servlet/FirstServlet and Ouptput is Generated

Life Cycle of Servlet

To initialize your servlet


before handling any
clients request

Request
Web
browser

Response

The servlet is initialized by calling the


init () method.
The servlet calls service() method to
process a client's request.
The servlet is terminated by calling the
destroy() method.

init

Service

Destroy

To
determine
which HTTP
method
should be
called
This method
gives your
servlet a
chance to
close
database
connections,
halt
background
threads i.e.,
to cleanup
activities

Life Cycle of Servlet


Client enters the URL in the web browser
and makes a request in which it generates
HTTP request and sends it to the Webserver
Server invokes the init() method and is
called,only,when the servlet is loaded in
memory for first time
Server can invoke the service for particular
HTTP request using service() method
Finally server unloads the servlet from the
memory using the destroy() method

Java Program[LifeCycle.java]

import java.io.*;
This class implements the Servlet
import javax.servlet.*;
and ServletConfig interfaces
import javax.servlet.http.*;
public class LifeCycle extends GenericServlet
Used an init() method to
{
which object of
public void init(ServletConfig config) throws ServletException ServletConfig interface
is passed
{
This interface allows the
System.out.println("init");
servlet to get the
}
initialization parameters
public void service(ServletRequest request,ServletResponse response)
throws ServletException,IO Exception
{
System.out.println("from service");
service() method is used to
PrintWriter out=response.getWriter();
ServletRequest and
out.println("Hello,How are you");
ServletResponse parameters
out.print("I'm good,Thanks");
are passed for making HTTP
request and getting HTTP
}
response from servlet
public void destroy()
Destroy()
{
function is
System.out.println("destroy");
written in order
}
to unload the
}

servlet from
memory

Handling HTTP Request and


Responses
We know that client makes request to server using HTTP protocol
There is HttpServlet class in which there are some special
methods which can be used to handle HTTP requests
The methods are:
(a)doDelete()
(b)doGet()
(c)doHead()
(d)doOption()
(e)doPost()
(f) doPut()
(g)doTrace()
For handling the input, HTTP request makes use of two commonly
used methods such as GET and POST

HTTP-GET & HTTP-POST


Request
In HTTP-GET request,doGET method is
used
In HTTP-POST request,doPOST method
is used
When User submits his request using
doGET method, then the URL string
displays the request submitted by the user
If doPOST method is used, then URL string
doesn't show the submitted contents

Handling HTTP-GET Request


We will learn how to write the servlet
which handles GET request in which
it invoked from HTML form.
Two Programs
- HTML script in which servlet is
invoked
- Servlet Program

HTML Program
<html>
<body>
<center>
<form name=form1 method=GETaction=http://localhost:4040/servletsexamples/servlet/my_choiceservlet>
<b>Fruit:</b>
1)The action
<select name="Fruit" size="1">
parameter specifies
<option value="Apple">Apple</option>
the servlet name
<option value="Mango">Mango</option>
which is to be invoked
<option value="Banana">Banana</option>
2) The action is
<option value="Strawberry">Strawberry</option>
specified as GET, i.e.,
</select>
GET request is made
<br><br>
by HTML to servlet
<input type="submit" value="submit">
</form>
</center>
</body>
</html>

Servlet
Program[my_choiceservlet.java
]

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class my_choiceservlet extends HttpServlet
{
public void doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException
{
String Fruit=req.getParameter("Fruit");
res.setContentType("text/html");
PrintWriter out=res.getWriter();
out.println("<b>Done!!! ");
out.println("You have choosen "+Fruit);
out.close();
}
}

Servlet
Program[my_choiceservlet.java
]
Servlet class my_choiceservlet is inherited from class

HttpServlet as it supports the methods like doGet and


doPost
Dont forget to throw Exceptions IOException and
ServletException for handling Exceptional cases
getParamater method is invoked in which parameter
Fruit is passed
setContentType specifies that the servlet contains data
in text form and browser should interpret the contents
as HTML source code. So, text/html is specified
Output stream is created using PrintWriter() .The
getwriter()method which helps to display messages

Handling HTTP-Post Request


Similar to GET request, we can
handle POST request by two
programs
- HTML program in which request is
made
- Servlet program by which the
POST request can be handled

Handling HTTP-POST Request


<html>
<body>
<center>
<form name=form1 method=post
action=http://localhost:4040/servletsexamples/servlet/my_choiceservlet1>
<b>Fruit:</b>
<select name="Fruit" size="1">
<option value="Apple">Apple</option>
1)Only change is
<option value="Mango">Mango</option>
method=Post in the
<option value="Banana">Banana</option>
form tag
<option value="Strawberry">Strawberry</option>
2)Servlet named as
</select>
my_choiceservlet1
<br><br>
<input type="submit" value="submit">
</form>
</center>
</body>
</html>

Servlet Program[my_choiceservlet1.java]
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class my_choiceservlet1 extends HttpServlet
{
public void doPost(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException
{
String Fruit=req.getParameter("Fruit");
res.setContentType("text/html");
PrintWriter out=res.getWriter();
out.println("<b>Done!!! ");
out.println("You have choosen "+Fruit);
out.close();
}
}

Session Tracking
Client 1

Client 2

S
E
R
V
E
R

Fig : Client(s) and Session


Relationship

Session
1

Session
2

One-One
relationship
between a client
and session i.e,
Particular
session
maintains an
identity and
state of
particular client
across multiple
HTTP requests

Session Tracking
Mechanism to maintain state across a series of
requests from the same browser
Ex: Selecting items in Online shopping cart
Each time a client sends requests a web server, it
opens new connection
Web based applications are responsible for
maintaining such state, called as Session

Session Tracking Techniques


Session Tracking Technique is a
mechanism by which we can keep track
of previous sessions between server
and browser
It can be done by three techniques:
(a)Use of cookies
(b)Embedding hidden fields in an HTML form
(c)Sending URL string in response body
Session ID is used while accessing the
information between browser and server

Use of cookies

Suppose we want to access web page


http://www.mywebpage.com/introduction.html, then the browser
connects to the server www.mywebpage.com by making a request

GET

/introduction.html

HOST
Browser

Requests

HTTP P.1

www.mywebpage.com
Server

The server then replies in the form of HTTP response. This packet
contains a line requesting browser to store cookies
Using set-cookie statement, server is requesting browser to store the
sid=xf1234ad

HTTP P.1
Set-Cookie :

Browser

Response

200 OK
sid=xf1234ad

Server

Use of cookies
GET

/Chapter1.html

HOST
Cookie

HTTP P.1

www.mywebpage.com
sid=xf1234ad

Browser
Request
Server
This is another request to the same server. By including
cookies which contain sid=xf1234ad server knows that this
request is related to previous request.
In this way, server-browser can keep track of current session

Hidden Form Field

In this method, when browser makes a request to the


server for webpage, then server responds by inserting
hidden from fields in html page, and then sending that page
to browser
GET

/introduction.html

HOST
Browser

www.mywebpage.com
Request

HTTP P.1

Browser

HTTP 1.1

Server
200 OK

<html>
<form action = introduction.html
method=post>
<input type = hidden
Name = sid
value = xf1234ad
.... <!----Content of Page--
</html>
Response

Server

Hidden Form Field


The hidden contents will not be displayed on web
browser
GET

/Chapter1.html

HTTP P.1

sid=xf1234ad

Browser

Request

Server

By hidden field sid=xf1234ad,server will come to


know that the request is previous request
When new session will start,new session id will be
set as hidden field

URL Rewriting

This is a technique in which information is embedded into


URL
GET

/introduction.html

HOST

www.mywebpage.com

Browser
Server

Request
HTTP P.1

HTTP 1.1

200 OK

<html>
The server then responds
by putting sid=xf1234ad in
<form action = introduction.html method=post>
response body
<input type = hidden
Name = sid
value = xf1234ad
.... <!----Content of Page--
</html>

Browser

Response

Serve

URL Rewriting

The browser will demand for the required webpage by


inserting the same URL string in the request
GET
Browser

/introduction.html
HTTP/1.1
Request

sid=xf1234ad
Server

When browser makes requests for another page same URL


is embedded
Server comes to know that the request is related to
previous page and the work in same session will get corelated

Session Tracking Example


// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
// Extend HttpServlet class
public class SessionTrack extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
// Create a session object if it is already not created.
HttpSession session = request.getSession(true);
// Get session creation time.
Date createTime = new Date(session.getCreationTime());
// Get last access time of this web page.
Date lastAccessTime = new Date(session.getLastAccessedTime());
String title = "Welcome Back to my website";

Session Tracking Example(Contd..)


Integer visitCount = new Integer(0);
String visitCountKey = new String("visitCount");
String userIDKey = new String("userID");
String userID = new String("ABCD");
// Check if this is new comer on your web page.
if (session.isNew()){
title = "Welcome to my website";
session.setAttribute(userIDKey, userID);
} else {
visitCount = (Integer)session.getAttribute(visitCountKey);
visitCount = visitCount + 1;
userID = (String)session.getAttribute(userIDKey);
}
session.setAttribute(visitCountKey, visitCount);
// Set response content type
response.setContentType("text/html");
PrintWriter out = response.getWriter();

Session Tracking Example(Contd..)


String docType = "<!doctype html public \"-//w3c//dtd html 4.0 " +
"transitional//en\">\n";
out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<body bgcolor=\"#f0f0f0\">\n" +
"<h1 align=\"center\">" + title + "</h1>\n" +
"<h2 align=\"center\">Session Infomation</h2>\n" +
"<table border=\"1\" align=\"center\">\n" +
"<tr bgcolor=\"#949494\">\n" +
" <th>Session info</th><th>value</th></tr>\n" +
"<tr>\n" +
" <td>id</td>\n" +
" <td>" + session.getId() + "</td></tr>\n" +
"<tr>\n" +
" <td>Creation Time</td>\n" +
" <td>" + createTime +
" </td></tr>\n" +
"<tr>\n" +

Session Tracking Example(Contd..)


" <td>Time of Last Access</td>\n" +
" <td>" + lastAccessTime +
" </td></tr>\n" +
"<tr>\n" +
" <td>User ID</td>\n" +
" <td>" + userID +
" </td></tr>\n" +
"<tr>\n" + " <td>Number of visits</td>\n" +
" <td>" + visitCount + "</td></tr>\n" +
"</table>\n
+ "</body></html>");
Compile servlet SessionTrack and
}
create appropriate entry in web.xml file.
Now running
}
http://localhost:8080/SessionTrack
would display the result when you would
run for the first time

Session Tracking Output

Cookies

Cookies are little information that can be left on computer


when we access an Internet
For applications like online-purchase systems, once you
enter personal information such as your name or e-mail ID,
then it can be remembered by the system with the help of
cookies
Three programs:
- Simple HTML form in which servlet is invoked
- This servelt creates a cookie named mycookieservlet and
stores the value entered by you in the textbox of HTML
form
- The other servlet program named getCookieServlet
which helps us to view the cookie

HTML form
<html>
<head>
<title>Demo of Cookie</title>
</head>
<body>
<form name=form1 method=post
action=http://localhost:8080/examples/servlet/mycooki
eservlet>
<h3>Enter the value for my Cookie:</h3>
<input type= text name=txt_data size=30 value= >
<input type=submit value=submit>
</form>
</body>
</html>

Servlet Program[mycookieservlet.java]
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class mycookieservlet extends HttpServlet
{
public void doPost(HtttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException
{
String txt_data = req.getParamater(txt_data);
//Create cookie
Cookie cookie = new Cookie(My_Cookie,txt_data);
// Adding cookie to HTTP response
res.addCookie(cookie);
//Write friendly output to browser
Res.setContentType(text/html)
PrintWriter out=response.getWriter();
out.println(<h2>MyCookie has been set to:");
out.println(txt_data);
out.println(<br> <br> <br>);
out.println(This page shows that the cookie has been added);
out.close();
}
}

Servlet Program[getcookieserlet.java]
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class getcookieservlet extends HttpServlet
{
public void doGet(HtttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException
{
Cookie[ ] my_cookies = req.getCookies();
res.setContentType(text/html)
PrintWriter out=res.getWriter();
out.println(<b>);
int n = my_cookies.length;
for(int i=0;i<n;i++)
{
String name=my_cookies[i].getName();
String value=my_cookies[i].getValue();
out.println(name=+name);
out.println(and value=+value);
}
out.close();
}
}

Security Issues
Two important security issues:
(a)Use of Cookies - Personal information can
be accessed by other computer using
cookies
(b)Use of doGet request: Using doGet()
method, if HTML page sends some
information to servlet, then it is visible in
browser
If we develop login page, avoiding use of
doGet method, then username and
password will be visible in browser

Model View Controller(MVC)


Modelviewcontroller (MVC) is a software architectural pattern for
implementing user interfaces. It divides a given software application
into three interconnected parts
Aim: To separate the business logic and application data from the
presentation data to the user.
Model: - Knows about all the data that need to be displayed
- Only represents the data of an application i.e., enterprise data and the
business rules that govern access to and updates of this data.
- Not aware about the presentation data and how that data will be displayed
to the browser.
View: - Represents the presentation of the application
- Uses the query methods of the Model to obtain the contents and renders it
- Responsibility to maintain the consistency in its presentation when the
Model changes.
Controller: - Responsible for intercepting the requests from View and
passes it to the Model for the appropriate action
- After the action has been taken on the data, the Controller is responsible for
directing the appropriate view to the user

MVC Architecture

Knows about all the data that need to be


displayed
Not aware about the presentation data and
how that data will be displayed to the
browser
Response to Client queries

MODEL
(Business logic
and Processing)

Querie
s

Change
Notificatio
n

VIEW
(User Interface)

Changes

View Selection

Represents the presentation of the User


application
Responses
Uses the query methods of the
Model to obtain the contents
Responsibility to maintain the
consistency in its presentation when
the Model changes
Allows Controller Select View

CONTROLLER
(Navigation and
input)

Responsible for intercepting the


requests from View and passes it to
the Model for the appropriate action
After the action has been taken on the
data, the Controller is responsible for
directing the appropriate view to the
user
Selects view for response

MVC Architecture

Advantages of MVC
Focus on Developer specialization
Allows separate teams to implement
project development
Reusability of business logic across
applications
Allows development User Interfaces
separate from business logic

Structure and Deployment of


Application)

Web Server: TOMCAT


Web application Development using Tomcat(Structure of Web Application)
A web application is a collection of static HTML pages, dynamic JSPs and
Servlet classes.
User Interfaces
(Collects Inputs from user)

.html
files
.jsp
files

Validates Inputs dynamically


.class
files

Web server: links all the files,


processes, and Produces results

Web application is defined as a hierarchy of directories and files in a standard


layout.
This hierarchy can be accessed in Two ways:
Unpacked each directory and file exists in the file system separately.
Packed form like Web Archive or RAR file. It is useful for distribution
of the web application and executing at various locations

Web Server: TOMCAT


Setting up a New Web Application:
To set up a new web application( or Servlet) with Tomcat, you need to add a directory
under the webapps dir and create a subdirectory called WEB-INF.
WEB-INF needs to contain a web.xml file ( a Tomcat/servlet configuration file).
Make sure you are consistent in the way you use upper case and lower case in your
directory names.
The easiest thing to do is to make a copy of the webdav directory and give it a new name.
After the WEB-INF directory is created, create a subdirectory under it called classes.
Your Java Package/classes will go under this directory.

72

Structure of Web Application

Structure of Web Application


Application Root Directory Root directory of the Web Application.
The name of this directory is named by the
developer - for example the default context we
created for this module was called "student".All JSP,
HTML and image files are stored here. Typically,
there would be an index.html or index.jsp file in this
directory.
The "other directories" could be, for example,
"images" (containing gifs and jpgs for the html
pages and servlets used in the Application), "style"
(containing the .css or other style files used) or
simply subdirectories of HTML or JSP pages.

Structure of Web Application


/WEB-INF- This directory contains all resources related to the
application that are not in the document root of the application.
It should be noted that the WEB-INF directory is not part of the
public document (ie. paths beginning in
http://localhost:8080/student/WEB-INF cannot be viewed in a
browser) and no files contained in this directory can be served
directly to the client.
The WEB-INF directory also contains theWeb Application
Deployment Descriptor.
/WEB-INF/classes- contains the application Java Servlets, class
files, JavaBeans and utility classes.
/WEB-INF/lib- The lib directory contains the Java ARchive (JAR)
files (or ZIP) that the web application depends upon. For
example, this directory might contain a JDBC Database
Connectivity driver in JAR or Zip format.
/WEB-INF/web.xml- The deployment descriptor is an XML file
named web.xml and forms the heart of the Web Application.

How Servlet Works?

76

How Servlet Works?

Client makes a request for some servlet using Web Browser

The Web Browser then sends the request to Web Server. The Web Server finds
the requested servlet

The obtained servlet gathers the relevant information by clients request and
builds a Web Page

The Web page is displayed by clients request

77

Deployment of Servlets

Writing the servlets is best choice for server side programming

Servlets need a special environment for execution i.e., Tomcat, a servlet


container & open-source product is recommended which contains class
libraries, documentation and runtime support which is useful for executing and
testing the servlets.

For execution of servlets, following software must be installed


JDK: As servlets are basically java files, JDK must be installed
Tomcat: servlet can be executed

78

JDSK
The Java Development Standard Edition Kit(JDSK) is
available from Sun Microsystems in order to develop
and deploy Java applications on desktop and servers
Installation : http://www.java.sun.com/j2se
After installation, important task is setting up of
environment variables
Steps: Control panel Click System Click Advanced
System Settings-Click Environment Variables
Set the path variable by mentioning the directory
C:\jdk1.06_4(your jdk directory)\bin.Click OK to save
settings.
Finally, go to cmd prompt and type javac

Tomcat Webserver

Tomcat installation : http://tomcat.apache.org


In configuration window, under Configuration Options setup, we can set the
connector port.
By default ,the port is 8080
We can also set the username and password for administrator login
After installation, we need to configure with environment variables
- Go to control panel-System Advanced tab
- Set the environmental variable i.e., Variable name : JAVA_HOME
- Set the environmental variable i.e., Variable value : your_jdk_directory
(
C: \jdk1.6.0_04 )
Again , Set the environmental variable i.e., Variable name : CATALINA_HOME
Set the environmental variable i.e., Variable value : your_tomcat_bin
directory
C:\Tomcat5.5\apache-tomcat-5.5.27\bin)
Now,you can start tomcat server by clicking on startup.bat batch file
in( C:\Tomcat5.5\apache-tomcat-5.5.27\bin)

Vous aimerez peut-être aussi