Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 70

CGI programming

• When a web server receives a request from a browser it


passes it to the CGI program.
• The CGI program processes the request and generates a
response at runtime.
• CGI programs can be written in any language, but Perl is
the most popular choice
Web Server Host

send a request URL

Web Browser Web Host Machine File System


Server
HTML page returned

spawn CGI process


generate response

Execute CGI
Program
get CGI code
Difference b/w CGI & Servlets
• CGI is extremely slow when handling a
large number of requests simultaneously,
because the web server must spawn a
process for executing each CGI program.
• Java servlets were developed to remedy
the performance problem of CGI
programs. Java servlets are basically
Java programs that behave like CGI
programs.
Difference between servlets and CGI
• Efficient, Convenient, Powerful, Portable,
Secure, Inexpensive
– Lightweight threads instead of OS threads created
– Single copy of code brought into memory for all
threads versus per thread
– Data (session state) can be stored across threads
within servlet container
– Java is portable and secure
– Requires little expense once servlet container
integrated with web server
• In CGI for each request the server creates one
process, whereas in Servlet for all the requests
the server creates only one process but multiple
threads.
Java Servlets
• Java servlets are executed upon request from a web
browser.
• All servlets execute inside a servlet container, also
referred to as a servlet server or a servlet engine.
• A servlet container is a single process that runs a JVM
(Java Virtual Machine).
• The JVM creates a thread to handle each servlet (recall
that threads have considerably less overhead than full-
blown processes).
• All the threads share the same memory allocated to the
JVM.
• The server that executes a servlet is referred to as
the servlet container or servlet engine.
• We’ll look at servlets that implement
the request-response model between
clients and servers using the HTTP
protocol. This architecture is shown
in the diagram below.
• A client application sends an
HTTP request to the server.
• The servlet container receives
the request and directs it to be
processed by the appropriate
servlet.
• The servlet does its processing,
which may include interacting
with a database or other
server-side components, such
as other servlets or JSPs.
• The servlet returns its results to
the client – normally in the form
of an HTML, XHTML, or XML
document to display in a
browser.
Skelton Structure of Servlets
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public lcass hi extends GenericServlet\
{
public void init(ServletConfig sc) throws ServletException;
{
}
void service(ServletRequest req,ServletResponse res)
throws ServletException,IOException;
void destroy();
}
Setting up Tomcat
• Tomcat is a fully functional implementation of
servlets and JSP. It includes a Web server, so it
can be used as a standalone test container for
servlets and JSPs.
• After the Tomcat is installed you’re ready to run
a demonstration test that will tell you if you’ve got
everything set-up properly.
• During the install, Tomcat will ask you which TCP
port Tomcat should run on. To avoid any conflict
with standard Web servers which default to TCP
port 80, Tomcat is set to default to TCP port
8080. If you have any other service running on
this port change the port number at this time to
one on which no conflict will occur.
Starting Up Tomcat

1.Start Tomcat running.


2.Start your Web browser.
3.Enter URL: http://localhost:8080
4.You should see the screen on the
following page if everything is set up ok.
A Tour of Tomcat, Directory structure
• Closer look at Tomcat which will help us better understand
how web applications are developed and deployed.
Logs:The logs directory contains a number of log files created by Tomcat. The file
catalina.out contains anything written to System.out and System.err, as well as
information relevant to the server as a whole.
Common:This directory contains three subdirectories – classes, lib, and endorsed – which
contain code used by Tomcat. The classes directory is effectively added to the
CLASSPATH, as are any jar files in lib and endorsed. Any custom jar files that may be
needed throughout Tomcat, such as a JDBC driver, are placed in these directories.
Bin:Directory bin contains scripts for starting and stopping Tomcat as well as
some additional tools.
Conf: Directory conf contains files used to configure Tomcat at the global level,
although it is possible for each web application to override many of the values
provided in this directory.
Server:This directory contains three subdirectories – classes, lib, and endorsed –
which contain code used by Tomcat. The classes directory is effectively added to
the CLASSPATH, as are any jar files in lib and endorsed. Any custom jar files that
may be needed throughout Tomcat, such as a JDBC driver, are placed in these
directories.
Shared:This is another directory containing classes and lib subdirectories. The
classes and jars within these directories are available to all web applications but will
not be available to the server infrastructure.
Webapps :This directory contains all the web applications Tomcat is configured to run,
one web application per subdirectory. We will be placing the web applications that
we develop into subdirectories in this directory. We’ll look in more detail at the
structure of these subdirectories a bit later.
Work:This directory is used by Tomcat to hold servlets that are built from JSP pages.
Users will typically not need anything in this directory.
Temp:This directory is used internally by Tomcat and can be ignored.
SERVLET INTERFACE
• The servlet packages define two abstract classes
that implement interface Servlet
• class GenericServlet
• (from the package javax.servlet) and

