You are on page 1of 57



Static Page Vs Dynamic Page
From the web, we get static pages as well as dynamic pages
Static Page Dynamic Page

Can be created and stored in web Can NOT be created and stored in web
server in advance as HTML file. server in advance as HTML file.
Static page does not change with user Dynamic page changes as per the user
and/or time. and/or time.
For delivery of static page, all we For delivery of dynamic page, apart
require at server side, HTML files in from Web Server, we require program
Web Server. to generate dynamic content.

The software component that runs the server side program to generate
the dynamic content is known as the Web Container
Generation of Dynamic Pages
Web Server

1. User Submits Form and resultant URL:

2. Send HTTP Request

for eshop/PurchaseItem with 3. Forwards the
params request to
Online Shopping a Server Side
Item Floppy Disc Program for
12 The Internet execution

4. Compose HTML

5. Send HTTP Response which contains the HTML output
of the request
Online Shopping
Floppy Disc Server Side Program
Price: Rs. 240/-

Goods once sold will not be taken back

Happy Shopping

Servlet & JSP

Server Side Java - Servlets
Servlet was introduced by Sun
Microsystems as an effective way to
generate dynamic content for web
Servlet is a Java program that is executed
at the server
The server associates the Servlet with a
When the URL is invoked, the Servlet is
Server Side Java - Servlets
Servlet works in a request/response
Accepts a request
Carries out the request and sends a
response, which can be in HTML format
Thus, Servlets can be used to generate
dynamic pages
Architecture of servlet
Servlet Container

For executing the programs in the server side,

the web server requires the help of a web
Servlets are executed by a Servlet
Tomcat is a Servlet Container that is popularly
The Container should be able to execute any
Servlet Container

This requirement calls for a standard

interface for all the Servlets
A class should implement the interface
called Servlet in the package
javax.servlet to become a Servlet

The important methods of the Servlet

interface are as follows

The Servlet Container will do the following

Create and initialize the Servlet by calling the
init method
Handle requests from clients by calling the
service method
Destroy the Servlet by calling the destroy
method and garbage collect it
The Servlet Lifecycle
The Servlet Container will call the init()
method (exactly once) of this Servlet object
(after instantiating it).
The Servlet Container will then call the
service method of the Servlet object
The service() method will generate the
dynamic page and deliver it to the client
The Web Container call thedestroy()method
before removing servlet instance, giving it a
chance for cleanup activity.
The Servlet Lifecycle
A new Servlet object is NOT instantiated for
each subsequent request
The Servlet Container will spawn a thread for
each request to call the service method of the
same Servlet object
This makes the Servlet technology faster and
The Servlet Lifecycle
The destroy method is called and the Servlet
object is garbage collected when the Servlet
Container decides to unload the Servlet from
the memory
When the server shuts down,
When an administrator manually unloads it
The phrase "instantiating a class" means the
same thing as "creating an object." When you
create an object, you are creating an "instance"
of a class, therefore "instantiating" a class.
Servlet Life-Cycle

The init method is called when the

servlet is first created, and is not called
again as long as the servlet is not
This resembles the applets init method,
which is invoked when the applet is
created, and is not invoked again as long
as applet is not destroyed.
Servlet Life-Cycle
The service method is invoked each time
the server receives a request for the servlet.
The server spawns a new thread and invokes
Servlet Life-Cycle

The destroy method is invoked once

all threads within the servlet's service
method have exited or after a timeout
period has passed.
This method releases resources for the
Responsibilities of Servlets
Coding the presentation logic and business logic
together is not a good practice
A change in any one of these requires the modification of
the entire code
Programmers with different skill sets are required for
creating and maintaining these
Earlier, programmers used to place the business
logic and presentation logic interleaved in a
Servlet program
Responsibilities of Servlets
Servlets, being Java programs, are best suited
for coding business logic and not presentation

Presentation logic is Business logic or domain

concerned with how logic is the part of the
business objects program that encodes the
real-world business rules that
determine how data can be
created, displayed, stored,
and changed
J2EE application layers
Thepresentation layer
Thepresentation layeris where the user
interface is dynamically generated. An
application may require the following J2EE
components in the presentation layer:
Static Content
Thebusiness logic layer
Thebusiness logic layertypically contains
deployed EJB components that encapsulate
business rules and other business functions in:
Session Beans
Entity Beans
Message-Driven Beans
Responsibilities of Servlets
Servlets are not suitable to code presentation
logic because
It is not easy to mix static contents with dynamic
contents in Servlets
As Servlets are not as easy as HTML, it will be
difficult for web designers to use this technology
Responsibilities of Servlets
A technology with the power of Servlets and
ease of HTML is required to code
presentation logic, so that web designers can
also easily use it.
And the solution is Java Server Pages (JSP)
Advantage of Servlet
better performance:because it creates a
thread for each request not process.
Portability:because it uses java language.
Robust:Servlets are managed by JVM so we
don't need to worry about memory leak,
garbage collection etc.
Secure:because it uses java language..
Applets vs Servlets

