SlideShare a Scribd company logo
UNIT3-SERVLETS
 Building a Web Application in Eclipse,
 Introduction to Servlets: Lifecycle of a
Servlet,The Servlet API, Reading Servlet
parameters, Reading initialization
parameters, Handling HTTP Request &
Responses, writing and deploying
Servlets,
 Session management using Hidden
fields, Cookies and sessions and URL
rewriting, Request Dispatcher,
 Connecting to a database from servlet
using JDBC.
UNDERSTANDING CLIENT AND SERVER SIDE
SCRIPTING
 Web-Site Structure
2
 Steps
1. Request Content(Client)
2. Get response back(Server)
 Additional Steps
 1.x Execute a script in the client side
 2.x: Execute a script in the server side
 Calculate something
 Retrieve data from a database
 3. Execute script in the client side
Client
Server
DEFINITION
 Client Side Scripting
 computer programs on the web
 that are executed client-side, by the user's web browser
 JavaScript
 Jquery
 VBScript
 Server Side Scripting
 computer programs on the web
 that are executed server-side
 usually used to provide interactive web sites
 that interface to databases or other data stores
 PHP
 Perl
 Ruby
 JSP
 Servlets 4
WEB SERVER
WHAT IS A WEB SERVER?
• A web server is a system that delivers
content(web pages) or services to end
users over the internet.
• The basic objective of the web server is to
store, process and deliver web pages to
the users.
• This intercommunication is done using
Hypertext Transfer Protocol (HTTP).
• Program that understands the HTTP protocol
and generates appropriate responses
– Clients “connect” to the machine
– Clients send a “request”
– Server reads request, generates “response”
– Client interprets response appropriately
WHAT IS A WEB SERVER?
WEB SERVERS
Popular Web Servers
Apache
Windows IIS
IBM Websphere
Apache server is the most common web server
available in the market. Apache is an open
source software that handles almost 70 percent
of all websites available today.
SERVLETS (2).pptxintroduction to servlet with all servlets
PROVIDE HTTP PORT NUMBER :
8080
SERVLETS (2).pptxintroduction to servlet with all servlets
SERVLETS (2).pptxintroduction to servlet with all servlets
SERVLETS (2).pptxintroduction to servlet with all servlets
WHAT IS WEB APPLICATION?
• A web application is an application accessible
from the web. A web application is composed
of web components like Servlet, JSP, Filter etc.
and other components such as HTML. The
web components typically execute in Web
Server and respond to HTTP request.
CGI(Common Gateway
Interface)
SERVLETS (2).pptxintroduction to servlet with all servlets
Disadvantages of CGI
1. If number of clients increases, it takes more time for
sending response.
2. It uses platform dependent language e.g. C, C++, perl.
3. For each request CGI Server receives, It creates new
Operating System Process.
4. If the number of requests from the client increases
then more time it will take to respond to the request.
5. As programs executed by CGI Script are written in
the native languages such as C, C++, perl which are
platform dependent.
Servlet
SERVLETS (2).pptxintroduction to servlet with all servlets
SERVLETS (2).pptxintroduction to servlet with all servlets
SERVLETS (2).pptxintroduction to servlet with all servlets
SERVLETS (2).pptxintroduction to servlet with all servlets
SERVLETS (2).pptxintroduction to servlet with all servlets
Advantages of Servlet
 Performance
 The performance of servlets is superior to CGI because
there is no process creation for each client request.
 Each request is handled by the servlet container process.
 After a servlet has completed processing a request, it stays
resident in memory, waiting for another request.
 Portability
 Like other Java technologies, servlet applications are portable.
 Rapid development cycle
 As a Java technology, servlets have access to the rich Java
library that will help speed up the development process.
 Robustness
 Servlets are managed by the Java Virtual Machine.
 Don't need to worry about memory leak or garbage collection,
which helps you write robust applications.
 Widespread acceptance
 Java is a widely accepted technology.
