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.
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.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
30. 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();
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
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
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
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
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
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
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
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
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
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>