Applets Servlets
Applets are applications Servlets are Java based
designed to be transmitted analog to CGI programs,
over the network and executed implemented by means of
by Java compatible web servlet container associated
browsers. with an HTTP server.
An Applet is a client side java Servlet is a server side
program that runs within a component which runs on
Web browser on the client the web server.
machine. The servlet does not have a
An applet can use the user user interface.
interface classes like AWT or Servlet Methods: doGet(),
Swing. doPost()
Applet Life Cycle Methods:
Example of servlet code
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloWWW extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{ response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " +
"Transitional//EN\">\n" + "<HTML>\n" + "<HEAD><TITLE>Hello
WWW</TITLE></HEAD>\n" + "<BODY>\n" + "<H1>Hello WWW</H1>\n" +
"</BODY></HTML>"); } }
<form action="login" method="post">
<td><font face="verdana" size="2px">Name:</font></td>
<td><input type="text" name="userName"></td>
<td><font face="verdana
<td><input type="password" name="userPassword"></td>
<input type="submit" value="Login">

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class OnServletLogin extends HttpServlet

protected void doPost(HttpServletRequest req,HttpServletResponse
res)throws ServletException,IOException
PrintWriter pw=res.getWriter();

String user=req.getParameter("userName");
String pass=req.getParameter("userPassword");

pw.println("Login Success...!");
pw.println("Login Failed...!");

Servlet & jsp

JSP is a technology developed by Sun
Microsystems for coding the presentation
layer of an enterprise application
A JSP file is very similar to an HTML file
Unlike HTML files, JSP files will contain some
Java code also with in <% %> elements
The JSP file will have a .jsp extension
The server associates the JSP with a URL
When the URL is invoked, the JSP is executed
Just like a ServletContainer is required for
executing a Servlet, a JSP Container is
required for executing a JSP
Tomcat is a very popular JSP container
When a client requests for a JSP, the JSP
container sends the HTML tags as such to the
Can be used to code presentation logic
Can be used to generate dynamic pages
Is as simple as HTML, even web designers
can use it easily
Servlets Vs JSP
Bits of HTML embedded in Java code
Suitable for coding the business layer of an
enterprise application
Created and maintained by Java programmers

Bits of Java code embedded in HTML
Suitable for coding the presentation layer of an
enterprise application
Created and maintained by web designers
Internally, the JSP Container converts the JSP
into a Servlet when a user requests for a JSP for
the first time
This Servlet would produce the output that the JSP
file is supposed to produce


JSPContainer (Tomcat)
JSP .java file
JSP Scriptlet tag (Scripting elements)
JSP comments tag
JSP Comments
JSP comment marks text or statements that the JSP
container should ignore. A JSP comment is useful
when you want to hide or "comment out" part of
your JSP page.
<%-- This is JSP comment --%>

Html comments
An HTML comment. Ignored by the browser.
<!-- comment -->
JSP directives tag
The jsp directives are messages that tells
the web container how to translate a JSP page
into the corresponding servlet.
There are three types of directives:
page directive
include directive
taglib directive
<html> JSP page directive

<%@ page import="java.util.Date" %>

Today is: <%= new Date() %>

<html> Jsp Include Directive

<%@ include file="header.html" %>

Today is: <%= java.util.Calendar.getInstance().getTime() %>

<body> JSP Taglib directive

<%@ taglib uri="" prefix="mytag" %>


JSP Declaration Tag
The JSP declaration tag is used to declare fields
and methods.
<html> <body>
<body> <%!
<%! int data=50; %> int cube(int n){
<%= "Value of the variable is:"+data %> return n*n*n*;
</body> }
</html> %>
<%= "Cube of 3 is:"+cube(3) %>

Example of JSP declaration tag Example of JSP declaration tag

that declares field that declares method
JSP scriptlet tag
A scriptlet tag is used to execute java source
code in JSP. Syntax is as follows:

index.html welcome.jsp