Life Cycle of Servlet
Initialization
init()
Service
service()
doGet()
doPost()
doDelete()
doHead()
doTrace()
doOptions()
Destruction
destroy()
Concurrent
Threads
of Execution
SERVLETS (2).pptxintroduction to servlet with all servlets
SERVLETS (2).pptxintroduction to servlet with all servlets
Life Cycle Methods
• init() :
– Servlet loads and initializes the servlet
• service():
– Servlet handles one or more client Request and
Responses to the client
• destroy():
– Servlet is deactivated or server is terminated
– Memory allocated for the servlet and its object are
garbage collected
Note: All above methods are inherited from GenericServlet class
SERVLETS (2).pptxintroduction to servlet with all servlets
SERVLETS (2).pptxintroduction to servlet with all servlets
SERVLETS (2).pptxintroduction to servlet with all servlets
public void service(ServletRequest
req,ServletResponse res) throws
ServletException,IOException
{
res.setContentType("text/html");
// server responds in HTML format
PrintWriter out=res.getWriter();
}
Sample Servlet Example
import java.io.*;
import javax.servlet.*;
public class ServletExample extends GenericServlet
{
public void service(ServletRequest req,ServletResponse res) throws
ServletException,IOException
{
res.setContentType("text/html"); // server responds in HTML format
PrintWriter out=res.getWriter();
out.println("<html>");
out.println("<body>");
out.println("Hello World...");
out.println("</body>");
out.println("</html>");
}
}
Directory Structure
ROOT
Save
.java program
Web.xml(Deployment Descriptor) is an XML document that
defines everything about your application that a server needs to
know
Web.xml(Deployment Descriptor file)
SERVLETS (2).pptxintroduction to servlet with all servlets
ServletContext and ServletConfig
Both ServletContext and ServletConfig a
re basically the configuration objects
which are used by the servlet container to
initialize the various parameter of a web
application. But they have some
difference in terms of scope and
availability.
Difference between ServletConfig vs.
ServletContext
• An object of ServletConfig is createdby the web
container for each servlet.
• This object can be used to get configuration
information from web.xml file.
• If the configuration information is modified
from the web.xml file, we don't need to change
the servlet.
• So it is easier to manage the web application if
any specific content is modified from time to
time.
SERVLETS (2).pptxintroduction to servlet with all servlets
ServletConfig ServletContext
ServletConfig object is one per servlet class. ServletContext object is global to the entire web application.
Object of ServletConfig will be created during the initialization
process of the servlet.
Object of ServletContext will be created at the time of web
application deployment
We have to give the request explicitly in order to create the
ServletConfig object for the first time.
ServletContext object can be available even before giving the
first request.
Scope: As long as a servlet is executing, the ServletConfig object
will be available, it will be destroyed once the servlet execution
is completed.
Scope: As long as a web application is executing, the
ServletContext object will be available, and it will be destroyed
once the application is removed from the server.
ServletConfig object is used while only one servlet requires
information shared by it.
ServletContext object is used while application requires
information shared by it.
getServletConfig() method is used to obtain Servletconfig object. getServletContext() method is used to obtain ServletContext
object.
In web.xml — tag will be appear under tag. In web.xml — tag will be appear under tag.
Reading Initialization paramters
• Sometimes we may have a requirement that a
value keeps changing time to time and so we do
not want to hard code it into a servlet.
• If it is done, we will have to change the value and
again recompile the servlet.
ServletConfig config=getServletConfig();
String name=config.getInitParameter(“uname");
Deployment Descriptor file(Web.xml)
<web-app>
<servlet>
<servlet-name>DemoServlet</servlet-name>
<servlet-class>DemoServlet</servlet-class>
<init-param>
<param-name>uname</param-name>
<param-value>scott</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>DemoServlet</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
</web-app>
Reading Init Parameters
web.xml
<web-app>
<servlet>
<servlet-name>Config</servlet-name>
<servlet-class>ConfigDemo</servlet-class>
<init-param>
<param-name>username</param-name>
<param-value>vnrvjiet</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>Config</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
</web-app>
ConfigDemo.java
// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
// Extend HttpServlet class
public class ConfigDemo extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Set response content type
response.setContentType("text/html");
// Actual logic goes here.
PrintWriter out = response.getWriter();
//get ServletConfig object.
ServletConfig config=getInitServletConfig();
//get init parameter from ServletConfig object.
String name= config.getParameter("username");
out.println("Welcome "+name);
out.close()
}}
Reading Initialization Parameters in multiple
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class DemoServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
ServletConfig config=getServletConfig();
Enumeration<String> e=config.getInitParameterNames();
String str="";
while(e.hasMoreElements()){
str=e.nextElement();
out.print("<br>Name: "+str);
out.print(" value: "+config.getInitParameter(str));
} out.close(); }
}
Reading Servlet Parameters
<html>
<body>
<form action = "HelloForm" method = "GET">
First Name: <input type = "text" name =
"first_name"> <br />
Last Name: <input type = "text" name =
"last_name" />
<input type = "submit" value = "Submit" />
</form>
</body> </html>
How to read servlet parameters
// Get enumeration of parameter names.
Enumeration e = request.getParameterNames();
// Display parameter names and values.
while(e.hasMoreElements())
{
String pname = (String)e.nextElement();
pw.print(pname + " = ");
String pvalue = request.getParameter(pname);
pw.println(pvalue);
}
// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
// Extend HttpServlet class
public class HelloForm extends HttpServlet {
// Method to handle GET method request.
public void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
// Set response content type
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>" +"<ul>n" +”<li><b>First Name</b>: "+
request.getParameter("first_name") + "n" +" <li><b>Last Name</b>: " +
request.getParameter("last_name") + "n" +
"</ul>n" +
" </html>"
); }
Javax.servlet.http
package
SERVLETS (2).pptxintroduction to servlet with all servlets
• The HttpServletRequest Interface
The HttpServletRequest interface
enables a servlet to obtain
information about a client request.
• The HttpServletResponse
Interface The HttpServletResponse
interface enables a servlet to
formulate an HTTP response to a
client.
• The HttpSession interface enables a
servlet to read and write the state
information that is associated with
an HTTP session.. All of these
methods throw an
IllegalStateException if the session
has already been invalidated.
• Why use Session Tracking?
• To recognize the user It is used to
recognize the particular user.
• Session Tracking Techniques
• There are four techniques used in
Session tracking:
• Cookies
• Hidden Form Field
• URL Rewriting
• HttpSession
SERVLETS (2).pptxintroduction to servlet with all servlets
SERVLETS (2).pptxintroduction to servlet with all servlets
SERVLETS (2).pptxintroduction to servlet with all servlets
SERVLETS (2).pptxintroduction to servlet with all servlets
SERVLETS (2).pptxintroduction to servlet with all servlets
The names and values of cookies
are stored on the user’s machine.
Some of the information that is
saved for each cookie includes the
following:
• The name of the cookie
• The value of the cookie
• The expiration date of the cookie
• The domain and path of the cookie
SERVLETS (2).pptxintroduction to servlet with all servlets
11/6/2011
62
sayed@justetc.net
CREATING COOKIE PROGRAM
Index.html
<form method="post" action="validate">
Name:<input type="text" name="user" /><br/>
Password:<input type="text" name="pass" ><br/>
<input type="submit" value="submit"> </form>
11/6/2011
63
sayed@justetc.net
MyServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class MyServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
String name = request.getParameter("user");
String pass = request.getParameter("pass");
if(pass.equals("1234"))
{
Cookie ck = new Cookie("username",name);
response.addCookie(ck);
response.sendRedirect("First");
}
}
}
64
First.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class First extends HttpServlet {
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html ");
PrintWriter out = response.getWriter();
Cookie[] cks = request.getCookies();
out.println("Welcome "+cks[0].getValue());
}
}
11/6/2011
65
sayed@justetc.net
<web-app...>
<servlet>
<servlet-name>validate</servlet-name>
<servlet-class>MyServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>validate</servlet-name>
<url-pattern>/validate</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>First</servlet-name>
<servlet-class>First</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>First</servlet-name>
<url-pattern>/First</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
66
HTTP SESSION
 A session contains information specific to a particular user across
the whole application. When a user enters into a website (or an
online application) for the first time HttpSession is obtained via
request.getSession(), the user is given a unique ID to identify his
session.
 The HttpSession stays alive until it has not been used for more than
the timeout value specified in tag in deployment descriptor
file( web.xml). The default timeout value is 30 minutes, this is used
if you don’t specify the value in tag. This means that when the user
doesn’t visit web application time specified, the session is
destroyed by servlet container. The subsequent request will not be
served from this session anymore, the servlet container will create
a new session.
11/6/2011
67
sayed@justetc.net
 Commonly used Methods of Servlet HttpSession
 setAttribute(String name, Object value): Binds an object to this session,