• class HttpServlet
(from the package javax.servlet.http).

• The GenericServlet is a protocol-indpendent


servlet, while the HttpServlet uses the HTTP
protocol to exchange information between the client
and server.
• If a problem occurs during the execution of a servlet,
either ServletExceptions or IOExceptions are
thrown to indicate the problem.
Servelet package framework
Generic Servlets
Httpservlet
Life cycle of Servlet
Step1: The Servlet container loads the Servlet class
that we developed and deployed into it. This can be
happen at the time of the first client request or at the
time of application startup.
Step2: the Servlet container creates the instance of the
just loaded servlet class
Step3:The Servlet engine creates the instance of some
chile class of ServletConfig interface. This child class
implementation changes from container to container.
This instance contains initialization information and
application/container context information.
Step4: Servlet container calls the init method on the
Servlet instance. While calling, it supplies the
reference of ServletConfig type to this method. This
reference refers to the object created in step three.
We can use this reference to retrieve the initialization
and context information.
Step5:
Servlet engine creates two instances basing upon the client
request. These two instances are container implemented
some child classes of ServletRequest interface and
ServletResponse interface respectively.
Step6:
Servlet container calls the service method on the Servlet
instance. While calling this method, container supplies the
references of type ServletRequest and ServletResponse
to this method. These references refer to the objects
constructed in step five. By using these two references,
client request processing code can be implemented.
Step7:
If the server receives another client request, process starts
from Step 5 again.
Step8:
When the container is instructed to keep the Servlet out of
service, container calls the destroy method just before the
Servlet instance is garbage collected.
HttpServlet Life Cycle
GenericServlet cannot provide the complete http functionality required for
our servlets. That is the reason we always use the HttpServlet class to be
extended to our servlet class.
Step1:
The Servlet container loads the Servlet class that we developed and
deployed into it. This can be happen at the time of the first client request
or at the time of application startup.
Step2:
the Servlet container creates the instance of the just loaded servlet class
Step3:
The Servlet engine creates the instance of some chile class of ServletConfig
interface. This child class implementation changes from container to
container. This instance contains initialization information and
application/container context information.
Step4:
Servlet container calls the init method on the Servlet instance. While calling, it
supplies the reference of ServletConfig type to this method. This reference
refers to the object created in step three. We can use this reference to
retrieve the initialization and context information.
Step5:
Servlet engine creates two instances basing upon the client request. These two
instances are container implemented some child classes of ServletRequest
interface and ServletResponse interface respectively.
Step6:
Servlet container calls the service method on the Servlet instance. While calling
this method, container supplies the references of type ServletRequest and
ServletResponse to this method. The request object becomes
HttpServletRequest and the response object becomes HttpServletResponse
object.
Step7:
Within the service method a call is made to the protected service method. The
arguments supplied to this method are HttpServletRequest object and
HttpServletResponse object. The default functionality of this method is to
calibrate the in coming http request type(GET/POST). Basing on the request
type this method calls either doGet method or doPost method on the Servlet
instance
Step 8:
In HttpServlet we always write our application logic either in the doGet() or
doPost(). If the server receives another client request, process starts from
Step 5 again.
Step 9:
When the container is instructed to keep the Servlet out of service, container
calls the destroy method just before the Servlet instance is garbage
collected.
Application Directory Structure
ROOT DIRECTORY
html/jsp/image files
WEB-INF DIRECTORY
web.xml page
CLASSES DIRECTORY

