SlideShare a Scribd company logo
1 of 79
20CS4104
INTERNET PROGRAMMING
UNIT III SERVER SIDE PROGRAMMING
Servlets: Java Servlet Architecture- Servlet Life Cycle- Form GET and POST
actions- Session Handling- Understanding Cookies Installing and Configuring
Apache Tomcat Web Server
DATABASE CONNECTIVITY: JDBC perspectives, JDBC program example
JSP: Understanding Java Server Pages Creating HTML forms by embedding JSP
code.
COURSE OUTCOMES (CO)
CO 1
Students will be able to construct a basic website using HTML and
Cascading Style Sheets.
CO 2
Students will be able to build dynamic web page with validation using Java
Script objects and by applying different event handling mechanisms.
CO 3
To learn Server-side programs using Servlets and JSP with Database
connection.
CO 4
To implement server-side programming and build web applications using
PHP.
CO 5
To understand the concept of server-side framework Node JS and Angular
JS
COURSE OBJECTIVES
1. To learn Server-side programs using Servlets and JSP with
Database connection.
UNIT III SERVER SIDE PROGRAMMING
Session # Topic
1 Installing and Configuring Apache Tomcat Web Server
2 Java Servlet Architecture
3 Servlet Life Cycle
4 Form GET and POST actions
5 Session Handling- Understanding Cookies
6 DATABASE CONNECTIVITY: JDBC perspectives
7 JDBC program example
8 JSP: Understanding Java Server Pages
9 Creating HTML forms by embedding JSP code.
Course Delivery Plan
Installing and Configuring Apache
Tomcat Web Server
• Install JDK
• Download from http://tomcat.apache.org/
• Run the installation file
• Remember port
• Check the installation by typing
http://localhost:8080/ in the browser
• Move web pages to D:Program FilesApache
Software FoundationTomcat 7.0webapps
folder
Servlets
• Java Servlet Architecture
• Servlet Life Cycle
• Form GET and POST actions
• Session Handling
• Understanding Cookies
Servlets
• Servlet is a Java Class File or a Java Program that
runs on a Web server
• Servlets are used for creating dynamic web applications
by extending the capability of a server
• The javax.servlet and javax.servlet.http are packages
which provides interfaces and classes for creating
servlets
• All the servlets must implement the Servlet interface,
which defines life-cycle methods
Java Servlet Architecture
Servlet Life Cycle
• Servlet lifecycle describes how the servlet container manages the
servlet object
• init() :- Initialization of servlet instance using the init() method.
• service() :- Servicing a client request using the service() method.
• destroy() :- Destroying a servlet instance using the destroy()
method.
8
Servlet Life Cycle
Servlet Syntax
public class ServletDemo extends HttpServlet
{
public void init()
{
/* used to initialize resources */
}
public void service()
{
/* used to fulfill client request */
}
public void destroy()
{
/* Release the resources */
}
}
Servlet Example1
public class HelloWorld extends GenericServlet
{
public void service(ServletRequest request, ServletResponse response )
throws IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<h1> Hello World </h1>");
out.close();
}
}
Servlet Example2
public class HelloWorld extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response )
throws IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<h1> Hello World </h1>");
out.close();
}
}
Servlet Container
• It is known as servlet engine which manages Java
Servlet components on top of a web server to the
request send by the client.
• Servlet Container provides the following services:
– It manages the servlet life cycle
– The resources like servlets, JSP pages and HTML
files are managed by servlet container
– It appends session ID to the URL path to maintain
session.
– Provides security service
– It loads a servlet class from network services, file
systems like remote file system and local file system
How web container handles the servlet
request?
1. Maps the request with the servlet in the web.xml file
2. Creates request and response objects for this request
3. Calls the service method on the thread
4. The public service method internally calls the protected
service method
5. The protected service method calls the doGet method
depending on the type of request.
6. The doGet method generates the response and it is passed
to the client.
7. After sending the response, the web container deletes the
request and response objects. The thread is contained in the
thread pool or deleted depends on the server
implementation.
How Servlet Works?
How Servlet Works?
1. When the web server (e.g. Apache Tomcat) starts up,
the servlet container deploy and loads all the servlets
2. Once the servlet is loaded, the servlet container creates
the instance of servlet class.
– For each instantiated servlet, its init() method is
invoked.
3. Client (user browser) sends an Http request to web
server on a certain port.
– Each time the web server receives a request, the
servlet container creates HttpServletRequest and
HttpServletResponse objects.
4. When servlet container shuts down, it unloads all the
servlets and calls destroy() method for each initialized
servlets.
Hierarchy of Packages
java.lang.Object
|_extended by javax.servlet.GenericServlet
|_extended by javax.servlet.http.HttpServlet
Interfaces in javax.servlet
package
• Servlet
• ServletRequest
• ServletResponse
• ServletConfig
• ServletContext
• SingleThreadModel
• RequestDispatcher
• ServletRequestListener
• ServletRequestAttributeListener
• ServletContextListener
• ServletContextAttributeListener
• Filter
• FilterConfig
• FilterChain
Classes in javax.servlet
package
• GenericServlet
• ServletInputStream
• ServletOutputStream
• ServletException
• ServletRequestWrapper
• ServletRequestEvent
• ServletResponseWrapper
• ServletContextEvent
• ServletRequestAttributeEvent
• ServletContextAttributeEvent
• UnavailableException
Interfaces in javax.servlet.http
package
• HttpSession
• HttpServletRequest
• HttpServletResponse
• HttpSessionAttributeListener
• HttpSessionListener
• HttpSessionBindingListener
• HttpSessionActivationListener
• HttpSessionContext
Classes in javax.servlet.http
package
• HttpServlet
• Cookie
• HttpSessionEvent
• HttpSessionBindingEvent
• HttpServletRequestWrapper
• HttpServletResponseWrapper
• HttpUtils
Form GET Actions
<!DOCTYPE html>
<html>
<head>
<title>doGet Example</title>
</head>
<body>
<form name="myform" action=“MyServlet" method=“get">
Enter Name:<input type="text" name="uname"><br><br>
Enter Age:<input type=“text" name=“uage"><br><br>
<input type="submit" value="submit">
</form>
</body>
</html>
Form GET Actions
import javax.servlet.*;
import javax.servlet.http.*;
public class MyServlet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException
{
try
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String name=request.getParameter("uname");
String age=request.getParameter(“uage");
out.println("<h3>Welcome to doGet Method</h3> ");
out.println("<br>Name:"+name);
out.println("<br>Age:"+age);
out.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
21
Form POST Actions
<!DOCTYPE html>
<html>
<head>
<title>doPost Example</title>
</head>
<body>
<form name="myform" action=“MyServlet" method=“post">
Enter Name:<input type="text" name="uname"><br><br>
Enter Password:<input type="password" name="pwd"><br><br>
<input type="submit" value="submit">
</form>
</body>
</html>
Form POST Actions
import javax.servlet.*;
import javax.servlet.http.*;
public class MySerlvet extends HttpServlet
{
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException
{
try
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String name=request.getParameter("uname");
String pwd=request.getParameter("pwd");
out.println("<h3>Welcome to doPost Method</h3> ");
out.println("<br>Name:"+name);
out.println("<br>Password:"+pwd);
out.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
} 23
Session Handling
• Session tracking is a mechanism that servlets use to maintain state
about a series of requests from the same user (that is, requests
originating from the same browser) across some period of time.
• Sessions are shared among the servlets accessed by a client.
• Techniques
– Cookies
– Hidden Form Field
– URL Rewriting
– HttpSession
1. Session Handling using Cookies
• Cookies are small pieces of information that are sent in
response from the web server to the client.
• A cookie has a name, a single value, and optional
attributes such as a comment, path and domain
qualifiers, a maximum age, and a version number.
• Types of Cookie
1. Non-persistent cookie - valid for single session
2. Persistent cookie - valid for multiple session
How cookies works?
• By default, each request is considered as a new request.
• Servlet adds cookie in response
• Then cookie is stored in the cache of the browser
• If request is sent by the same user, cookie is added with
request by default. Thus, server recognizes the user as
the old user.
Methods of Cookie Class
Method Description
public void setMaxAge(int expiry)
Sets the maximum age of the cookie in
seconds.
public String getName()
Returns the name of the cookie. The name
cannot be changed after creation.
public String getValue() Returns the value of the cookie.
public void setName(String name) changes the name of the cookie.
public void setValue(String value) changes the value of the cookie.
Other Methods
public void addCookie(Cookie ck)
method of HttpServletResponse interface is
used to add cookie in response object
public Cookie[] getCookies()
method of HttpServletRequest interface is
used to return all the cookies from the browser
Example using cookies
login.html
<html>
<body>
<form method="post" action=“Validate1">
Name:<input type="text" name="user" /><br/>
Password:<input type=“password" name="pass" ><br/>
<input type="submit" value="submit">
</form>
</body>
</html>
28
login.htmlValidate1
//Session Handling using Cookies
import javax.servlet.*;
import javax.servlet.http.*;
public class Validate1 extends HttpServlet
{
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType(“text/html”);
String name = request.getParameter(“user”);
String pass = request.getParameter(“pass”);
if(name.equals(“abc”)&&pass.equals(“1234”))
{
Cookie ck = new Cookie(“username”,name);
response.addCookie(ck);
response.sendRedirect(“Welcome”);
}
}
}`
29
login.html Validate1Welcome
//Session Handling using Cookies
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Welcome extends HttpServlet
{
protected void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
{
res.setContentType("text/html");
PrintWriter out = res.getWriter();
Cookie[] cks = request.getCookies();
out.println("Welcome "+cks[1].getValue());
}
}
30
2. URL Rewriting for Session Management
• If the client has disabled cookies in the browser then session
management using cookie wont work.
• In that case URL Rewriting can be used as a backup
31
login.html Validate
//Session Handlig using URL Rewriting
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Validate extends HttpServlet
{
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
String name = request.getParameter("user");
String pass = request.getParameter("pass");
if(pass.equals("1234"))
{
response.sendRedirect(“Welcome?uname="+name);
}
}
}
32
login.html ValidateWelcome
//Session Handlig using URL Rewriting
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Welcome extends HttpServlet
{
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String user = request.getParameter("uname");
out.println("Welcome "+user);
}
}
33
3. Hidden Form Fields for Session Management
<html>
<body>
<form method="post" action="Validate">
User: <input type="text" name="user" /><br/>
Password: <input type=“password" name="pass" ><br/>
<input type="submit" value=“Submit">
</form>
</body>
</html>
34
index.html
login.htmlValidate
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Validate extends HttpServlet
{
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out=response.getWriter();
String uname = request.getParameter("user");
String pass = request.getParameter("pass");
if(pass.equals("1234"))
{
out.println(“<form action=‘Welcome’ method=‘post’>”);
out.println(“<input type=‘hidden’ name=‘uname’ value=“+uname+”>”);
out.println(“<input type=‘submit’ value=‘Go’>”);
}
}
}
35
ValidateWelcome
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Welcome extends HttpServlet
{
protected void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String user=request.getParameter(“uname”);
out.println("Hello "+user);
}
}
36
4. HttpSession for Session Management
• HttpSession object is used to store entire session with a
specific client
• On client's first request, the Web Container generates a
unique session ID and gives it back to the client with
response. This is a temporary session created by web
container.
• The client sends back the session ID with each request.
Making it easier for the web container to identify where the
request is coming from.
• The Web Container uses this ID, finds the matching session
with the ID and associates the session with the request.
37
4. HttpSession for Session
Management
38
Methods of HttpSession
Methods Description
long getCreationTime()
returns the time when the session was
created, measured in milliseconds since
midnight January 1, 1970 GMT.
String getId()
returns a string containing the unique
identifier assigned to the session.
long getLastAccessedTime()
returns the last time the client sent a request
associated with the session
int getMaxInactiveInterval()
returns the maximum time interval, in
seconds.
void invalidate() destroy the session
boolean isNew() returns true if the session is new else false
void setMaxInactiveInterval(int interval)
Specifies the time, in seconds,after servlet
container will invalidate the session. 39
//Session Handling using HttpSession
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class FirstServlet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
{
try
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("uname");
out.print("Welcome "+n);
HttpSession session=request.getSession();
session.setAttribute("uname",n);
out.print("<a href=‘SecondServlet'>visit</a>");
out.close();
}
catch(Exception e) { System.out.println(e); }
}
} 40
//Session Handling using HttpSession
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SecondServlet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
{
try
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
HttpSession session=request.getSession(false);
String n=(String)session.getAttribute("uname");
out.print("Hello "+n);
out.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
41
DATABASE CONNECTIVITY
• JDBC perspectives
• JDBC program example
JDBC
• Java Database Connectivity (JDBC) is
an application programming
interface (API) for the programming
language Java, which defines how a
client may access a database
• It is Java based data access technology
and used for Java database connectivity
• JDBC allows multiple implementations to
exist and be used by the same
application
• The JVM uses a JDBC driver to translate
generalized JDBC calls into vendor
specific database calls
JDBC Architecture
JDBC Architecture
• JDBC API
– JDBC API provides universal data access from the
Java programming language
– Using the JDBC API, you can access virtually any
data source, from relational databases to
spreadsheets and flat files
– The JDBC API is comprised of two packages:
• java.sql
• javax.sql
JDBC Architecture
• JDBC Driver Manager
– The DriverManager class acts as an interface
between user and drivers
– It keeps track of the drivers that are available and
handles establishing a connection between a
database and the appropriate driver
– The DriverManager class maintains a list of Driver
classes that have registered themselves by calling the
method DriverManager.registerDriver()
JDBC Architecture
• JDBC Driver
– A JDBC driver is a software component enabling
a Java application to interact with a database
– JDBC drivers are analogous to ODBC drivers, ADO.NET
data providers, and OLE DB providers
– To connect with individual databases, JDBC (the Java
Database Connectivity API) requires drivers for each
database
– The JDBC driver gives out the connection to the database
and implements the protocol for transferring the query
and result between client and database.
Drivers Types
• Type 1 - JDBC-ODBC Bridge
• Type 2 - Native API Driver
• Type 3 – Network-Protocol Driver
• Type 4 – Database-Protocol Driver
48
Drivers Types
• Type 1 that calls native code of the locally
available ODBC driver.
• Type 2 that calls database vendor native library
on a client side. This code then talks to database
over the network.
• Type 3, the pure-java driver that talks with the
server-side middleware that then talks to the
database.
• Type 4, the pure-java driver that uses database
native protocol.
49
Drivers Types
• Type 1 - JDBC-ODBC Bridge
• Uses a bridging technology to access a database. JDBC-ODBC
bridge is an example. It provides a gateway to the ODBC.
• Type 2 - Native API Driver
• Native API drivers.
• Driver contains Java code that calls native C/C++ methods
provided by the database vendors.
• Type 3 – Network-Protocol Driver
• Generic network API that is then translated into database-specific
access at the server level.
• The JDBC driver on the client uses sockets to call a middleware
application on the server that translates the client requests into an
API specific to the desired driver. Extremely flexible.
• Type 4 – Database-Protocol Driver
• Using network protocols built into the database engine talk directly
to the database using Java sockets. Almost always comes only
from database vendors. 50
Type-1 JDBC-ODBC Bridge
51
Type-1 JDBC-ODBC Bridge
• Converts JDBC method calls into ODBC function calls
• Platform-dependent
• ODBC must be installed on the computer having the driver
• Sun (now Oracle) provided a JDBC-ODBC Bridge
river: sun.jdbc.odbc.JdbcOdbcDriver.
• Advantages
– Almost any database for which an ODBC driver is installed can be
accessed, and data can be retrieved.
• Disadvantages
– Performance overhead
– The ODBC driver needs to be installed on the client machine.
– Not suitable for applets
– Specific ODBC drivers are not always available on all platforms
– No support from JDK 1.8 (Java 8) onwards.
52
Type 2 - Native API Driver
53
Type 2 - Native API Driver
• It is a database driver implementation that uses the client-side
libraries of the database
• converts JDBC method calls into native calls of the database
API
• Advantages
– As there is no implementation of JDBC-ODBC bridge, it may
be considerably faster than a Type 1 driver.
• Disadvantages
– The vendor client library needs to be installed on the client
machine.
– Not all databases have a client-side library.
– This driver is platform dependent.
– No Applets support
54
Type 3 – Network-Protocol Driver
55
Type 3 – Network-Protocol Driver
• Pure Java driver for database middleware
• It is a database driver implementation which makes use of a middle
tier between the calling program and the database
• The middle-tier (application server) converts JDBC calls directly or indirectly
into a vendor-specific database protocol.
• platform-independent
• Advantages
– Since the communication between client and the middleware server is
database independent, there is no need for the database vendor library on
the client.
– The middleware server can provide typical middleware services like
caching, load balancing, logging, and auditing.
– A single driver can handle any database, provided the middleware
supports it.
• Disadvantages
– Requires database-specific coding to be done in the middle tier.
– The middleware layer added may result in additional latency, but is
typically overcome by using better middleware services. 56
Type-4 Database-Protocol driver
(Pure Java driver)
57
Type-4 Database-Protocol driver
(Pure Java driver)
• a database driver implementation that converts JDBC calls directly into
a vendor-specific database protocol
• Written completely in Java
• Platform independent
• Advantages
– These drivers don't translate the requests into an intermediary
format (such as ODBC).
– The client application connects directly to the database server.
– The JVM can manage all aspects of the application-to-database
connection
• Disadvantages
– Drivers are database specific, as different database vendors use
widely different network protocols.
58
Which Driver should be Used?
• Type is 4: If you are accessing one type of database,
such as Oracle, Sybase, or IBM
• Type 3: If your Java application is accessing multiple
types of databases at the same time
• Type 2: When a type 3 or type 4 driver is not available
• Type 1: It is typically used for development and testing
purposes only.
Basic steps to use a database in Java
1. Register the Driver class
2. Create connection
3. Create statement
4. Execute queries
5. Close connection
60
JDBC program example-1
import java.sql.*;
public class DatabaseAccess
{
public static void main(String args[]) throws IOException
{
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/test","root","root");
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM student");
while(rs.next())
{
System.out.println("Roll No: " + rs.getInt(1) + "<br>");
System.out.println("Name: " + rs.getString(2) + "<br>");
}
stmt.close(); conn.close();
}
catch(SQLException se) { se.printStackTrace(); }
}
}
61
JDBC program example-2
import java.sql.*;
class DatabaseInsert
{
public static void main(String args[])
{
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:testdb","system","oracle");
PreparedStatement stmt=con.prepareStatement("insert into Emp values(?,?)");
stmt.setInt(1,101);
stmt.setString(2,"Ratan");
int i=stmt.executeUpdate();
System.out.println(i+" records inserted");
con.close();
}
catch(Exception e){System.out.println(e);}
}
}
62
• Class.forName()
– The forName() method of Class class is used to register the driver class.
This method is used to dynamically load the driver class.
• DriverManager class
– The DriverManager class maintains a list of Driver classes that have
registered themselves by calling the method DriverManager.registerDriver().
1. public static Connection getConnection(String url,String
userName,String password):establish the connection with the specified
url, username and password.
• Connection interface
– A Connection is the session between java application and database.
1. public Statement createStatement():creates a statement object that can
be used to execute SQL queries.
2. public void close(): closes the connection and Releases a JDBC
resources immediately.
• Statement interface
– provides methods to execute queries with the database.
1. public ResultSet executeQuery(String sql): is used to execute SELECT
query. It returns the object of ResultSet.
2. public int executeUpdate(String sql): is used to execute specified query,
it may be create, drop, insert, update, delete etc.
• ResultSet interface
– maintains a cursor pointing to a row of a table. Initially, cursor points
to before the first row.
1. public boolean next():is used to move the cursor to the one row
next from the current position.
2. public int getInt(int columnIndex):return the data of specified column
index of the current row as int.
3. public int getInt(String columnName):return the data of specified
column name of the current row as int.
4. public String getString(int columnIndex):return the data of
specified column index of the current row as String.
5. public String getString(String columnName):return the data of
specified column name of the current row as String.
• PreparedStatement interface
– a subinterface of Statement
– It is used to execute parameterized query.
– Eg.: String sql="insert into emp values(?,?,?)";
JSP
• Java Server Pages (JSP) is a server-side programming
technology that enables the creation of dynamic,
platform-independent method for building Web-based
applications.
• JSP have access to the entire family of Java APIs,
including the JDBC API to access enterprise databases.
• JSP technology enables rapid development of web-
based applications
• JSP pages are easier to maintain then a Servlet
• JSP pages are opposite of Servlets as a servlet adds
HTML code inside Java code, while JSP adds Java code
inside HTML using JSP tags
JSP Architecture
66
JSP Life Cycle
67
JSP Syntax
• JSP Scriptlet
– Scriptlet tag allows to write Java code into JSP file.
– JSP container moves statements in _jspservice() method while
generating servlet from jsp.
– Syntax:
<% ... %>
• JSP Declaration Tag
– for declaring variables, methods and classes
– declaration is made outside the service method
– Syntax:
<%! Datatype varname; %>
• JSP Expression
– evaluates the expression placed in it
<%= ... %>
• JSP Directives
<%@ ... %> 68
JSP Scriptlet Example
<!DOCTYPE html>
<html>
<head><title>JSP Example</title></head>
<body>
<% out.println(“Hello World”); %>
</body>
</html>
JSP Declaration Example
<!DOCTYPE html>
<html>
<head><title>JSP Example</title></head>
<body>
<%! int num=10; %>
<% out.println(“This number is ”+num); %>
</body>
</html>
JSP Expression Example
date.jsp
<html>
<body>
Hello! The time is now <%= new java.util.Date() %>
</body>
</html>
71
Directives
• 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
<%@ page attribute="value" %>
– include directive
<%@ include file="resourceName" %>
– taglib directive
<%@ taglib uri="uriofthetaglibrary" prefix="prefixoftaglibrary" %>
72
page directive
• Attributes of JSP page directive
– import
– contentType
– extends
– info
– buffer
– language
– isELIgnored
– isThreadSafe
– autoFlush
– session
– pageEncoding
– errorPage
– isErrorPage
73
include directive
header.html
<html>
<head>
<title>K.Ramakrishnan College of Technology</title>
</head>
<body>
<h1>K.Ramakrishnan College of Technology</h1>
footer.html
</body>
</html>
main.jsp
<%@ include file="header.html" %>
<p>Main content</p>
<%@ include file="footer.html" %>
74
taglib directive
• The JavaServer Pages API allows you to define
custom JSP tags that look like HTML or XML tags
and a tag library is a set of user-defined tags that
implement custom behavior.
• Syntax:
<%@ taglib uri="uriofthetaglibrary" prefix="prefixoftaglibrary" %>
75
JSP Action Tags
JSP Action Tags Description
jsp:forward forwards the request and response to another resource.
jsp:include includes another resource.
jsp:useBean creates or locates bean object.
jsp:setProperty sets the value of property in bean object.
jsp:getProperty prints the value of property of the bean.
jsp:plugin embeds another components such as applet.
jsp:param sets the parameter value. It is used in forward and include
mostly.
jsp:fallback can be used to print the message if plugin is working. It is
used in jsp:plugin.
76
jsp:forward & jsp:param
77
page1.jsp
<html>
<body>
<h2>this is index page</h2>
<jsp:forward page="page2.jsp" >
<jsp:param name=“email" value=“abc@gmail.com" />
</jsp:forward>
</body>
</html>
page2.jsp
<html>
<body>
<%= request.getParameter(“email") %>
</body>
</html>
jsp:include
<html>
<body>
<h2>this is index page</h2>
<jsp:include page=“page2.jsp" />
<h2>end section of index page</h2>
</body>
</html>
78
Creating HTML forms by embedding
JSP code.
<html>
<head>
<title>Using GET Method to Read Form Data</title>
</head>
<body>
<h1>Using GET Method to Read Form Data</h1>
<ul>
<li><p><b>First Name:</b>
<%= request.getParameter("first_name")%>
</p></li>
<li><p><b>Last Name:</b>
<%= request.getParameter("last_name")%>
</p></li>
</ul>
</body>
</html>

More Related Content

Similar to IP UNIT III PPT.pptx (20)

Servlet.pptx
Servlet.pptxServlet.pptx
Servlet.pptx
 
Servlet life cycle
Servlet life cycleServlet life cycle
Servlet life cycle
 
servlet_lifecycle.pdf
servlet_lifecycle.pdfservlet_lifecycle.pdf
servlet_lifecycle.pdf
 
J2ee servlet
J2ee servletJ2ee servlet
J2ee servlet
 
UNIT-3 Servlet
UNIT-3 ServletUNIT-3 Servlet
UNIT-3 Servlet
 
Enterprise java unit-1_chapter-3
Enterprise java unit-1_chapter-3Enterprise java unit-1_chapter-3
Enterprise java unit-1_chapter-3
 
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 9...
 Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 9... Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 9...
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 9...
 
JAVA Servlets
JAVA ServletsJAVA Servlets
JAVA Servlets
 
Java Servlet Programming under Ubuntu Linux by Tushar B Kute
Java Servlet Programming under Ubuntu Linux by Tushar B KuteJava Servlet Programming under Ubuntu Linux by Tushar B Kute
Java Servlet Programming under Ubuntu Linux by Tushar B Kute
 
Wt unit 3 server side technology
Wt unit 3 server side technologyWt unit 3 server side technology
Wt unit 3 server side technology
 
Wt unit 3 server side technology
Wt unit 3 server side technologyWt unit 3 server side technology
Wt unit 3 server side technology
 
J servlets
J servletsJ servlets
J servlets
 
Chapter 3 servlet & jsp
Chapter 3 servlet & jspChapter 3 servlet & jsp
Chapter 3 servlet & jsp
 
Servlet and JSP
Servlet and JSPServlet and JSP
Servlet and JSP
 
Java Servlets.pdf
Java Servlets.pdfJava Servlets.pdf
Java Servlets.pdf
 
Servlet and Servlet Life Cycle
Servlet and Servlet Life CycleServlet and Servlet Life Cycle
Servlet and Servlet Life Cycle
 
java Servlet technology
java Servlet technologyjava Servlet technology
java Servlet technology
 
Servlets
ServletsServlets
Servlets
 
WEB TECHNOLOGY Unit-3.pptx
WEB TECHNOLOGY Unit-3.pptxWEB TECHNOLOGY Unit-3.pptx
WEB TECHNOLOGY Unit-3.pptx
 
Java servlets
Java servletsJava servlets
Java servlets
 

More from ssuser92282c

More from ssuser92282c (8)

unit-4-apache pig-.pdf
unit-4-apache pig-.pdfunit-4-apache pig-.pdf
unit-4-apache pig-.pdf
 
hive in bigdata.pptx
hive in bigdata.pptxhive in bigdata.pptx
hive in bigdata.pptx
 
Bigdata Unit1.pptx
Bigdata Unit1.pptxBigdata Unit1.pptx
Bigdata Unit1.pptx
 
unit-5 SPM.pptx
unit-5 SPM.pptxunit-5 SPM.pptx
unit-5 SPM.pptx
 
Planning.ppt
Planning.pptPlanning.ppt
Planning.ppt
 
UNIT 4-SPM.pptx
UNIT 4-SPM.pptxUNIT 4-SPM.pptx
UNIT 4-SPM.pptx
 
SPM-Lecture -3.ppt
SPM-Lecture -3.pptSPM-Lecture -3.ppt
SPM-Lecture -3.ppt
 
SPM-Lecture 2.pptx
SPM-Lecture 2.pptxSPM-Lecture 2.pptx
SPM-Lecture 2.pptx
 

Recently uploaded

(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024hassan khalil
 
Introduction to Microprocesso programming and interfacing.pptx
Introduction to Microprocesso programming and interfacing.pptxIntroduction to Microprocesso programming and interfacing.pptx
Introduction to Microprocesso programming and interfacing.pptxvipinkmenon1
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.eptoze12
 
Internship report on mechanical engineering
Internship report on mechanical engineeringInternship report on mechanical engineering
Internship report on mechanical engineeringmalavadedarshan25
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130Suhani Kapoor
 
Biology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxBiology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxDeepakSakkari2
 
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escortsranjana rawat
 
Artificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxArtificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxbritheesh05
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxJoão Esperancinha
 
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝soniya singh
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerAnamika Sarkar
 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...Soham Mondal
 
power system scada applications and uses
power system scada applications and usespower system scada applications and uses
power system scada applications and usesDevarapalliHaritha
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort servicejennyeacort
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfAsst.prof M.Gokilavani
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSKurinjimalarL3
 

Recently uploaded (20)

(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024
 
Introduction to Microprocesso programming and interfacing.pptx
Introduction to Microprocesso programming and interfacing.pptxIntroduction to Microprocesso programming and interfacing.pptx
Introduction to Microprocesso programming and interfacing.pptx
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.
 
Internship report on mechanical engineering
Internship report on mechanical engineeringInternship report on mechanical engineering
Internship report on mechanical engineering
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
 
Biology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxBiology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptx
 
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
 
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
 
Artificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxArtificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptx
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
 
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
 
power system scada applications and uses
power system scada applications and usespower system scada applications and uses
power system scada applications and uses
 
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCRCall Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
 

IP UNIT III PPT.pptx

  • 1. 20CS4104 INTERNET PROGRAMMING UNIT III SERVER SIDE PROGRAMMING Servlets: Java Servlet Architecture- Servlet Life Cycle- Form GET and POST actions- Session Handling- Understanding Cookies Installing and Configuring Apache Tomcat Web Server DATABASE CONNECTIVITY: JDBC perspectives, JDBC program example JSP: Understanding Java Server Pages Creating HTML forms by embedding JSP code.
  • 2. COURSE OUTCOMES (CO) CO 1 Students will be able to construct a basic website using HTML and Cascading Style Sheets. CO 2 Students will be able to build dynamic web page with validation using Java Script objects and by applying different event handling mechanisms. CO 3 To learn Server-side programs using Servlets and JSP with Database connection. CO 4 To implement server-side programming and build web applications using PHP. CO 5 To understand the concept of server-side framework Node JS and Angular JS COURSE OBJECTIVES 1. To learn Server-side programs using Servlets and JSP with Database connection.
  • 3. UNIT III SERVER SIDE PROGRAMMING Session # Topic 1 Installing and Configuring Apache Tomcat Web Server 2 Java Servlet Architecture 3 Servlet Life Cycle 4 Form GET and POST actions 5 Session Handling- Understanding Cookies 6 DATABASE CONNECTIVITY: JDBC perspectives 7 JDBC program example 8 JSP: Understanding Java Server Pages 9 Creating HTML forms by embedding JSP code. Course Delivery Plan
  • 4. Installing and Configuring Apache Tomcat Web Server • Install JDK • Download from http://tomcat.apache.org/ • Run the installation file • Remember port • Check the installation by typing http://localhost:8080/ in the browser • Move web pages to D:Program FilesApache Software FoundationTomcat 7.0webapps folder
  • 5. Servlets • Java Servlet Architecture • Servlet Life Cycle • Form GET and POST actions • Session Handling • Understanding Cookies
  • 6. Servlets • Servlet is a Java Class File or a Java Program that runs on a Web server • Servlets are used for creating dynamic web applications by extending the capability of a server • The javax.servlet and javax.servlet.http are packages which provides interfaces and classes for creating servlets • All the servlets must implement the Servlet interface, which defines life-cycle methods
  • 8. Servlet Life Cycle • Servlet lifecycle describes how the servlet container manages the servlet object • init() :- Initialization of servlet instance using the init() method. • service() :- Servicing a client request using the service() method. • destroy() :- Destroying a servlet instance using the destroy() method. 8
  • 10. Servlet Syntax public class ServletDemo extends HttpServlet { public void init() { /* used to initialize resources */ } public void service() { /* used to fulfill client request */ } public void destroy() { /* Release the resources */ } }
  • 11. Servlet Example1 public class HelloWorld extends GenericServlet { public void service(ServletRequest request, ServletResponse response ) throws IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<h1> Hello World </h1>"); out.close(); } }
  • 12. Servlet Example2 public class HelloWorld extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response ) throws IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<h1> Hello World </h1>"); out.close(); } }
  • 13. Servlet Container • It is known as servlet engine which manages Java Servlet components on top of a web server to the request send by the client. • Servlet Container provides the following services: – It manages the servlet life cycle – The resources like servlets, JSP pages and HTML files are managed by servlet container – It appends session ID to the URL path to maintain session. – Provides security service – It loads a servlet class from network services, file systems like remote file system and local file system
  • 14. How web container handles the servlet request? 1. Maps the request with the servlet in the web.xml file 2. Creates request and response objects for this request 3. Calls the service method on the thread 4. The public service method internally calls the protected service method 5. The protected service method calls the doGet method depending on the type of request. 6. The doGet method generates the response and it is passed to the client. 7. After sending the response, the web container deletes the request and response objects. The thread is contained in the thread pool or deleted depends on the server implementation.
  • 16. How Servlet Works? 1. When the web server (e.g. Apache Tomcat) starts up, the servlet container deploy and loads all the servlets 2. Once the servlet is loaded, the servlet container creates the instance of servlet class. – For each instantiated servlet, its init() method is invoked. 3. Client (user browser) sends an Http request to web server on a certain port. – Each time the web server receives a request, the servlet container creates HttpServletRequest and HttpServletResponse objects. 4. When servlet container shuts down, it unloads all the servlets and calls destroy() method for each initialized servlets.
  • 17. Hierarchy of Packages java.lang.Object |_extended by javax.servlet.GenericServlet |_extended by javax.servlet.http.HttpServlet
  • 18. Interfaces in javax.servlet package • Servlet • ServletRequest • ServletResponse • ServletConfig • ServletContext • SingleThreadModel • RequestDispatcher • ServletRequestListener • ServletRequestAttributeListener • ServletContextListener • ServletContextAttributeListener • Filter • FilterConfig • FilterChain Classes in javax.servlet package • GenericServlet • ServletInputStream • ServletOutputStream • ServletException • ServletRequestWrapper • ServletRequestEvent • ServletResponseWrapper • ServletContextEvent • ServletRequestAttributeEvent • ServletContextAttributeEvent • UnavailableException
  • 19. Interfaces in javax.servlet.http package • HttpSession • HttpServletRequest • HttpServletResponse • HttpSessionAttributeListener • HttpSessionListener • HttpSessionBindingListener • HttpSessionActivationListener • HttpSessionContext Classes in javax.servlet.http package • HttpServlet • Cookie • HttpSessionEvent • HttpSessionBindingEvent • HttpServletRequestWrapper • HttpServletResponseWrapper • HttpUtils
  • 20. Form GET Actions <!DOCTYPE html> <html> <head> <title>doGet Example</title> </head> <body> <form name="myform" action=“MyServlet" method=“get"> Enter Name:<input type="text" name="uname"><br><br> Enter Age:<input type=“text" name=“uage"><br><br> <input type="submit" value="submit"> </form> </body> </html>
  • 21. Form GET Actions import javax.servlet.*; import javax.servlet.http.*; public class MyServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { try { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String name=request.getParameter("uname"); String age=request.getParameter(“uage"); out.println("<h3>Welcome to doGet Method</h3> "); out.println("<br>Name:"+name); out.println("<br>Age:"+age); out.close(); } catch(Exception e) { System.out.println(e); } } } 21
  • 22. Form POST Actions <!DOCTYPE html> <html> <head> <title>doPost Example</title> </head> <body> <form name="myform" action=“MyServlet" method=“post"> Enter Name:<input type="text" name="uname"><br><br> Enter Password:<input type="password" name="pwd"><br><br> <input type="submit" value="submit"> </form> </body> </html>
  • 23. Form POST Actions import javax.servlet.*; import javax.servlet.http.*; public class MySerlvet extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { try { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String name=request.getParameter("uname"); String pwd=request.getParameter("pwd"); out.println("<h3>Welcome to doPost Method</h3> "); out.println("<br>Name:"+name); out.println("<br>Password:"+pwd); out.close(); } catch(Exception e) { System.out.println(e); } } } 23
  • 24. Session Handling • Session tracking is a mechanism that servlets use to maintain state about a series of requests from the same user (that is, requests originating from the same browser) across some period of time. • Sessions are shared among the servlets accessed by a client. • Techniques – Cookies – Hidden Form Field – URL Rewriting – HttpSession
  • 25. 1. Session Handling using Cookies • Cookies are small pieces of information that are sent in response from the web server to the client. • A cookie has a name, a single value, and optional attributes such as a comment, path and domain qualifiers, a maximum age, and a version number. • Types of Cookie 1. Non-persistent cookie - valid for single session 2. Persistent cookie - valid for multiple session
  • 26. How cookies works? • By default, each request is considered as a new request. • Servlet adds cookie in response • Then cookie is stored in the cache of the browser • If request is sent by the same user, cookie is added with request by default. Thus, server recognizes the user as the old user.
  • 27. Methods of Cookie Class Method Description public void setMaxAge(int expiry) Sets the maximum age of the cookie in seconds. public String getName() Returns the name of the cookie. The name cannot be changed after creation. public String getValue() Returns the value of the cookie. public void setName(String name) changes the name of the cookie. public void setValue(String value) changes the value of the cookie. Other Methods public void addCookie(Cookie ck) method of HttpServletResponse interface is used to add cookie in response object public Cookie[] getCookies() method of HttpServletRequest interface is used to return all the cookies from the browser
  • 28. Example using cookies login.html <html> <body> <form method="post" action=“Validate1"> Name:<input type="text" name="user" /><br/> Password:<input type=“password" name="pass" ><br/> <input type="submit" value="submit"> </form> </body> </html> 28
  • 29. login.htmlValidate1 //Session Handling using Cookies import javax.servlet.*; import javax.servlet.http.*; public class Validate1 extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType(“text/html”); String name = request.getParameter(“user”); String pass = request.getParameter(“pass”); if(name.equals(“abc”)&&pass.equals(“1234”)) { Cookie ck = new Cookie(“username”,name); response.addCookie(ck); response.sendRedirect(“Welcome”); } } }` 29
  • 30. login.html Validate1Welcome //Session Handling using Cookies import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class Welcome extends HttpServlet { protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/html"); PrintWriter out = res.getWriter(); Cookie[] cks = request.getCookies(); out.println("Welcome "+cks[1].getValue()); } } 30
  • 31. 2. URL Rewriting for Session Management • If the client has disabled cookies in the browser then session management using cookie wont work. • In that case URL Rewriting can be used as a backup 31
  • 32. login.html Validate //Session Handlig using URL Rewriting import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class Validate extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); String name = request.getParameter("user"); String pass = request.getParameter("pass"); if(pass.equals("1234")) { response.sendRedirect(“Welcome?uname="+name); } } } 32
  • 33. login.html ValidateWelcome //Session Handlig using URL Rewriting import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class Welcome extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String user = request.getParameter("uname"); out.println("Welcome "+user); } } 33
  • 34. 3. Hidden Form Fields for Session Management <html> <body> <form method="post" action="Validate"> User: <input type="text" name="user" /><br/> Password: <input type=“password" name="pass" ><br/> <input type="submit" value=“Submit"> </form> </body> </html> 34 index.html
  • 35. login.htmlValidate import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class Validate extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out=response.getWriter(); String uname = request.getParameter("user"); String pass = request.getParameter("pass"); if(pass.equals("1234")) { out.println(“<form action=‘Welcome’ method=‘post’>”); out.println(“<input type=‘hidden’ name=‘uname’ value=“+uname+”>”); out.println(“<input type=‘submit’ value=‘Go’>”); } } } 35
  • 36. ValidateWelcome import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class Welcome extends HttpServlet { protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); String user=request.getParameter(“uname”); out.println("Hello "+user); } } 36
  • 37. 4. HttpSession for Session Management • HttpSession object is used to store entire session with a specific client • On client's first request, the Web Container generates a unique session ID and gives it back to the client with response. This is a temporary session created by web container. • The client sends back the session ID with each request. Making it easier for the web container to identify where the request is coming from. • The Web Container uses this ID, finds the matching session with the ID and associates the session with the request. 37
  • 38. 4. HttpSession for Session Management 38
  • 39. Methods of HttpSession Methods Description long getCreationTime() returns the time when the session was created, measured in milliseconds since midnight January 1, 1970 GMT. String getId() returns a string containing the unique identifier assigned to the session. long getLastAccessedTime() returns the last time the client sent a request associated with the session int getMaxInactiveInterval() returns the maximum time interval, in seconds. void invalidate() destroy the session boolean isNew() returns true if the session is new else false void setMaxInactiveInterval(int interval) Specifies the time, in seconds,after servlet container will invalidate the session. 39
  • 40. //Session Handling using HttpSession import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class FirstServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) { try { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String n=request.getParameter("uname"); out.print("Welcome "+n); HttpSession session=request.getSession(); session.setAttribute("uname",n); out.print("<a href=‘SecondServlet'>visit</a>"); out.close(); } catch(Exception e) { System.out.println(e); } } } 40
  • 41. //Session Handling using HttpSession import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class SecondServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) { try { response.setContentType("text/html"); PrintWriter out = response.getWriter(); HttpSession session=request.getSession(false); String n=(String)session.getAttribute("uname"); out.print("Hello "+n); out.close(); } catch(Exception e) { System.out.println(e); } } } 41
  • 42. DATABASE CONNECTIVITY • JDBC perspectives • JDBC program example
  • 43. JDBC • Java Database Connectivity (JDBC) is an application programming interface (API) for the programming language Java, which defines how a client may access a database • It is Java based data access technology and used for Java database connectivity • JDBC allows multiple implementations to exist and be used by the same application • The JVM uses a JDBC driver to translate generalized JDBC calls into vendor specific database calls
  • 45. JDBC Architecture • JDBC API – JDBC API provides universal data access from the Java programming language – Using the JDBC API, you can access virtually any data source, from relational databases to spreadsheets and flat files – The JDBC API is comprised of two packages: • java.sql • javax.sql
  • 46. JDBC Architecture • JDBC Driver Manager – The DriverManager class acts as an interface between user and drivers – It keeps track of the drivers that are available and handles establishing a connection between a database and the appropriate driver – The DriverManager class maintains a list of Driver classes that have registered themselves by calling the method DriverManager.registerDriver()
  • 47. JDBC Architecture • JDBC Driver – A JDBC driver is a software component enabling a Java application to interact with a database – JDBC drivers are analogous to ODBC drivers, ADO.NET data providers, and OLE DB providers – To connect with individual databases, JDBC (the Java Database Connectivity API) requires drivers for each database – The JDBC driver gives out the connection to the database and implements the protocol for transferring the query and result between client and database.
  • 48. Drivers Types • Type 1 - JDBC-ODBC Bridge • Type 2 - Native API Driver • Type 3 – Network-Protocol Driver • Type 4 – Database-Protocol Driver 48
  • 49. Drivers Types • Type 1 that calls native code of the locally available ODBC driver. • Type 2 that calls database vendor native library on a client side. This code then talks to database over the network. • Type 3, the pure-java driver that talks with the server-side middleware that then talks to the database. • Type 4, the pure-java driver that uses database native protocol. 49
  • 50. Drivers Types • Type 1 - JDBC-ODBC Bridge • Uses a bridging technology to access a database. JDBC-ODBC bridge is an example. It provides a gateway to the ODBC. • Type 2 - Native API Driver • Native API drivers. • Driver contains Java code that calls native C/C++ methods provided by the database vendors. • Type 3 – Network-Protocol Driver • Generic network API that is then translated into database-specific access at the server level. • The JDBC driver on the client uses sockets to call a middleware application on the server that translates the client requests into an API specific to the desired driver. Extremely flexible. • Type 4 – Database-Protocol Driver • Using network protocols built into the database engine talk directly to the database using Java sockets. Almost always comes only from database vendors. 50
  • 52. Type-1 JDBC-ODBC Bridge • Converts JDBC method calls into ODBC function calls • Platform-dependent • ODBC must be installed on the computer having the driver • Sun (now Oracle) provided a JDBC-ODBC Bridge river: sun.jdbc.odbc.JdbcOdbcDriver. • Advantages – Almost any database for which an ODBC driver is installed can be accessed, and data can be retrieved. • Disadvantages – Performance overhead – The ODBC driver needs to be installed on the client machine. – Not suitable for applets – Specific ODBC drivers are not always available on all platforms – No support from JDK 1.8 (Java 8) onwards. 52
  • 53. Type 2 - Native API Driver 53
  • 54. Type 2 - Native API Driver • It is a database driver implementation that uses the client-side libraries of the database • converts JDBC method calls into native calls of the database API • Advantages – As there is no implementation of JDBC-ODBC bridge, it may be considerably faster than a Type 1 driver. • Disadvantages – The vendor client library needs to be installed on the client machine. – Not all databases have a client-side library. – This driver is platform dependent. – No Applets support 54
  • 55. Type 3 – Network-Protocol Driver 55
  • 56. Type 3 – Network-Protocol Driver • Pure Java driver for database middleware • It is a database driver implementation which makes use of a middle tier between the calling program and the database • The middle-tier (application server) converts JDBC calls directly or indirectly into a vendor-specific database protocol. • platform-independent • Advantages – Since the communication between client and the middleware server is database independent, there is no need for the database vendor library on the client. – The middleware server can provide typical middleware services like caching, load balancing, logging, and auditing. – A single driver can handle any database, provided the middleware supports it. • Disadvantages – Requires database-specific coding to be done in the middle tier. – The middleware layer added may result in additional latency, but is typically overcome by using better middleware services. 56
  • 58. Type-4 Database-Protocol driver (Pure Java driver) • a database driver implementation that converts JDBC calls directly into a vendor-specific database protocol • Written completely in Java • Platform independent • Advantages – These drivers don't translate the requests into an intermediary format (such as ODBC). – The client application connects directly to the database server. – The JVM can manage all aspects of the application-to-database connection • Disadvantages – Drivers are database specific, as different database vendors use widely different network protocols. 58
  • 59. Which Driver should be Used? • Type is 4: If you are accessing one type of database, such as Oracle, Sybase, or IBM • Type 3: If your Java application is accessing multiple types of databases at the same time • Type 2: When a type 3 or type 4 driver is not available • Type 1: It is typically used for development and testing purposes only.
  • 60. Basic steps to use a database in Java 1. Register the Driver class 2. Create connection 3. Create statement 4. Execute queries 5. Close connection 60
  • 61. JDBC program example-1 import java.sql.*; public class DatabaseAccess { public static void main(String args[]) throws IOException { try { Class.forName("com.mysql.jdbc.Driver"); Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/test","root","root"); Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("SELECT * FROM student"); while(rs.next()) { System.out.println("Roll No: " + rs.getInt(1) + "<br>"); System.out.println("Name: " + rs.getString(2) + "<br>"); } stmt.close(); conn.close(); } catch(SQLException se) { se.printStackTrace(); } } } 61
  • 62. JDBC program example-2 import java.sql.*; class DatabaseInsert { public static void main(String args[]) { try { Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:testdb","system","oracle"); PreparedStatement stmt=con.prepareStatement("insert into Emp values(?,?)"); stmt.setInt(1,101); stmt.setString(2,"Ratan"); int i=stmt.executeUpdate(); System.out.println(i+" records inserted"); con.close(); } catch(Exception e){System.out.println(e);} } } 62
  • 63. • Class.forName() – The forName() method of Class class is used to register the driver class. This method is used to dynamically load the driver class. • DriverManager class – The DriverManager class maintains a list of Driver classes that have registered themselves by calling the method DriverManager.registerDriver(). 1. public static Connection getConnection(String url,String userName,String password):establish the connection with the specified url, username and password. • Connection interface – A Connection is the session between java application and database. 1. public Statement createStatement():creates a statement object that can be used to execute SQL queries. 2. public void close(): closes the connection and Releases a JDBC resources immediately. • Statement interface – provides methods to execute queries with the database. 1. public ResultSet executeQuery(String sql): is used to execute SELECT query. It returns the object of ResultSet. 2. public int executeUpdate(String sql): is used to execute specified query, it may be create, drop, insert, update, delete etc.
  • 64. • ResultSet interface – maintains a cursor pointing to a row of a table. Initially, cursor points to before the first row. 1. public boolean next():is used to move the cursor to the one row next from the current position. 2. public int getInt(int columnIndex):return the data of specified column index of the current row as int. 3. public int getInt(String columnName):return the data of specified column name of the current row as int. 4. public String getString(int columnIndex):return the data of specified column index of the current row as String. 5. public String getString(String columnName):return the data of specified column name of the current row as String. • PreparedStatement interface – a subinterface of Statement – It is used to execute parameterized query. – Eg.: String sql="insert into emp values(?,?,?)";
  • 65. JSP • Java Server Pages (JSP) is a server-side programming technology that enables the creation of dynamic, platform-independent method for building Web-based applications. • JSP have access to the entire family of Java APIs, including the JDBC API to access enterprise databases. • JSP technology enables rapid development of web- based applications • JSP pages are easier to maintain then a Servlet • JSP pages are opposite of Servlets as a servlet adds HTML code inside Java code, while JSP adds Java code inside HTML using JSP tags
  • 68. JSP Syntax • JSP Scriptlet – Scriptlet tag allows to write Java code into JSP file. – JSP container moves statements in _jspservice() method while generating servlet from jsp. – Syntax: <% ... %> • JSP Declaration Tag – for declaring variables, methods and classes – declaration is made outside the service method – Syntax: <%! Datatype varname; %> • JSP Expression – evaluates the expression placed in it <%= ... %> • JSP Directives <%@ ... %> 68
  • 69. JSP Scriptlet Example <!DOCTYPE html> <html> <head><title>JSP Example</title></head> <body> <% out.println(“Hello World”); %> </body> </html>
  • 70. JSP Declaration Example <!DOCTYPE html> <html> <head><title>JSP Example</title></head> <body> <%! int num=10; %> <% out.println(“This number is ”+num); %> </body> </html>
  • 71. JSP Expression Example date.jsp <html> <body> Hello! The time is now <%= new java.util.Date() %> </body> </html> 71
  • 72. Directives • 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 <%@ page attribute="value" %> – include directive <%@ include file="resourceName" %> – taglib directive <%@ taglib uri="uriofthetaglibrary" prefix="prefixoftaglibrary" %> 72
  • 73. page directive • Attributes of JSP page directive – import – contentType – extends – info – buffer – language – isELIgnored – isThreadSafe – autoFlush – session – pageEncoding – errorPage – isErrorPage 73
  • 74. include directive header.html <html> <head> <title>K.Ramakrishnan College of Technology</title> </head> <body> <h1>K.Ramakrishnan College of Technology</h1> footer.html </body> </html> main.jsp <%@ include file="header.html" %> <p>Main content</p> <%@ include file="footer.html" %> 74
  • 75. taglib directive • The JavaServer Pages API allows you to define custom JSP tags that look like HTML or XML tags and a tag library is a set of user-defined tags that implement custom behavior. • Syntax: <%@ taglib uri="uriofthetaglibrary" prefix="prefixoftaglibrary" %> 75
  • 76. JSP Action Tags JSP Action Tags Description jsp:forward forwards the request and response to another resource. jsp:include includes another resource. jsp:useBean creates or locates bean object. jsp:setProperty sets the value of property in bean object. jsp:getProperty prints the value of property of the bean. jsp:plugin embeds another components such as applet. jsp:param sets the parameter value. It is used in forward and include mostly. jsp:fallback can be used to print the message if plugin is working. It is used in jsp:plugin. 76
  • 77. jsp:forward & jsp:param 77 page1.jsp <html> <body> <h2>this is index page</h2> <jsp:forward page="page2.jsp" > <jsp:param name=“email" value=“abc@gmail.com" /> </jsp:forward> </body> </html> page2.jsp <html> <body> <%= request.getParameter(“email") %> </body> </html>
  • 78. jsp:include <html> <body> <h2>this is index page</h2> <jsp:include page=“page2.jsp" /> <h2>end section of index page</h2> </body> </html> 78
  • 79. Creating HTML forms by embedding JSP code. <html> <head> <title>Using GET Method to Read Form Data</title> </head> <body> <h1>Using GET Method to Read Form Data</h1> <ul> <li><p><b>First Name:</b> <%= request.getParameter("first_name")%> </p></li> <li><p><b>Last Name:</b> <%= request.getParameter("last_name")%> </p></li> </ul> </body> </html>