using the name specified.
setMaxInactiveInterval(int interval): Specifies the time, in seconds,
between client requests before the servlet container will invalidate this
session.
getAttribute(String name): Returns the object bound with the specified
name in this session, or null if no object is bound under the name.
getAttributeNames(): Returns an Enumeration of String objects containing
the names of all the objects bound to this session.
getId(): Returns a string containing the unique identifier assigned to this
session.
invalidate(): Invalidates this session then unbinds any objects bound to it.
removeAttribute(String name): Removes the object bound with the
specified name from this session.
11/6/2011
68
sayed@justetc.net
sessionemo.html
<html>
<head>
<title>session Demo</title>
</head>
<body>
<form action="servlet1" method="post">
Enter Your Name:<input type="text"
name="userName"/><br/><br/>
<input type="submit" value="SUBMIT"/>
</form>
</body>
</html>
11/6/2011
69
sayed@justetc.net
SetSessionServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SetSessionServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse
response){
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String name=request.getParameter("userName");
// Create a session object.
HttpSession session = request.getSession(true);
session.setAttribute("uname",name);
11/6/2011
70
sayed@justetc.net
//creating submit button
out.print("<br><form action='servlet2'
method='post'>");
out.print("<input type='submit' value='View the
session'>");
out.print("</form>");
out.close();
}
catch(Exception e){
System.out.println(e);
} }}
11/6/2011
71
sayed@justetc.net
GetSessionServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class GetSessionServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse
response){
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
HttpSession session=request.getSession(false);
String name=(String)session.getAttribute("uname");
out.print("Hello!.. Welcome "+name);
out.close(); }catch(Exception e){ System.out.println(e); }
}}
11/6/2011
72
sayed@justetc.net
11/6/2011
73
sayed@justetc.net
web.xml
<web-app>
<servlet>
<servlet-name>set</servlet-name>
<servlet-class>SetSessionServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>set</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>get</servlet-name>
<servlet-class>GetSessionServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>get</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>
</web-app>
11/6/2011
sayed@justetc.net
74
HIDDEN FORM FIELD
<form method="post" action="validate">
Name:<input type="text" name="user" /><br/>
Password:<input type="text" name="pass" ><br/>
<input type="submit" value="submit"> </form>
75
FIRST.JAVA
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class First extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
//getting value submitted in form from HTML file
String user = request.getParameter("user");
//creating a new hidden form field
out.println("<form action='Second'>");
out.println("<input type='hidden' name='user' value='"+user+"'>");
out.println("<input type='submit' value='submit' >");
out.println("</form>");
}
}
76
SECOND.JAVA
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Second extends HttpServlet {
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
//getting parameter from the hidden field
String user = request.getParameter("user");
out.println("Welcome "+user);
}
}
77
WEB.XML
<web-app...>
<servlet>
<servlet-name>First</servlet-name>
<servlet-class>First</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>First</servlet-name>
<url-pattern>/First</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>Second</servlet-name>
<servlet-class>Second</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Second</servlet-name>
<url-pattern>/Second</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
78
URL REWRITING
In URL rewriting, we append a token or identifier to the
URL of the next Servlet or the next resource. We can
send parameter name/value pairs using the following
format:
url?name1=value1&name2=value2&??
A name and a value is separated using an equal = sign,
a parameter name/value pair is separated from another
parameter using the ampersand(&). When the user
clicks the hyperlink, the parameter name/value pairs
will be passed to the server. From a Servlet, we can use
getParameter() method to obtain a parameter value.
11/6/2011
sayed@justetc.net
79
SESSION TRACKING
80
11/6/2011
sayed@justetc.net
81
SESSION TRACKING
1.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.
2.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.
3.The Web Container uses this ID, finds the
matching session with the ID and associates the
session with the request.
11/6/2011
sayed@justetc.net
82
INDEX.HTML
<form method="post" action="Validate">
User: <input type="text" name="user" /><br/>
Password: <input type="text" name="pass" ><br/>
<input type="submit" value="submit">
</form>
11/6/2011
sayed@justetc.net
83
VALIDATE.JAVA
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"))
{
//creating a session
HttpSession session = request.getSession();
session.setAttribute("user", name);
response.sendRedirect("Welcome");
}
}
}
11/6/2011
sayed@justetc.net
84
WELCOME.JAVA
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();
HttpSession session = request.getSession();
String user =
(String)session.getAttribute("user");
out.println("Hello "+user);
}}
11/6/2011
sayed@justetc.net
85
WEB.XML
<web-app..>
<servlet>
<servlet-name>Validate</servlet-name>
<servlet-class>Validate</servlet-class>
</servlet>
<servlet>
<servlet-name>Welcome</servlet-name>
<servlet-class>Welcome</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Validate</servlet-name>
<url-pattern>/Validate</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Welcome</servlet-name>
<url-pattern>/Welcome</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
11/6/2011
sayed@justetc.net
86
UNIT
4
JDBC
SERVLETS (2).pptxintroduction to servlet with all servlets
JAVA DATABASE
CONNECTIVITY(JDBC)
• Java Database Connectivity(JDBC) is
an Application Programming Interface(API)
used to connect Java application with Database.
• JDBC is used to interact with various type of
Database such as Oracle, MS Access, My SQL
and SQL Server.
• It allows java program to execute SQL
statement and retrieve result from database.
JDBC IN JAVA
• Jdbc is a part of JDK software so no need to
install separate software for Jdbc API
• Jdbc API consists of two packages
java.sql package
javax.sql package
JDBC ARCHITECTURE
• JDBC Architecture consists of two layers −
JDBC API: This provides the application-to-JDBC Manager
connection.
JDBC Driver API: This supports the JDBC Manager-to-
Driver Connection.
• The JDBC API uses a driver manager and database-specific
drivers to provide transparent connectivity to heterogeneous
databases.
• The JDBC driver manager ensures that the correct driver is
used to access each data source.
JDBC DRIVER
• JDBC Driver is a software component that
enables java application to interact with the
database.
• Types of drivers
JDBC-ODBC bridge driver
Native-API driver (partially java driver)
Network Protocol driver (fully java driver)
Thin driver (fully java driver)
TYPE 1 : JDBC-ODBC BRIDGE
DRIVER
• The JDBC-ODBC is also known as Type 1 driver.
• The JDBC-ODBC bridge driver converts the JDBC method call into the
ODBC function call.
• This driver is platform dependent.
• Sun provides the JDBC-ODBC Bridge driver by following URL -
“sun.jdbc.odbc.JdbcOdbcDriver”
• Advantage
 Easy to use
 Allow easy connectivity to all database supported by the ODBC