LIB DIRECTORY
Simple Servlet

• To become familiar with the key servlet


concepts, we will begin by building and testing
• a simple servlet. The basic steps are the
following:
1. Create and compile the servlet source code.
2. Start Tomcat.
3. Start a Web browser and request the servlet.
web.xml
<servlet>
<servlet-name>hello</servlet-name>
<servlet-class>HelloServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
</web-app>
javax.Servlet package
The servlet package consisting of
Servlet interface

• Servlet interface
ServletConfig interface
ServletContext interface
• ServletRequest interface
ServletResponse interface
Classes in servlet package
javax.servlet.http package
HttpServletRequest interface
HttpServletRequest interface
HTTPServletResponse Methods
• void addCookie (Cookie cookie) – adds a Cookie to
the header of the response to the client.
• ServletOutputStream getOutputStream() – gets a
byte-based output stream for sending binary data to the client.
• PrintWriter getWriter() – gets a character-based
output stream for sending text data (typically HTML formatted
text) to the client.
• void SetContentType (String type) – specifies the
content type of the response to the browser to assist in
displaying the data.
• void getContentType() – gets the content type of the
response.
HTTPServletRequest Methods
• Cookie[] getCookies() – returns an array of Cookie
objects stored on the client by the server. Cookies are used
to uniquely identify clients to the server.
• String getLocalName() – gets the host name on which
the request was received.
• String getLocalAddr() – gets the IP address on which
the request was received.
• int getLocalPort() – gets the IP port number on which
the request was received.
• String getParameter( String name) – gets the value
of a parameter set to the servlet as part of a get or post
request.
HttpSession interface
HttpSessionBindingListener Interface

The HttpSessionBindingListener interface is implemented


by objects that need to benotified when they are bound
to or unbound from an HTTP session. The methods that
are invoked when an object is bound or unbound are
• void valueBound(HttpSessionBindingEvent e)
• void valueUnbound(HttpSessionBindingEvent e)
• Here, e is the event object that describes the
binding
Sessiontracking & cookies
• To help the server distinguish between
clients, each client must identify itself to
the server. There are a number of popular
techniques for distinguishing between
clients.
• Two common techniques are cookies and
session tracking we’ll look at both of these
mechanisms. Two other techniques are
hidden forms and URL-rewriting.

cookies
Cookies are a popular technique for customizing web pages.
Browsers can store cookies on the user’s computer for retrieval
later in the same browsing session or in future browsing sessions.
• For example, cookies are used in on-line shopping applications to
store unique identifiers for the users. When users add items to
their on-line shopping carts or perform other tasks resulting in a
request to the web server, the server receives cookies containing
unique identifiers for each user. The server then uses the unique
identifier to locate the shopping carts and perform any necessary
processing.
• Cookies are also used to indicate the client’s shopping
preferences. When the servlet receives the client’s nest
communication, the servlet can examine the cookie(s) it sent to the
client in a previous communication, identify the client’s preferences
and immediately display products of interest to that particular client.
Methods in Cookies class
setComment(string)
Specify or look up a comment associated with the cookie.
getComment()
setDomain(string) Set or retrieve the domain to which the cookie applies. Normally, the
browser returns cookies only to the exact same hostname that sent
getDomain() the cookies.
These methods tell how much time (in seconds) should elapse before
setMaxAge(int) the cookie expires. A negative value, which is the default, indicates
that the cookie will last only for the current browsing session and will
getMaxAge() not be stored on disk. Specifying a value of 0 instructs the browser to
delete the cookie.
Retrieves the name of the cookie. The name and the value are the
getName() two pieces of information which are the most important.

setPath(string) Sets or retrieves the path to which the cookie applies. If you do not
specify a path, the browser returns the cookie only to URLs in or
getPath() below the directory containing the page that sent the cookie.