<html> <html>
<body> <body>
<form action="welcome.jsp"> <%
<input type="text" name="uname"> String
<input type="submit" name=request.getParameter("uname");
value="go"><br/> out.print(Welcome "+name);
</form> %>
</body> </form>
</html> </body>
JSP expression tag
The code placed within JSP expression tag
is written to the output stream of the
response. So you need not write out.print() to
write data. It is mainly used to print the values
of variable or method.
JSP expression tag
index.html welcome.jsp

<html> <body>
<body> <%= "Welcome
<form action="welcome.jsp"> "+request.getParameter("uname") %>
<input type="text" name="uname"><b
r/> </body>
<input type="submit" value="go"> </html>
Java Beans
JavaBean is a Java class that is mainly
responsible for holding on to some data without a
large degree of functionality built into the class.
A Java Bean is a java class that should follow
following conventions:
It should have a no-arg constructor.
It should be Serializable.
It should provide methods to set and get the values of
the properties, known as getter and setter methods.
JavaBeans Properties
A JavaBean property is a named attribute that can be
accessed by the user of the object. The attribute can
be of any Java data type, including classes that you
A JavaBean property may be read, write, read only, or
write only. JavaBean properties are accessed through
two methods in the JavaBean's implementation class
A read-only attribute will have only a
getPropertyName() method, and a write-only
attribute will have only a setPropertyName()
Why use Java Bean?
According to Java white paper, it is a reusable software
component. A bean encapsulates many objects into one object,
so we can access this object from multiple places. Moreover, it
provides the easy maintenance.
JavaBeans example
public class StudentsBean implements public int getAge(){ return age;
{ }
private String firstName = null; public void setFirstName(String
private String lastName = null; this.firstName = firstName;
private int age = 0; }
public void setLastName(String
public StudentsBean() { this.lastName = lastName;
} }
public String getFirstName(){ public void setAge(Integer age){
this.age = age;
return firstName;
} }
public String getLastName(){
return lastName;
JavaBeans example
<head> <p>Student First Name:
<jsp:getProperty name="students"
<title>get and set properties Example</title>
</head> </p>
<body> <p>Student Last Name:
<jsp:getProperty name="students"
<jsp:useBean id="students" property="lastName"/>
class="StudentsBean"> </p>
<p>Student Age:
<jsp:setProperty name="students"
<jsp:getProperty name="students"
value="Zara"/> </p>
<jsp:setProperty name="students"
property="lastName" </body>
<jsp:setProperty name="students"
A Simple JSP
<!-- CurrentTime.jsp -->
Current time is <%= new java.util.Date() %>
<!-- ComputeLoan.html --> Example 35.2
<html> Computing Loan
Write an HTML page that prompts
the user to enter loan amount,
<body> annual interest rate, and number of
Compute Loan Payment years. Clicking the Compute Loan
Payment button invokes a JSP to
<form method="get" compute and display the monthly
and total loan payment.
<p>Loan Amount
<input type="text" name="loanAmount"><br>
Annual Interest Rate
<input type="text" name="annualInterestRate"><br>
Number of Years <input type="text" name="numberOfYears"
<p><input type="submit" name="Submit" value="Compute Loan
<input type="reset" value="Reset"></p>
<!-- ComputeLoan.jsp -->
</head> Predefined variable
<% double loanAmount = Double.parseDouble(
double annualInterestRate = Double.parseDouble(
double numberOfYears = Integer.parseInt(
double monthlyInterestRate = annualInterestRate / 1200;
double monthlyPayment = loanAmount * monthlyInterestRate /
(1 - 1 / Math.pow(1 + monthlyInterestRate, numberOfYears * 12));
double totalPayment = monthlyPayment * numberOfYears * 12; %>
Loan Amount: <%= loanAmount %><br>
Annual Interest Rate: <%= annualInterestRate %><br>
Number of Years: <%= numberOfYears %><br>
<b>Monthly Payment: <%= monthlyPayment %><br>
Total Payment: <%= totalPayment %><br></b>
<meta http-equiv="Content-Type" content="text/html;
<form action="reg.jsp" method="post">

Email :<input type="text" name="email" />

First name :<input type="text" name="fname" />
Last name :<input type="text" name="lname" />
User name :<input type="text" name="userid" />
password :<input type="password" name="pwd" />
<input type="submit" />

<%@ page import ="java.sql.*" %>
<%@ page import ="javax.sql.*" %>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
String user=request.getParameter("userid"); JSP to database
String pwd=request.getParameter("pwd");
String fname=request.getParameter("fname");
String lname=request.getParameter("lname");
String email=request.getParameter("email");
java.sql.Connection con = DriverManager.getConnection("jdbc:mysql://localhost/login","root","");
Statement st= con.createStatement();
ResultSet rs;
int i=st.executeUpdate("insert into users values

You are successfully registered..Click <a href="Login.html"> Here </a> to login