Driver.
• Disadvantage
• Slow execution time
• Dependent on ODBC Driver.
SERVLETS (2).pptxintroduction to servlet with all servlets
TYPE 2 : NATIVE API DRIVER
(PARTIAL JAVA DRIVER)
• The Native API driver is also known as Type 2 driver.
• It uses the client-side libraries of the database.
• must be installed on each client system.
• This driver converts the JDBC method call into native
call of database.
Advantage
faster as compared to Type-1 Driver
Disadvantage
Requires native library
Type 2 driver is platform
dependent.
It does not support applet
programming.
TYPE 3 : NETWORK PROTOCOL
DRIVER
• The Network protocol driver uses the
three- tier model.
• The middle tier is responsible to
converts JDBC calls directly or
indirectly into vender specific
database protocol.
• This type of driver is very flexible
that is a single driver can actually
provide access to multiple
databases.
Advantage
Does not require any native library to be installed.
Database Independency.
Disadvantage
Slow due to increase number of network call.
TYPE 4 : THIN DRIVER (PURE JAVA
DRIVER)
• It is a pure Java driver which connects all Java
drivers directly to the vendor specific
database protocol.
• This driver provides the highest performance
driver for the database.
• Thin driver is completely written in Java
because of that it is known as 100% pure Java
driver.
SERVLETS (2).pptxintroduction to servlet with all servlets
JDBC - SQL
SYNTAX
• Create Database
CREATE DATABASE DATABASE_NAME;
Create a Database named EMP ?
CREATE DATABASE EMP;
• Drop Database
DROP DATABASE DATABASE_NAME;
• Create Table
CREATE TABLE table_name ( column_name
column_data_type, column_name
column_data_type, column_name column_data_type ... );
CREATE TABLE Employees ( id INT NOT NULL,
INT NOT NULL,
age
first
last
VARCHAR(255),
VARCHAR(255),
PRIMARY KEY ( id )
);
CREATE AN EMPLOYEE
TABLE?
INSERT Data:
INSERT INTO
...);
table_name VALUES (column1, column2,
INSERT A NEW ROW IN THE EMPLOYEES
DATABASE CREATED EARLIER ?
INSERT INTO Employees VALUES (100, 18, ‘cse', ‘vnr');
SELECT Data
SELECT column_name, column_name, ... FROM
table_name WHERE conditions;
The WHERE clause can use the comparison operators such as =, !
=,
<, >, <=,and >=, as well as the BETWEEN and LIKE operators.
• To select the age, first and last columns
from the Employees table, where id column is
100 ?
•
SELECT
FROM
WHERE
first, last, age
Employees
id = 100;
• UPDATE Data
UPDATE table_name
SET column_name =
value, WHERE
conditions;
column_name = value, ...
• To UPDATE statement changes the age column
of the employee whose id is 100 ?
• UPDATE Employees SET age=20 WHERE id=100;
• DELETE Data
• DELETE FROM table_name WHERE
conditions;
• DELETE statement deletes the record of the
employee whose id is 100 ?
• DELETE FROM Employees WHERE
id=100;
STEPS TO CONNECT A JAVA
APPLICATION
TO DATABASE
1. Register the Driver
2. Create a Connection
3. Create SQL Statement
4. Execute SQL Statement
5. Closing the connection
• Register the Driver
Class.forName() is used to load the driver class
explicitly.
• Example to register with JDBC-ODBC Driver
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
• Create a Connection
getConnection() method of DriverManager class is
used to create a connection.
DRIVERMANAGER CLASS
• Syntax
getConnection(String url)
getConnection(String url, String username, String password)
getConnection(String url, Properties info)
Example establish connection with Oracle Driver
Connection con =
DriverManager.getConnection("jdbc:odbc:DSN","username",
"password");
CREATE SQL
STATEMENT
• The Connection interface provides
the createStatement() method to create SQL
statement.
• Syntax:
public Statement createStatement( ) throws
SQLException
• Example:
Statement stmt = con.createStatement();
EXECUTE SQL QUERIES
• The Statement interface provides
the executeQuery( ) method to execute SQL
statements.
• Syntax:
public ResultSet executeQuery(String
sql) throws SQLException
• Example:
• ResultSet rs = stmt.executeQuery("select * from students");
while (rs.next())
{
System.out.println (rs.getInt(1)+" "+rs.getString(2)+"
"+rs.getFloat(3));
}
• Closing the Connection
• The Connection interface provides close( ) method, used to
close the connection.
• Example:
con.close( );
STATEMENT
INTERFACE IN JDBC
• The Statement interface provides methods to execute queries
with the database.
RESULTSET
INTERFACE IN JDBC
• The object of ResultSet maintains a cursor pointing to a
particular row of data. Initially, cursor points to before the first
row.
SERVLETS (2).pptxintroduction to servlet with all servlets
HOW TO CREATE JDBC
CONNECTION?
SERVLETS (2).pptxintroduction to servlet with all servlets
WHAT ARE THE TYPES OF
JDBC STATEMENTS
AVAILABLE?
• There are 3 types of Statements, as given below:
Statement:
It can be used for general-purpose access to the database. It is
useful when you are using static SQL statements at runtime.
PreparedStatement:
It can be used when you plan to use the same SQL statement many
times. The PreparedStatement interface accepts input parameters
at runtime.
CallableStatement:
CallableStatement can be used when you want to access database
stored procedures.
CONNECTION
CON;
PreparedStatement pstmt =
con.prepareStatement("sql command");
Example:
PreparedStatement pstmt =
con.prepareStatement("Insert into emp
value(?,
?)");
The each ? represent the column index number in the table. If
table EMP has id, name columns, then 1st ? refer to id, 2nd ?
refer to name.
Afterthat we need to set the value to each ? by using the
setter method from PreparedStatement interface as follows :
Syntax : setXXX(ColumnIndex, value)
METHODS OF PREPAREDSTATEMENT
INTERFACE
PREPAREDSTATEMENT
INTERFACE
• It represents precompiled SQL statements and
stores it in a PreparedStatement object.
• It increases the performance of the application
because the query is compiled only once.
• The PreparedStatement is easy to reuse with new
parameters.
SERVLETS (2).pptxintroduction to servlet with all servlets
CREATING
PREPAREDSTATEMENT
OBJECT
• Syntax
Connection con;
PreparedStatement
String sql
=
pstmt = con.prepareStatement("sql command");
"Select * from Student where rollNo= ?";
• PreparedStatement ps
=
con.prepareStatement(sql);
• END
of
JDBC
Ad

More Related Content

Similar to SERVLETS (2).pptxintroduction to servlet with all servlets (20)

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
Tushar B Kute
 
Wt unit 3
Wt unit 3 Wt unit 3
Wt unit 3
team11vgnt
 
Servlet
Servlet Servlet
Servlet
Dhara Joshi
 
Ecom 1
Ecom 1Ecom 1
Ecom 1
Santosh Pandey
 
Servlet ppt by vikas jagtap
Servlet ppt by vikas jagtapServlet ppt by vikas jagtap
Servlet ppt by vikas jagtap
Vikas Jagtap
 
Server side programming
Server side programming Server side programming
Server side programming
javed ahmed
 
Bt0083 server side programing
Bt0083 server side programing Bt0083 server side programing
Bt0083 server side programing
Techglyphs
 
Servlets
ServletsServlets
Servlets
ZainabNoorGul
 
Lecture 2
Lecture 2Lecture 2
Lecture 2
Ahmed Madkor
 
Unitwwsbdsbsdbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb-4.pptx
Unitwwsbdsbsdbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb-4.pptxUnitwwsbdsbsdbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb-4.pptx
Unitwwsbdsbsdbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb-4.pptx
VikasTuwar1
 
Java servlet technology
Java servlet technologyJava servlet technology
Java servlet technology
Minal Maniar
 
Servlet by Rj
Servlet by RjServlet by Rj
Servlet by Rj
Shree M.L.Kakadiya MCA mahila college, Amreli
 
JAVA Servlets
JAVA ServletsJAVA Servlets
JAVA Servlets
deepak kumar
 
Java servlets
Java servletsJava servlets
Java servlets
yuvarani p
 
UNIT-3 Servlet
UNIT-3 ServletUNIT-3 Servlet
UNIT-3 Servlet
ssbd6985
 
J2ee servlet
J2ee servletJ2ee servlet
J2ee servlet
vinoth ponnurangam
 
Knowledge Sharing : Java Servlet
Knowledge Sharing : Java ServletKnowledge Sharing : Java Servlet
Knowledge Sharing : Java Servlet
Fahmi Jafar
 
Advance Java Topics (J2EE)
Advance Java Topics (J2EE)Advance Java Topics (J2EE)
Advance Java Topics (J2EE)
slire
 
Servlet and JSP
Servlet and JSPServlet and JSP
Servlet and JSP
Gary Yeh
 
Chapter 3 servlet & jsp
Chapter 3 servlet & jspChapter 3 servlet & jsp
Chapter 3 servlet & jsp
Jafar Nesargi
 
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
Tushar B Kute
 
Servlet ppt by vikas jagtap
Servlet ppt by vikas jagtapServlet ppt by vikas jagtap
Servlet ppt by vikas jagtap
Vikas Jagtap
 
Server side programming
Server side programming Server side programming
Server side programming
javed ahmed
 
Bt0083 server side programing
Bt0083 server side programing Bt0083 server side programing
Bt0083 server side programing
Techglyphs
 
Unitwwsbdsbsdbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb-4.pptx
Unitwwsbdsbsdbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb-4.pptxUnitwwsbdsbsdbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb-4.pptx
Unitwwsbdsbsdbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb-4.pptx
VikasTuwar1
 
Java servlet technology
Java servlet technologyJava servlet technology
Java servlet technology
Minal Maniar
 
UNIT-3 Servlet
UNIT-3 ServletUNIT-3 Servlet
UNIT-3 Servlet
ssbd6985
 
Knowledge Sharing : Java Servlet
Knowledge Sharing : Java ServletKnowledge Sharing : Java Servlet
Knowledge Sharing : Java Servlet
Fahmi Jafar
 
Advance Java Topics (J2EE)
Advance Java Topics (J2EE)Advance Java Topics (J2EE)
Advance Java Topics (J2EE)
slire
 
Servlet and JSP
Servlet and JSPServlet and JSP
Servlet and JSP
Gary Yeh
 
Chapter 3 servlet & jsp
Chapter 3 servlet & jspChapter 3 servlet & jsp
Chapter 3 servlet & jsp
Jafar Nesargi
 

Recently uploaded (20)

hypermedia_system_revisit_roy_fielding .
hypermedia_system_revisit_roy_fielding .hypermedia_system_revisit_roy_fielding .
hypermedia_system_revisit_roy_fielding .
NABLAS株式会社
 
Control Methods of Noise Pollutions.pptx
Control Methods of Noise Pollutions.pptxControl Methods of Noise Pollutions.pptx
Control Methods of Noise Pollutions.pptx
vvsasane
 
Jacob Murphy Australia - Excels In Optimizing Software Applications
Jacob Murphy Australia - Excels In Optimizing Software ApplicationsJacob Murphy Australia - Excels In Optimizing Software Applications
Jacob Murphy Australia - Excels In Optimizing Software Applications
Jacob Murphy Australia
 
ML_Unit_VI_DEEP LEARNING_Introduction to ANN.pdf
ML_Unit_VI_DEEP LEARNING_Introduction to ANN.pdfML_Unit_VI_DEEP LEARNING_Introduction to ANN.pdf
ML_Unit_VI_DEEP LEARNING_Introduction to ANN.pdf
rameshwarchintamani
 
Working with USDOT UTCs: From Conception to Implementation
Working with USDOT UTCs: From Conception to ImplementationWorking with USDOT UTCs: From Conception to Implementation
Working with USDOT UTCs: From Conception to Implementation
Alabama Transportation Assistance Program
 
Design Optimization of Reinforced Concrete Waffle Slab Using Genetic Algorithm
Design Optimization of Reinforced Concrete Waffle Slab Using Genetic AlgorithmDesign Optimization of Reinforced Concrete Waffle Slab Using Genetic Algorithm
Design Optimization of Reinforced Concrete Waffle Slab Using Genetic Algorithm
Journal of Soft Computing in Civil Engineering
 
Nanometer Metal-Organic-Framework Literature Comparison
Nanometer Metal-Organic-Framework  Literature ComparisonNanometer Metal-Organic-Framework  Literature Comparison
Nanometer Metal-Organic-Framework Literature Comparison
Chris Harding
 
22PCOAM16 ML Unit 3 Full notes PDF & QB.pdf
22PCOAM16 ML Unit 3 Full notes PDF & QB.pdf22PCOAM16 ML Unit 3 Full notes PDF & QB.pdf
22PCOAM16 ML Unit 3 Full notes PDF & QB.pdf
Guru Nanak Technical Institutions
 
6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)
6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)
6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)
ijflsjournal087
 