setSecure(boolean) Sets or retrieves the boolean value which indicates whether the
cookie should only be sent over encrypted connections. The default is
getSecure() false.
setValue(string)
Sets or retrieves the value associated with the cookie.
getValue()
Session Tracking
• As we mentioned before, HTTP is a “stateless” protocol: each time a
client retrieves a web page, the client opens a separate connection
to the web server and the server does not automatically maintain
contextual information about the client.
• Even with servers that support persistent (keep-alive) HTTP
connections and keep sockets open for multiple client requests that
occur in rapid succession, there is no built-in support for maintaining
contextual information.
• This lack of context causes a number of difficulties. For example,
when clients at an online store add an item to their shopping carts,
how does the server know what’s already in the carts? Similarly,
when clients decide to proceed to checkout, how can the server
determine which of the previously created shopping carts are theirs?
• Servlets provide an outstanding session tracking solution: the
HttpSession API. This high-level interface is built on top of
cookies (and URL rewriting). All servers are required to support
session tracking with cookies.
Session Tracking (cont.)
• Using sessions in servlets is straightforward and involves four
basic steps:
1. Accessing the session object associated with the current request.
Call request.getSession to get an HttpSession object,
which is a simple hash table for storing user-specific data.
2. Looking up information associated with a session. Call
getAttribute on the HttpSession object, cast the return
value to the appropriate type, and check whether the result is null.
3. Storing information in a session. Use setAttribute with a key
and a value.
4. Discarding session data. Call removeAttribute to discard a
specific value. Call invalidate to discard an entire session.
Call logout to log the client out of the web server and invalidate
all sessions associated with that user.
Html page for get request
ColorGetServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ColorGetServlet extends HttpServlet
{
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
String color = request.getParameter("color");
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>The selected color is: ");
pw.println(color);
pw.close();
}
}
web.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app>
<servlet>
<servlet-name>hi</servlet-name>
<servlet-class>ColorGetServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>hi</servlet-name>
<url-pattern>hello</url-pattern>
</servlet-mapping>
</web-app>
Http post request
<html>
<body>
<center>
<form name="Form1"
method="post"
action="http://localhost:8080/examples/servlet/ColorPostServlet">
<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>
ColorPostServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ColorPostServlet 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("<B>The selected color is: ");
pw.println(color);
pw.close();
}
}
web.xml
<web-app>
<servlet>
<servlet-name>hi</servlet-name>
<servlet-class>ColorPostServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>hi</servlet-name>
<url-pattern>hello</url-pattern>
</servlet-mapping>
</web-app>
Html document
<html>
<head></head>
<body>
<form action="/phani1/hello" method="get">
<p><label>click this button
<input type="submit" value="click" />
</label>
</p>
</body>
</html>
Some.java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class some extends HttpServlet
{
public void doGet(HttpServletRequest

req,HttpServletResponse res)throws

ServletException,IOException
{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
out.println("hihihihihih");
out.close();
}
}
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app>
<servlet>
<servlet-name>hi</servlet-name>
<servlet-class>some</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>hi</servlet-name>
<url-pattern>hello</url-pattern>
</servlet-mapping>
</web-app>
Passing Parameter Using Html
Form
<html>
<head>
<title>New Page 1</title>
</head>
<body>
<h2>Login</h2>
<p>Please enter your username and password</p>
<form method="GET" action="/htmlform/LoginServlet">
<p> Username <input type="text" name="username" size="20"></p>
<p> Password <input type="text" name="password" size="20"></p>
<p><input type="submit" value="Submit" name="B1"></p>
</form>
<p>&nbsp;</p>
</body>
</html>
Loginservlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class LoginServlet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String name = request.getParameter("username");
String pass = request.getParameter("password");
out.println("<html>");
out.println("<body>");
out.println("Thanks Mr." + " " + name + " " + "for visiting vrsec<br>" );
out.println("Now you can see your password : " + " " + pass + "<br>");
out.println("</body></html>");
}
}
web.xml file
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app>
<servlet>
<servlet-name>Hello</servlet-name>
<servlet-class>LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Hello</servlet-name>
<url-pattern>/LoginServlet</url-pattern>
</servlet-mapping>
</web-app>
Redirect in servlet
Login.html
<html>
<head>
<title>New Page 1</title>
</head>
<body>
<form method="POST"
action="/SendRedirect/SendRedirectServlet">
<p>Enter your name
<input type="text" name="username" size="20"></p>
<p>Enter your password
<input type="text" name="password" size="20"></p>
<p > <input type="submit" value="Submit"
name="B1"></p>
</form>
</body>
</html>
SendRedirectServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SendRedirectServlet extends HttpServlet{
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException
{
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
String name = request.getParameter("username");
String password = request.getParameter("password");
if(name.equals(“phani")&& password.equals("abc")){
response.sendRedirect("/SendRedirect/ValidUserServlet");
}
else{
pw.println("u r not a valid user");
}
}
}
ValidUserServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ValidUserServlet extends HttpServlet{
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException,
IOException {
PrintWriter pw = response.getWriter();
pw.println("Welcome to IT " + " ");
pw.println("how are you");
}
}
Web.xml
<web-app>
<servlet>
<servlet-name>hi</servlet-name>
<servlet-class>SendRedirectServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>hi</servlet-name>
<url-pattern>/SendRedirectServlet</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>Hello</servlet-name>
<servlet-class>ValidUserServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Hello</servlet-name>
<url-pattern>/ValidUserServlet</url-pattern>
</servlet-mapping>
</web-app>
Getting InitInitServlet.java
Parameter Names
import java.io.*;
import javax.servlet.*;import javax.servlet.http.*;
import java.util.*;
public class InitServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter pw = response.getWriter();
pw.print("Init Parameters are : ");
Enumeration enumeration = getServletConfig().getInitParameterNames();
while(enumeration.hasMoreElements())
{
pw.print(enumeration.nextElement() + " ");
}
pw.println("\nThe email address is " +
getServletConfig().getInitParameter("AdminEmail"));
pw.println("The address is " +
getServletConfig().getInitParameter("Address"));
pw.println("The phone no is " +
getServletConfig().getInitParameter("PhoneNo"));
}
}
web.xml
<web-app>
<servlet>
<init-param>
<param-name>AdminEmail</param-name>
<param-value>it@yahoomail.com</param-value>
</init-param>
<init-param>
<param-name>Address</param-name>
<param-value>kanuru</param-value>
</init-param>
<init-param>
<param-name>PhoneNo</param-name>
<param-value>9948099480</param-value>
</init-param>
<servlet-name>hi</servlet-name>
<servlet-class>InitServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>hi</servlet-name>
<url-pattern>/InitServlet</url-pattern>
</servlet-mapping>
</web-app>
Program on Cookies
File Description
AddCookie.htm
Allows a user to specify a value for the
cookie named MyCookie.
AddCookieServlet.java
Processes the submission of
AddCookie.htm.
GetCookiesServlet.java
Displays cookie values.
AddCookie.htm

