You are on page 1of 28

JDBC

Topics to be covered
 JDBC
 Architecture
 Components
 Demo program
 SERVLETS
 Lifecycle
 Servlet deployment
 Session
What is JDBC?
Java database
connectivity (JDBC) is
the Java Soft
specification of a
standard application
programming interface
(API) that allows Java
programs to access
database management
systems. The JDBC API
consists of a set of
interfaces and classes
written in the Java
programming language.
JDBC Architecture
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. The driver
manager is capable of supporting
multiple concurrent drivers
connected to multiple heterogeneous
databases
JDBC Components

 The JDBC API provides the following interfaces and classes −


 Driver Manager: This class manages a list of database drivers. Matches connection requests from the java
application with the proper database driver using communication sub protocol. The first driver that recognizes a
certain subprotocol under JDBC will be used to establish a database Connection.
 Driver: This interface handles the communications with the database server. You will interact directly with Driver
objects very rarely. Instead, you use Driver Manager objects, which manages objects of this type. It also abstracts
the details associated with working with Driver objects.
 Connection: This interface with all methods for contacting a database. The connection object
represents communication context, i.e., all communication with database is through connection object
only.
 Statement: You use objects created from this interface to submit the SQL statements to the database.
Some derived interfaces accept parameters in addition to executing stored procedures.
 Result Set: These objects hold data retrieved from a database after you execute an SQL query using
Statement objects. It acts as an iterator to allow you to move through its data.
 SQL Exception: This class handles any errors that occur in a database application.
JDBC Program

 package DAY1;
 public class JdbcDemo1 {
 public static void main(String[] args) {
 JdbccDao jdbcDao = new JdbccDao();
 jdbcDao.getConnection();
 }
 }
JDBC Program
 import java.sql.Connection;