Uses of drones in civil construction.pdf
Uses of drones in civil construction.pdfUses of drones in civil construction.pdf
Uses of drones in civil construction.pdf
surajsen1729
 
Design of Variable Depth Single-Span Post.pdf
Design of Variable Depth Single-Span Post.pdfDesign of Variable Depth Single-Span Post.pdf
Design of Variable Depth Single-Span Post.pdf
Kamel Farid
 
Modelling of Concrete Compressive Strength Admixed with GGBFS Using Gene Expr...
Modelling of Concrete Compressive Strength Admixed with GGBFS Using Gene Expr...Modelling of Concrete Compressive Strength Admixed with GGBFS Using Gene Expr...
Modelling of Concrete Compressive Strength Admixed with GGBFS Using Gene Expr...
Journal of Soft Computing in Civil Engineering
 
Artificial intelligence and machine learning.pptx
Artificial intelligence and machine learning.pptxArtificial intelligence and machine learning.pptx
Artificial intelligence and machine learning.pptx
rakshanatarajan005
 
ML_Unit_V_RDC_ASSOCIATION AND DIMENSIONALITY REDUCTION.pdf
ML_Unit_V_RDC_ASSOCIATION AND DIMENSIONALITY REDUCTION.pdfML_Unit_V_RDC_ASSOCIATION AND DIMENSIONALITY REDUCTION.pdf
ML_Unit_V_RDC_ASSOCIATION AND DIMENSIONALITY REDUCTION.pdf
rameshwarchintamani
 
Construction Materials (Paints) in Civil Engineering
Construction Materials (Paints) in Civil EngineeringConstruction Materials (Paints) in Civil Engineering
Construction Materials (Paints) in Civil Engineering
Lavish Kashyap
 
Machine foundation notes for civil engineering students
Machine foundation notes for civil engineering studentsMachine foundation notes for civil engineering students
Machine foundation notes for civil engineering students
DYPCET
 
twin tower attack 2001 new york city
twin  tower  attack  2001 new  york citytwin  tower  attack  2001 new  york city
twin tower attack 2001 new york city
harishreemavs
 
Prediction of Flexural Strength of Concrete Produced by Using Pozzolanic Mate...
Prediction of Flexural Strength of Concrete Produced by Using Pozzolanic Mate...Prediction of Flexural Strength of Concrete Produced by Using Pozzolanic Mate...
Prediction of Flexural Strength of Concrete Produced by Using Pozzolanic Mate...
Journal of Soft Computing in Civil Engineering
 
2.3 Genetically Modified Organisms (1).ppt
2.3 Genetically Modified Organisms (1).ppt2.3 Genetically Modified Organisms (1).ppt
2.3 Genetically Modified Organisms (1).ppt
rakshaiya16
 
Mode-Wise Corridor Level Travel-Time Estimation Using Machine Learning Models
Mode-Wise Corridor Level Travel-Time Estimation Using Machine Learning ModelsMode-Wise Corridor Level Travel-Time Estimation Using Machine Learning Models
Mode-Wise Corridor Level Travel-Time Estimation Using Machine Learning Models
Journal of Soft Computing in Civil Engineering
 
hypermedia_system_revisit_roy_fielding .
hypermedia_system_revisit_roy_fielding .hypermedia_system_revisit_roy_fielding .
hypermedia_system_revisit_roy_fielding .
NABLAS株式会社
 
Control Methods of Noise Pollutions.pptx
Control Methods of Noise Pollutions.pptxControl Methods of Noise Pollutions.pptx
Control Methods of Noise Pollutions.pptx
vvsasane
 
Jacob Murphy Australia - Excels In Optimizing Software Applications
Jacob Murphy Australia - Excels In Optimizing Software ApplicationsJacob Murphy Australia - Excels In Optimizing Software Applications
Jacob Murphy Australia - Excels In Optimizing Software Applications
Jacob Murphy Australia
 
ML_Unit_VI_DEEP LEARNING_Introduction to ANN.pdf
ML_Unit_VI_DEEP LEARNING_Introduction to ANN.pdfML_Unit_VI_DEEP LEARNING_Introduction to ANN.pdf
ML_Unit_VI_DEEP LEARNING_Introduction to ANN.pdf
rameshwarchintamani
 
Nanometer Metal-Organic-Framework Literature Comparison
Nanometer Metal-Organic-Framework  Literature ComparisonNanometer Metal-Organic-Framework  Literature Comparison
Nanometer Metal-Organic-Framework Literature Comparison
Chris Harding
 
6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)
6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)
6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)
ijflsjournal087
 
Uses of drones in civil construction.pdf
Uses of drones in civil construction.pdfUses of drones in civil construction.pdf
Uses of drones in civil construction.pdf
surajsen1729
 
Design of Variable Depth Single-Span Post.pdf
Design of Variable Depth Single-Span Post.pdfDesign of Variable Depth Single-Span Post.pdf
Design of Variable Depth Single-Span Post.pdf
Kamel Farid
 
Artificial intelligence and machine learning.pptx
Artificial intelligence and machine learning.pptxArtificial intelligence and machine learning.pptx
Artificial intelligence and machine learning.pptx
rakshanatarajan005
 