<html>
<body>
<center>
<form name="Form1"
method="post"
action="http://localhost:8080/examples/servlet/AddCookieServ
let">
<B>Enter a value for MyCookie:</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 request,
HttpServletResponse response)
throws ServletException, IOException {
// Get parameter from HTTP request.
String data = request.getParameter("data");
// Create cookie.
Cookie cookie = new Cookie("MyCookie", data);
// Add cookie to HTTP response.
response.addCookie(cookie);
// Write output to browser.
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>MyCookie has been set to");
pw.println(data);
pw.close();
}}
GetCookieServlet.java
import java.io.*;import javax.servlet.*;import javax.servlet.http.*;
public class GetCookiesServlet extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
// Get cookies from header of HTTP request.

Cookie[ ] cookies = request.getCookies();


// Display these cookies.
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>");
for(int i = 0; i < cookies.length; i++) {
String name = cookies[i].getName();
String value = cookies[i].getValue();
pw.println("name = " + name +
"; value = " + value);
}
pw.close();
}}
CheckingTheSession.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class CheckingTheSession extends HttpServlet
{
protected void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("Checking whether the session is new or old<br>");
HttpSession session = request.getSession();
if(session.isNew()){
pw.println("You have created a new session");
}
else{
pw.println("Session already exists");
}
}}
web.xml
<web-app>
<servlet>
<servlet-name>Hello</servlet-name>
<servlet-class>CheckingTheSession</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Hello</servlet-name>
<url-pattern>/CheckingTheSession</url-pattern>
</servlet-mapping>
</web-app>
output

You might also like