20cs4104 Ip Unit III
20cs4104 Ip Unit III
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 OBJECTIVES
1. To learn Server-side programs using Servlets and JSP with
Database connection.
Session # Topic
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 Classes in javax.servlet
package package
• Servlet • GenericServlet
• ServletRequest
• ServletInputStream
• ServletResponse
• ServletConfig • ServletOutputStream
• ServletContext
• ServletException
• SingleThreadModel
• RequestDispatcher • ServletRequestWrapper
• ServletRequestListener • ServletRequestEvent
• ServletRequestAttributeListener
• ServletContextListener • ServletResponseWrapper
• ServletContextAttributeListener • ServletContextEvent
• Filter
• ServletRequestAttributeEvent
• FilterConfig
• FilterChain • ServletContextAttributeEvent
• UnavailableException
Interfaces in javax.servlet.http Classes in javax.servlet.http
package package
• HttpServlet
• HttpSession
• Cookie
• HttpServletRequest • HttpSessionEvent
• HttpSessionBindingEvent
• HttpServletResponse
• HttpServletRequestWrapper
• HttpSessionAttributeListener • HttpServletResponseWrapper
• HttpSessionListener • HttpUtils
• HttpSessionBindingListener
• HttpSessionActivationListener
• HttpSessionContext
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
– URL Rewriting
– HttpSession
1. Session Handling using Cookies
Other Methods
method of HttpServletResponse interface is
public void addCookie(Cookie ck)
used to add cookie in response object
method of HttpServletRequest interface is
public Cookie[] getCookies()
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.htmlValidate1
//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 Validate1Welcome
//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();
30
2. URL Rewriting for Session Management
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 ValidateWelcome
//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
index.html
<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
login.htmlValidate
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
ValidateWelcome
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Welcome extends HttpServlet
{
protected void doGet(HttpServletRequest request,HttpServletResponse response)
36
4. HttpSession for Session Management
37
4. HttpSession for Session Management
38
Methods of HttpSession
Methods Description
• 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
– 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
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.
– include directive
<%@ include file="resourceName" %>
– taglib directive
<%@ taglib uri="uriofthetaglibrary" prefix="prefixoftaglibrary" %>
72
page directive
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
76
jsp:forward & jsp:param
page1.jsp
<html>
<body>
<h2>this is index page</h2>
</body>
77
</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>
Grade program
index.html
• <!DOCTYPE html>
• <html>
• <head>
• <title> Marks </title>
• <meta charset="UTF-8">
• <meta name="viewport" content="width=device-width, initial-scale=1.0">
• </head>
• <body>
• <p> Enter Marks </p>
• <form action="result.jsp" method="get">
• Enter Marks in Advanced Java: <input type="text" name="java"><br><br>
• Enter NMA Marks: <input type="text" name="NMA"><br><br>
• Enter MCAD Marks: <input type="text" name="MCAD"><br><br>
• Enter PPUD Marks: <input type="text" name="PPUD"><br><br>
• Enter Project Marks: <input type="text" name="pro"><br><br>
• <input type="submit">
• </form>
• </body>
• </html>
Result.jsp
• <%@page contentType="text/html" pageEncoding="UTF-8"%>
• <!DOCTYPE html>
• <html>
• <head>
• <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
• <title> Result </title>
• </head>
• <body>
• <%
• int java = Integer.parseInt(request.getParameter("java"));
• int NMA = Integer.parseInt(request.getParameter("NMA"));
• int MCAD = Integer.parseInt(request.getParameter("MCAD"));
• int PPUD = Integer.parseInt(request.getParameter("PPUD"));
• int Project = Integer.parseInt(request.getParameter("pro"));
• int totalMarks = java + NMA + MCAD + PPUD + Project;
• double average = totalMarks / 5.0;
• out.print("Your grade is ");
• if (average > 90) {
• out.print("A");
• } else if (average >= 80) {
• out.print("B");
• } else if (average >= 70) {
• out.print("C");
• } else if (average >= 60) {
• out.print("D");
• } else {
• out.print("E");
• }
• %>
• </body>
• </html>