ML_Unit_V_RDC_ASSOCIATION AND DIMENSIONALITY REDUCTION.pdf
ML_Unit_V_RDC_ASSOCIATION AND DIMENSIONALITY REDUCTION.pdfML_Unit_V_RDC_ASSOCIATION AND DIMENSIONALITY REDUCTION.pdf
ML_Unit_V_RDC_ASSOCIATION AND DIMENSIONALITY REDUCTION.pdf
rameshwarchintamani
 
Construction Materials (Paints) in Civil Engineering
Construction Materials (Paints) in Civil EngineeringConstruction Materials (Paints) in Civil Engineering
Construction Materials (Paints) in Civil Engineering
Lavish Kashyap
 
Machine foundation notes for civil engineering students
Machine foundation notes for civil engineering studentsMachine foundation notes for civil engineering students
Machine foundation notes for civil engineering students
DYPCET
 
twin tower attack 2001 new york city
twin  tower  attack  2001 new  york citytwin  tower  attack  2001 new  york city
twin tower attack 2001 new york city
harishreemavs
 
2.3 Genetically Modified Organisms (1).ppt
2.3 Genetically Modified Organisms (1).ppt2.3 Genetically Modified Organisms (1).ppt
2.3 Genetically Modified Organisms (1).ppt
rakshaiya16
 
Ad