,password)value
 import java.sql.DriverManager; ('bindhu',520.520,'bindhu520','password')");
 import java.sql.SQLException;  } catch (ClassNotFoundException e) {
 import com.mysql.cj.xdevapi.Statement;  e.printStackTrace();
 public class JdbccDao {  } catch (SQLException e) {
 public void getConnection() {  e.printStackTrace();
 String URL = "jdbc:mysql://localhost:3306/CSE_b";  } finally{
 Connection con = null;  try {
 try {  con.close();
 Class.forName("com.mysql.cj.jdbc.Driver");  } catch (SQLException e) {
 con = DriverManager.getConnection(URL,"root","tiger");  e.printStackTrace();
 Statement st = (Statement) con.createStatement();  } }
 }private Object Update(String string) {
 ((java.sql.Statement) st).executeUpdate("insert into
employee (empName,salary,loginId  return null;}}
SERVLETS
 Servlets are Java classes which service HTTP requests and implement the
javax.servlet.Servlet interface. Web application developers typically write
servlets that extend javax.servlet.http.HttpServlet, an abstract class that
implements the Servlet interface and is specially designed to handle HTTP
requests.
 Steps to run servlets:
 First create a new web application.
 Add new servlet to the web application.
 Run the servlet
 The servlet in action.
War File

 A war (web archive) File contains files of a web project. It may have servlet, xml, jsp, image, html, css, js
etc. files.
 Here, we will discuss what is war file, how to create war file, how to deploy war file and how to extract war
file.
 To create war file, you need to use jar tool of JDK. You need to use -c switch of jar, to create the war file.
 Go inside the project directory of your project (outside the WEB-INF), then write the following command:
jar -cvf projectname.war *  
 Here, -c is used to create file, -v to generate the verbose output and -f to specify the archive file name.
The * (asterisk) symbol signifies that all the files of this directory (including sub directory).
 o extract the war file, you need to use -x switch of jar tool of JDK. Let's see the command to extract the war
file.
jar -xvf projectname.war  
Servlets example
// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
// Extend HttpServlet class
public class HelloWorld extends HttpServlet {
private String message;
public void init() throws ServletException {
// Do required initialization
message = "Hello World";
} public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Set response content type
response.setContentType("text/html");
// Actual logic goes here.
PrintWriter out = response.getWriter();
out.println("<h1>" + message + "</h1>");
} public void destroy() {
// do nothing.
}}
Compiling a Servlet

Let us create a file with name HelloWorld.java with the code shown above. Place this file at C:\ServletDevel (in Windows) or at
/usr/ServletDevel (in Unix). This path location must be added to CLASSPATH before proceeding further.
Assuming your environment is setup properly, go in ServletDevel directory and compile HelloWorld.java as follows −
$ javac HelloWorld.java
If the servlet depends on any other libraries, you have to include those JAR files on your CLASSPATH as
well. I have included only servlet-api.jar JAR file because I'm not using any other library in Hello World
program.
This command line uses the built-in javac compiler that comes with the Sun Microsystems Java Software
Development Kit (JDK). For this command to work properly, you have to include the location of the Java
SDK that you are using in the PATH environment variable. If everything goes fine, above compilation would
produce HelloWorld.class file in the same directory. Next section would explain how a compiled servlet
would be deployed in production.
Servlet Deployment

A servlet application is located at the path <Tomcat-installationdirectory>/webapps/ROOT


and the class file would reside in <Tomcat-installationdirectory>/webapps/ROOT/WEB-
INF/classes.
If you have a fully qualified class name of com.myorg.MyServlet, then this servlet class
must be located in WEB-INF/classes/com/myorg/MyServlet.class.
For now, let us copy HelloWorld.class into <Tomcat-
installationdirectory>/webapps/ROOT/WEB-INF/classes and create following entries in
web.xml file located in <Tomcat-installation-directory>/webapps/ROOT/WEB-INF/
<servlet>
<servlet-name>HelloWorld</servlet-name>
<servlet-class>HelloWorld</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloWorld</servlet-name>
<url-pattern>/HelloWorld</url-pattern>
</servlet-mapping>
Servlet lifecycle

 A servlet life cycle can be defined as the entire


process from its creation till the destruction. The
following are the paths followed by a servlet.
 The servlet is initialized by calling the init() method.
 The servlet calls service() method to process a
client's request.
 The servlet is terminated by calling the destroy()
method.
 Finally, servlet is garbage collected by the garbage
collector of the JVM
Creating the form in eclipse IDE

 Creating new Html form


 Create new servlet.
 Hello servlet in action
 Hello servlet – HTTP request.
Servlet Session:
Session simply means a particular interval of time.
Session Tracking is a way to maintain state (data) of
an user. It is also known as session management in
servlet.
Http protocol is a stateless so we need to maintain state
using session tracking techniques. Each time user
requests to the server, server treats the request as the
new request. So we need to maintain the state of an
user to recognize to particular user.
HTTP is stateless that means each request is
considered as the new request. It is shown in the figure
given :
Session Tracking Techniques

There are four techniques used in Session tracking:


 Cookies
 Login & logout
 Hidden Form Field
 URL Rewriting
 HttpSession
Servlet Login and Logout Example using Cookies

 A cookie is a kind of information that is stored at client side.


 In the previous page, we learned a lot about cookie e.g. how to create cookie, how to delete cookie, how to get cookie etc.
 Here, we are going to create a login and logout example using servlet cookies.
 In this example, we are creating 3 links: login, logout and profile. User can't go to profile page until he/she is logged in. If user is
logged out, he need to login again to visit profile.
 In this application, we have created following files.
o index.html
o link.html
o login.html
o LoginServlet.java
o LogoutServlet.java
o ProfileServlet.java
o web.xml
Index.html Link.html

 <!DOCTYPE html>    <a href="login.html">Login</a> |  
 <html>    <a href="LogoutServlet">Logout</a> 
 <head>    <a href="ProfileServlet">Profile</a>  
 <meta charset="ISO-8859-1">  
 <hr>  
 <title>Servlet Login Example</title>  
 </head>  
 <body>  
 <h1>Welcome to Login App by Cookie</h1>  
 <a href="login.html">Login</a>|  
 <a href="LogoutServlet">Logout</a>|  
 <a href="ProfileServlet">Profile</a>  
 </body>  
 </html>  
login.html

1. <form action="LoginServlet" method="post">  
2. Name:<input type="text" name="name"><br>  
3. Password:<input type="password" name="password"><br>  
4. <input type="submit" value="login">  
5. </form>  
LoginServlet.java

        request.getRequestDispatcher("link.html").incl
package com.javatpoint;  
import java.io.IOException;   ude(request, response); 
        String name=request.getParameter("name");  
import java.io.PrintWriter;  
        String password=request.getParameter("pass
import javax.servlet.ServletException;  
import javax.servlet.http.Cookie;   word");  
        if(password.equals("admin123")){  
import javax.servlet.http.HttpServlet;  
            out.print("You are successfully logged in!");  
import javax.servlet.http.HttpServletRequest;  
            out.print("<br>Welcome, "+name);   
import javax.servlet.http.HttpServletResponse;  
            Cookie ck=new Cookie("name",name);  
public class LoginServlet extends HttpServlet {  
            response.addCookie(ck);  
    protected void doPost(HttpServletRequest re
        }else{  
quest, HttpServletResponse response)               out.print("sorry, username or password error
                           throws ServletException, IOEx
!");  
ception {               request.getRequestDispatcher("login.html").i
        response.setContentType("text/html");  
 PrintWriter out=response.getWriter();   nclude(request, response);  
        }out.close();  

    }  }  
web.xml
 <?xml version="1.0" encoding="UTF-8"?>            <display-name>ProfileServlet</display-name>  
 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-      <servlet-name>ProfileServlet</servlet-name>  
instance"   
     <servlet-class>com.javatpoint.ProfileServlet</servlet-class>  
 xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://j
ava.sun.com/xml/ns/javaee   
   </servlet>   <servlet-mapping>  

 http://java.sun.com/xml/ns/javaee/web-
     <servlet-name>ProfileServlet</servlet-name>  
app_2_5.xsd" id="WebApp_ID" version="2.5">        <url-pattern>/ProfileServlet</url-pattern>  
   <servlet>      </servlet-mapping>  <servlet>  
     <description></description>        <description></description>  
     <display-name>LoginServlet</display-name>        <display-name>LogoutServlet</display-name>  
     <servlet-name>LoginServlet</servlet-name>        <servlet-name>LogoutServlet</servlet-name>  
     <servlet-class>com.javatpoint.LoginServlet</servlet-class>        <servlet-class>com.javatpoint.LogoutServlet</servlet-class>  
   </servlet>      </servlet>   <servlet-mapping>  
   <servlet-mapping>        <servlet-name>LogoutServlet</servlet-name>  
     <servlet-name>LoginServlet</servlet-name>        <url-pattern>/LogoutServlet</url-pattern>  
     <url-pattern>/LoginServlet</url-pattern>      </servlet-mapping>  
   </servlet-mapping>    </web-app>  
   <servlet>  
 <description></description>  
OUTPUTS
THANK YOU

You might also like