You are on page 1of 57

SERVLET & JSP

FP612 WEB PROGRAMMING II


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: abcbooks.co.in


http://abcbooks.co.in/eshop/ 202.68.33.49
PurchaseItem?iname=Floppy+Disc&qty=12

2. Send HTTP Request


for eshop/PurchaseItem with 3. Forwards the
http://abcbooks.co.in/e
params request to
Online Shopping a Server Side
Item Floppy Disc Program for
Name
12 The Internet execution
Quantity
Submit

4. Compose HTML
output

5. Send HTTP Response


http://abcbooks.co.in/e which contains the HTML output
of the request
Online Shopping
Bill
Floppy Disc Server Side Program
Price: Rs. 240/-

Goods once sold will not be taken back


Happy Shopping
Servlet

Servlet & JSP


Server Side Java - Servlets
Servlet was introduced by Sun
Microsystems as an effective way to
generate dynamic content for web
applications
Servlet is a Java program that is executed
at the server
The server associates the Servlet with a
URL
When the URL is invoked, the Servlet is
executed
Server Side Java - Servlets
Servlet works in a request/response
model
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
container
Servlets are executed by a Servlet
Container
Tomcat is a Servlet Container that is popularly
used
The Container should be able to execute any
Servlet
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
Servlets

The important methods of the Servlet


interface are as follows
init
service
destroy
Servlets

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
scalable
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
destroyed.
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
service.
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
servlet.
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
logic

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:
Servlets
JSPs
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 java.io.*;
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>"); } }
Output
<form action="login" method="post">
<table>
<tr>
<td><font face="verdana" size="2px">Name:</font></td>
<td><input type="text" name="userName"></td>
</tr>
<tr>
<td><font face="verdana
size="2px">Password:</font></td>
<td><input type="password" name="userPassword"></td>
</tr>
</table>
<input type="submit" value="Login">
</form>
import java.io.IOException;
import java.io.PrintWriter;

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();
res.setContentType("text/html");

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

if(user.equals("java4s")&&pass.equals("java4s"))
pw.println("Login Success...!");
else
pw.println("Login Failed...!");
pw.close();
JSP

Servlet & jsp


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
JSP
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
browser
JSP
JSP
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
Servlet
Bits of HTML embedded in Java code
Suitable for coding the business layer of an
enterprise application
Created and maintained by Java programmers

JSP
Bits of Java code embedded in HTML
Suitable for coding the presentation layer of an
enterprise application
Created and maintained by web designers
JSP
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

Equivalent
Servlet

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
<body>

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


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

</body>
</html>
<html> Jsp Include Directive
<body>

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

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

</body>
</html>
<html>
<body> JSP Taglib directive

<%@ taglib uri="http://www.javatpoint.com/tags" prefix="mytag" %>

<mytag:currentDate/>

</body>
JSP Declaration Tag
The JSP declaration tag is used to declare fields
and methods.
<%!fieldormethoddeclaration%>
<html>
<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) %>
</body>
</html>

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:
<%javasourcecode%>

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>
</html>
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.
<%=statement%>
JSP expression tag
index.html welcome.jsp

<html>
<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>
</form>
</body>
</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
define.
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()
method.
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(){
java.io.Serializable return age;
{ }
private String firstName = null; public void setFirstName(String
firstName){
private String lastName = null; this.firstName = firstName;
private int age = 0; }
public void setLastName(String
lastName){
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
<html>
<head> <p>Student First Name:
<jsp:getProperty name="students"
<title>get and set properties Example</title>
property="firstName"/>
</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"
property="firstName"
property="age"/>
value="Zara"/> </p>
<jsp:setProperty name="students"
property="lastName" </body>
</html>
value="Ali"/>
<jsp:setProperty name="students"
property="age"
value="10"/>
</jsp:useBean>
A Simple JSP
<!-- CurrentTime.jsp -->
<HTML>
<HEAD>
<TITLE>
CurrentTime
</TITLE>
</HEAD>
<BODY>
Current time is <%= new java.util.Date() %>
</BODY>
</HTML>
<!-- ComputeLoan.html --> Example 35.2
<html> Computing Loan
<head>
<title>ComputeLoan</title>
Write an HTML page that prompts
</head>
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.
action="http://localhost:8080/examples/jsp/ComputeLoan.jsp">
<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"
size="3"></p>
<p><input type="submit" name="Submit" value="Compute Loan
Payment">
<input type="reset" value="Reset"></p>
</form>
</body>
<!-- ComputeLoan.jsp -->
<html>
<head>
<title>ComputeLoan</title>
</head> Predefined variable
<body>
<% double loanAmount = Double.parseDouble(
request.getParameter("loanAmount"));
double annualInterestRate = Double.parseDouble(
request.getParameter("annualInterestRate"));
double numberOfYears = Integer.parseInt(
request.getParameter("numberOfYears"));
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>
</body>
</html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html;
charset=UTF-8">
</head>
<body>
<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" />

</form>
</body>
</html>
<%@ page import ="java.sql.*" %>
<%@ page import ="javax.sql.*" %>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<%
String user=request.getParameter("userid"); JSP to database
session.putValue("userid",user);
String pwd=request.getParameter("pwd");
String fname=request.getParameter("fname");
String lname=request.getParameter("lname");
String email=request.getParameter("email");
Class.forName("com.mysql.jdbc.Driver");
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
('"+user+"','"+pwd+"','"+fname+"','"+lname+"','"+email+"')");

if(i>0)
{
%>
You are successfully registered..Click <a href="Login.html"> Here </a> to login
<%
}
%>
</body>