SERVLETS (2).pptxintroduction to servlet with all servlets

  • 1. UNIT3-SERVLETS  Building a Web Application in Eclipse,  Introduction to Servlets: Lifecycle of a Servlet,The Servlet API, Reading Servlet parameters, Reading initialization parameters, Handling HTTP Request & Responses, writing and deploying Servlets,  Session management using Hidden fields, Cookies and sessions and URL rewriting, Request Dispatcher,  Connecting to a database from servlet using JDBC.
  • 2. UNDERSTANDING CLIENT AND SERVER SIDE SCRIPTING  Web-Site Structure 2  Steps 1. Request Content(Client) 2. Get response back(Server)  Additional Steps  1.x Execute a script in the client side  2.x: Execute a script in the server side  Calculate something  Retrieve data from a database  3. Execute script in the client side
  • 4. DEFINITION  Client Side Scripting  computer programs on the web  that are executed client-side, by the user's web browser  JavaScript  Jquery  VBScript  Server Side Scripting  computer programs on the web  that are executed server-side  usually used to provide interactive web sites  that interface to databases or other data stores  PHP  Perl  Ruby  JSP  Servlets 4
  • 6. WHAT IS A WEB SERVER? • A web server is a system that delivers content(web pages) or services to end users over the internet. • The basic objective of the web server is to store, process and deliver web pages to the users. • This intercommunication is done using Hypertext Transfer Protocol (HTTP).
  • 7. • Program that understands the HTTP protocol and generates appropriate responses – Clients “connect” to the machine – Clients send a “request” – Server reads request, generates “response” – Client interprets response appropriately WHAT IS A WEB SERVER?
  • 8. WEB SERVERS Popular Web Servers Apache Windows IIS IBM Websphere Apache server is the most common web server available in the market. Apache is an open source software that handles almost 70 percent of all websites available today.
  • 10. PROVIDE HTTP PORT NUMBER : 8080
  • 14. WHAT IS WEB APPLICATION? • A web application is an application accessible from the web. A web application is composed of web components like Servlet, JSP, Filter etc. and other components such as HTML. The web components typically execute in Web Server and respond to HTTP request.
  • 17. Disadvantages of CGI 1. If number of clients increases, it takes more time for sending response. 2. It uses platform dependent language e.g. C, C++, perl. 3. For each request CGI Server receives, It creates new Operating System Process. 4. If the number of requests from the client increases then more time it will take to respond to the request. 5. As programs executed by CGI Script are written in the native languages such as C, C++, perl which are platform dependent.
  • 24. Advantages of Servlet  Performance  The performance of servlets is superior to CGI because there is no process creation for each client request.  Each request is handled by the servlet container process.  After a servlet has completed processing a request, it stays resident in memory, waiting for another request.  Portability  Like other Java technologies, servlet applications are portable.  Rapid development cycle  As a Java technology, servlets have access to the rich Java library that will help speed up the development process.  Robustness  Servlets are managed by the Java Virtual Machine.  Don't need to worry about memory leak or garbage collection, which helps you write robust applications.  Widespread acceptance  Java is a widely accepted technology.
  • 25. Life Cycle of Servlet Initialization init() Service service() doGet() doPost() doDelete() doHead() doTrace() doOptions() Destruction destroy() Concurrent Threads of Execution
  • 28. Life Cycle Methods • init() : – Servlet loads and initializes the servlet • service(): – Servlet handles one or more client Request and Responses to the client • destroy(): – Servlet is deactivated or server is terminated – Memory allocated for the servlet and its object are garbage collected Note: All above methods are inherited from GenericServlet class
  • 32. public void service(ServletRequest req,ServletResponse res) throws ServletException,IOException { res.setContentType("text/html"); // server responds in HTML format PrintWriter out=res.getWriter(); }
  • 33. Sample Servlet Example import java.io.*; import javax.servlet.*; public class ServletExample extends GenericServlet { public void service(ServletRequest req,ServletResponse res) throws ServletException,IOException { res.setContentType("text/html"); // server responds in HTML format PrintWriter out=res.getWriter(); out.println("<html>"); out.println("<body>"); out.println("Hello World..."); out.println("</body>"); out.println("</html>"); } }
  • 35. Web.xml(Deployment Descriptor) is an XML document that defines everything about your application that a server needs to know
  • 38. ServletContext and ServletConfig Both ServletContext and ServletConfig a re basically the configuration objects which are used by the servlet container to initialize the various parameter of a web application. But they have some difference in terms of scope and availability. Difference between ServletConfig vs. ServletContext
  • 39. • An object of ServletConfig is createdby the web container for each servlet. • This object can be used to get configuration information from web.xml file. • If the configuration information is modified from the web.xml file, we don't need to change the servlet. • So it is easier to manage the web application if any specific content is modified from time to time.
  • 41. ServletConfig ServletContext ServletConfig object is one per servlet class. ServletContext object is global to the entire web application. Object of ServletConfig will be created during the initialization process of the servlet. Object of ServletContext will be created at the time of web application deployment We have to give the request explicitly in order to create the ServletConfig object for the first time. ServletContext object can be available even before giving the first request. Scope: As long as a servlet is executing, the ServletConfig object will be available, it will be destroyed once the servlet execution is completed. Scope: As long as a web application is executing, the ServletContext object will be available, and it will be destroyed once the application is removed from the server. ServletConfig object is used while only one servlet requires information shared by it. ServletContext object is used while application requires information shared by it. getServletConfig() method is used to obtain Servletconfig object. getServletContext() method is used to obtain ServletContext object. In web.xml — tag will be appear under tag. In web.xml — tag will be appear under tag.
  • 42. Reading Initialization paramters • Sometimes we may have a requirement that a value keeps changing time to time and so we do not want to hard code it into a servlet. • If it is done, we will have to change the value and again recompile the servlet. ServletConfig config=getServletConfig(); String name=config.getInitParameter(“uname");
  • 45. ConfigDemo.java // Import required java libraries import java.io.*; import javax.servlet.*; import javax.servlet.http.*; // Extend HttpServlet class public class ConfigDemo extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Set response content type response.setContentType("text/html"); // Actual logic goes here. PrintWriter out = response.getWriter(); //get ServletConfig object. ServletConfig config=getInitServletConfig(); //get init parameter from ServletConfig object. String name= config.getParameter("username"); out.println("Welcome "+name); out.close() }}
  • 46. Reading Initialization Parameters in multiple import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class DemoServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); ServletConfig config=getServletConfig(); Enumeration<String> e=config.getInitParameterNames(); String str=""; while(e.hasMoreElements()){ str=e.nextElement(); out.print("<br>Name: "+str); out.print(" value: "+config.getInitParameter(str)); } out.close(); } }
  • 47. Reading Servlet Parameters <html> <body> <form action = "HelloForm" method = "GET"> First Name: <input type = "text" name = "first_name"> <br /> Last Name: <input type = "text" name = "last_name" /> <input type = "submit" value = "Submit" /> </form> </body> </html>
  • 48. How to read servlet parameters // Get enumeration of parameter names. Enumeration e = request.getParameterNames(); // Display parameter names and values. while(e.hasMoreElements()) { String pname = (String)e.nextElement(); pw.print(pname + " = "); String pvalue = request.getParameter(pname); pw.println(pvalue); }
  • 49. // Import required java libraries import java.io.*; import javax.servlet.*; import javax.servlet.http.*; // Extend HttpServlet class public class HelloForm extends HttpServlet { // Method to handle GET method request. public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Set response content type response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<html>" +"<ul>n" +”<li><b>First Name</b>: "+ request.getParameter("first_name") + "n" +" <li><b>Last Name</b>: " + request.getParameter("last_name") + "n" + "</ul>n" + " </html>" ); }
  • 52. • The HttpServletRequest Interface The HttpServletRequest interface enables a servlet to obtain information about a client request. • The HttpServletResponse Interface The HttpServletResponse interface enables a servlet to formulate an HTTP response to a client.
  • 53. • The HttpSession interface enables a servlet to read and write the state information that is associated with an HTTP session.. All of these methods throw an IllegalStateException if the session has already been invalidated.
  • 54. • Why use Session Tracking? • To recognize the user It is used to recognize the particular user. • Session Tracking Techniques • There are four techniques used in Session tracking: • Cookies • Hidden Form Field • URL Rewriting • HttpSession
  • 60. The names and values of cookies are stored on the user’s machine. Some of the information that is saved for each cookie includes the following: • The name of the cookie • The value of the cookie • The expiration date of the cookie • The domain and path of the cookie
  • 63. CREATING COOKIE PROGRAM Index.html <form method="post" action="validate"> Name:<input type="text" name="user" /><br/> Password:<input type="text" name="pass" ><br/> <input type="submit" value="submit"> </form> 11/6/2011 63 sayed@justetc.net
  • 64. MyServlet.java import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class MyServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); String name = request.getParameter("user"); String pass = request.getParameter("pass"); if(pass.equals("1234")) { Cookie ck = new Cookie("username",name); response.addCookie(ck); response.sendRedirect("First"); } } } 64
  • 65. First.java import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class First extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html "); PrintWriter out = response.getWriter(); Cookie[] cks = request.getCookies(); out.println("Welcome "+cks[0].getValue()); } } 11/6/2011 65 sayed@justetc.net
  • 67. HTTP SESSION  A session contains information specific to a particular user across the whole application. When a user enters into a website (or an online application) for the first time HttpSession is obtained via request.getSession(), the user is given a unique ID to identify his session.  The HttpSession stays alive until it has not been used for more than the timeout value specified in tag in deployment descriptor file( web.xml). The default timeout value is 30 minutes, this is used if you don’t specify the value in tag. This means that when the user doesn’t visit web application time specified, the session is destroyed by servlet container. The subsequent request will not be served from this session anymore, the servlet container will create a new session. 11/6/2011 67 sayed@justetc.net
  • 68.  Commonly used Methods of Servlet HttpSession  setAttribute(String name, Object value): Binds an object to this session, using the name specified. setMaxInactiveInterval(int interval): Specifies the time, in seconds, between client requests before the servlet container will invalidate this session. getAttribute(String name): Returns the object bound with the specified name in this session, or null if no object is bound under the name. getAttributeNames(): Returns an Enumeration of String objects containing the names of all the objects bound to this session. getId(): Returns a string containing the unique identifier assigned to this session. invalidate(): Invalidates this session then unbinds any objects bound to it. removeAttribute(String name): Removes the object bound with the specified name from this session. 11/6/2011 68 sayed@justetc.net
  • 69. sessionemo.html <html> <head> <title>session Demo</title> </head> <body> <form action="servlet1" method="post"> Enter Your Name:<input type="text" name="userName"/><br/><br/> <input type="submit" value="SUBMIT"/> </form> </body> </html> 11/6/2011 69 sayed@justetc.net
  • 70. SetSessionServlet.java import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class SetSessionServlet extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response){ try{ response.setContentType("text/html"); PrintWriter out = response.getWriter(); String name=request.getParameter("userName"); // Create a session object. HttpSession session = request.getSession(true); session.setAttribute("uname",name); 11/6/2011 70 sayed@justetc.net
  • 71. //creating submit button out.print("<br><form action='servlet2' method='post'>"); out.print("<input type='submit' value='View the session'>"); out.print("</form>"); out.close(); } catch(Exception e){ System.out.println(e); } }} 11/6/2011 71 sayed@justetc.net
  • 72. GetSessionServlet.java import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class GetSessionServlet extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response){ try{ response.setContentType("text/html"); PrintWriter out = response.getWriter(); HttpSession session=request.getSession(false); String name=(String)session.getAttribute("uname"); out.print("Hello!.. Welcome "+name); out.close(); }catch(Exception e){ System.out.println(e); } }} 11/6/2011 72 sayed@justetc.net
  • 75. HIDDEN FORM FIELD <form method="post" action="validate"> Name:<input type="text" name="user" /><br/> Password:<input type="text" name="pass" ><br/> <input type="submit" value="submit"> </form> 75
  • 76. FIRST.JAVA import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class First extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); //getting value submitted in form from HTML file String user = request.getParameter("user"); //creating a new hidden form field out.println("<form action='Second'>"); out.println("<input type='hidden' name='user' value='"+user+"'>"); out.println("<input type='submit' value='submit' >"); out.println("</form>"); } } 76
  • 77. SECOND.JAVA import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class Second extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); //getting parameter from the hidden field String user = request.getParameter("user"); out.println("Welcome "+user); } } 77
  • 79. URL REWRITING In URL rewriting, we append a token or identifier to the URL of the next Servlet or the next resource. We can send parameter name/value pairs using the following format: url?name1=value1&name2=value2&?? A name and a value is separated using an equal = sign, a parameter name/value pair is separated from another parameter using the ampersand(&). When the user clicks the hyperlink, the parameter name/value pairs will be passed to the server. From a Servlet, we can use getParameter() method to obtain a parameter value. 11/6/2011 sayed@justetc.net 79
  • 82. SESSION TRACKING 1.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. 2.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. 3.The Web Container uses this ID, finds the matching session with the ID and associates the session with the request. 11/6/2011 sayed@justetc.net 82
  • 83. INDEX.HTML <form method="post" action="Validate"> User: <input type="text" name="user" /><br/> Password: <input type="text" name="pass" ><br/> <input type="submit" value="submit"> </form> 11/6/2011 sayed@justetc.net 83
  • 84. VALIDATE.JAVA 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")) { //creating a session HttpSession session = request.getSession(); session.setAttribute("user", name); response.sendRedirect("Welcome"); } } } 11/6/2011 sayed@justetc.net 84
  • 85. WELCOME.JAVA 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(); HttpSession session = request.getSession(); String user = (String)session.getAttribute("user"); out.println("Hello "+user); }} 11/6/2011 sayed@justetc.net 85
  • 89. JAVA DATABASE CONNECTIVITY(JDBC) • Java Database Connectivity(JDBC) is an Application Programming Interface(API) used to connect Java application with Database. • JDBC is used to interact with various type of Database such as Oracle, MS Access, My SQL and SQL Server. • It allows java program to execute SQL statement and retrieve result from database.
  • 90. JDBC IN JAVA • Jdbc is a part of JDK software so no need to install separate software for Jdbc API • Jdbc API consists of two packages java.sql package javax.sql package
  • 92. • JDBC Architecture consists of two layers − JDBC API: This provides the application-to-JDBC Manager connection. JDBC Driver API: This supports the JDBC Manager-to- Driver Connection. • The JDBC API uses a driver manager and database-specific drivers to provide transparent connectivity to heterogeneous databases. • The JDBC driver manager ensures that the correct driver is used to access each data source.
  • 93. JDBC DRIVER • JDBC Driver is a software component that enables java application to interact with the database. • Types of drivers JDBC-ODBC bridge driver Native-API driver (partially java driver) Network Protocol driver (fully java driver) Thin driver (fully java driver)
  • 94. TYPE 1 : JDBC-ODBC BRIDGE DRIVER • The JDBC-ODBC is also known as Type 1 driver. • The JDBC-ODBC bridge driver converts the JDBC method call into the ODBC function call. • This driver is platform dependent. • Sun provides the JDBC-ODBC Bridge driver by following URL - “sun.jdbc.odbc.JdbcOdbcDriver” • Advantage  Easy to use  Allow easy connectivity to all database supported by the ODBC Driver. • Disadvantage • Slow execution time • Dependent on ODBC Driver.
  • 96. TYPE 2 : NATIVE API DRIVER (PARTIAL JAVA DRIVER) • The Native API driver is also known as Type 2 driver. • It uses the client-side libraries of the database. • must be installed on each client system. • This driver converts the JDBC method call into native call of database.
  • 97. Advantage faster as compared to Type-1 Driver Disadvantage Requires native library Type 2 driver is platform dependent. It does not support applet programming.
  • 98. TYPE 3 : NETWORK PROTOCOL DRIVER • The Network protocol driver uses the three- tier model. • The middle tier is responsible to converts JDBC calls directly or indirectly into vender specific database protocol. • This type of driver is very flexible that is a single driver can actually provide access to multiple databases.
  • 99. Advantage Does not require any native library to be installed. Database Independency. Disadvantage Slow due to increase number of network call.
  • 100. TYPE 4 : THIN DRIVER (PURE JAVA DRIVER) • It is a pure Java driver which connects all Java drivers directly to the vendor specific database protocol. • This driver provides the highest performance driver for the database. • Thin driver is completely written in Java because of that it is known as 100% pure Java driver.
  • 102. JDBC - SQL SYNTAX • Create Database CREATE DATABASE DATABASE_NAME; Create a Database named EMP ? CREATE DATABASE EMP; • Drop Database DROP DATABASE DATABASE_NAME; • Create Table CREATE TABLE table_name ( column_name column_data_type, column_name column_data_type, column_name column_data_type ... );
  • 103. CREATE TABLE Employees ( id INT NOT NULL, INT NOT NULL, age first last VARCHAR(255), VARCHAR(255), PRIMARY KEY ( id ) ); CREATE AN EMPLOYEE TABLE? INSERT Data: INSERT INTO ...); table_name VALUES (column1, column2,
  • 104. INSERT A NEW ROW IN THE EMPLOYEES DATABASE CREATED EARLIER ? INSERT INTO Employees VALUES (100, 18, ‘cse', ‘vnr'); SELECT Data SELECT column_name, column_name, ... FROM table_name WHERE conditions; The WHERE clause can use the comparison operators such as =, ! =, <, >, <=,and >=, as well as the BETWEEN and LIKE operators.
  • 105. • To select the age, first and last columns from the Employees table, where id column is 100 ? • SELECT FROM WHERE first, last, age Employees id = 100; • UPDATE Data UPDATE table_name SET column_name = value, WHERE conditions; column_name = value, ...
  • 106. • To UPDATE statement changes the age column of the employee whose id is 100 ? • UPDATE Employees SET age=20 WHERE id=100; • DELETE Data • DELETE FROM table_name WHERE conditions; • DELETE statement deletes the record of the employee whose id is 100 ? • DELETE FROM Employees WHERE id=100;
  • 107. STEPS TO CONNECT A JAVA APPLICATION TO DATABASE 1. Register the Driver 2. Create a Connection 3. Create SQL Statement 4. Execute SQL Statement 5. Closing the connection
  • 108. • Register the Driver Class.forName() is used to load the driver class explicitly. • Example to register with JDBC-ODBC Driver Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); • Create a Connection getConnection() method of DriverManager class is used to create a connection.
  • 109. DRIVERMANAGER CLASS • Syntax getConnection(String url) getConnection(String url, String username, String password) getConnection(String url, Properties info) Example establish connection with Oracle Driver Connection con = DriverManager.getConnection("jdbc:odbc:DSN","username", "password");
  • 110. CREATE SQL STATEMENT • The Connection interface provides the createStatement() method to create SQL statement. • Syntax: public Statement createStatement( ) throws SQLException • Example: Statement stmt = con.createStatement();
  • 111. EXECUTE SQL QUERIES • The Statement interface provides the executeQuery( ) method to execute SQL statements. • Syntax: public ResultSet executeQuery(String sql) throws SQLException
  • 112. • Example: • ResultSet rs = stmt.executeQuery("select * from students"); while (rs.next()) { System.out.println (rs.getInt(1)+" "+rs.getString(2)+" "+rs.getFloat(3)); } • Closing the Connection • The Connection interface provides close( ) method, used to close the connection. • Example: con.close( );
  • 113. STATEMENT INTERFACE IN JDBC • The Statement interface provides methods to execute queries with the database.
  • 114. RESULTSET INTERFACE IN JDBC • The object of ResultSet maintains a cursor pointing to a particular row of data. Initially, cursor points to before the first row.
  • 116. HOW TO CREATE JDBC CONNECTION?
  • 118. WHAT ARE THE TYPES OF JDBC STATEMENTS AVAILABLE? • There are 3 types of Statements, as given below: Statement: It can be used for general-purpose access to the database. It is useful when you are using static SQL statements at runtime. PreparedStatement: It can be used when you plan to use the same SQL statement many times. The PreparedStatement interface accepts input parameters at runtime. CallableStatement: CallableStatement can be used when you want to access database stored procedures.
  • 119. CONNECTION CON; PreparedStatement pstmt = con.prepareStatement("sql command"); Example: PreparedStatement pstmt = con.prepareStatement("Insert into emp value(?, ?)"); The each ? represent the column index number in the table. If table EMP has id, name columns, then 1st ? refer to id, 2nd ? refer to name. Afterthat we need to set the value to each ? by using the setter method from PreparedStatement interface as follows : Syntax : setXXX(ColumnIndex, value)
  • 121. PREPAREDSTATEMENT INTERFACE • It represents precompiled SQL statements and stores it in a PreparedStatement object. • It increases the performance of the application because the query is compiled only once. • The PreparedStatement is easy to reuse with new parameters.
  • 123. CREATING PREPAREDSTATEMENT OBJECT • Syntax Connection con; PreparedStatement String sql = pstmt = con.prepareStatement("sql command"); "Select * from Student where rollNo= ?"; • PreparedStatement ps = con.prepareStatement(sql);
  翻译: