UNIT-5

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 54

Java Database

Connectivity
Connecting to Database in Java
using JDBC
• Java provides a mechanism to interact with databases using JDBC
(Java Database Connectivity), which allows Java applications to
execute SQL queries and access relational databases (like MySQL,
PostgreSQL, etc.).
JDBC Overview
JDBC (Java Database Connectivity):
• It is a standard Java API to connect Java programs with relational databases.
• It provides methods for querying and updating data.
JDBC Architecture:
• Application: Your Java code.
• JDBC API: Standard interfaces to communicate with the database.
• Driver Manager: Loads database drivers.
• JDBC Driver: A specific driver implementation for the targeted database.
• Database: The actual relational database you connect to (e.g., MySQL, Oracle,
etc.).
JDBC Drivers
• A JDBC Driver acts as a bridge between Java applications and the
database.
• Common JDBC drivers are:
• Type 1: JDBC-ODBC Bridge (deprecated).
• Type 2: Native-API Driver (requires native libraries).
• Type 3: Network Protocol Driver (acts as middleware).
• Type 4: Thin Driver (pure Java driver, directly communicates with the
database).
Most modern applications use Type 4 drivers.
Example Drivers:
MySQL: com.mysql.cj.jdbc.Driver
PostgreSQL: org.postgresql.Driver
Steps to Connect to a Database
using JDBC
1. Load the Driver
This step registers the driver with the DriverManager.

Class.forName("com.mysql.cj.jdbc.Driver"); // MySQL Driver

2. Establish the Connection


Using the DriverManager, you create a connection to the database.

Connection conn = DriverManager.getConnection(“<Path>", "username",


"password");

Ex path: jdbc:mysql://localhost:3306/mydatabase
3. Create a Statement

A Statement object is used to execute SQL queries.

Statement stmt = conn.createStatement();

4. Execute Queries and Retrieve Results

Use executeQuery() or executeUpdate() methods to interact with the database.

ResultSet rs = stmt.executeQuery("SELECT * FROM users");

Note:
The executeQuery() returns an object of ResultSet, which points to the output set
of query result.
5. Process the Result Set
You can loop through the ResultSet to get the data.
while (rs.next())
{
System.out.println(rs.getInt("id") + " " + rs.getString("name"));
}

6. Close the Resources


Always close the Connection, Statement and ResultSet to avoid memory leaks.
rs.close();
stmt.close();
conn.close();
Some of the important methods in ResultSet:
• boolean next()
• boolean previous()
• boolean first()
• boolean last()
• getInt(String columnLabel)
• getString(String columnLabel)
• getDouble(String columnLabel)
• getDate(String columnLabel)
• getBoolean(String columnLabel)
• ResultSetMetaData getMetaData()
MySQL connector for java
• https://dev.mysql.com/downloads/connector/j/

• Windows: command line


Download the MySQL Connecter-> it a JAR file and save in your project
location
• javac -cp .; mysql-connector-j-9.1.0.jar MySQLDemo.java
• java -cp .; mysql-connector-j-9.1.0.jar MySQLDemo
• Here . Indicates current path, if connector is located in a different path
mention the path name completely
• If you are using Eclipse:
• Right-click your project → Properties → Java Build Path → Libraries → Add
External JARs...
Statements and their Types

Statement
Used for executing simple SQL queries.

Statement stmt = conn.createStatement();

stmt.executeQuery("SELECT * FROM users");


PreparedStatement

Used for parameterized queries to prevent SQL injection.

PreparedStatement pstmt

= conn.prepareStatement("SELECT * FROM users WHERE id = ?");

pstmt.setInt(1, 5); // Replace '?' with the value 5.

ResultSet rs = pstmt.executeQuery();
CallableStatement

Used to call stored procedures from the database.

CallableStatement cstmt = conn.prepareCall("{call getUserById(?)}");

cstmt.setInt(1, 5);

ResultSet rs = cstmt.executeQuery();
CRUD Operations using JDBC
CRUD stands for Create, Read, Update, and Delete. These are the basic
operations performed on a database.
Create (Insert)

String sql = "INSERT INTO users (name, email) VALUES (?, ?)";

PreparedStatement pstmt = conn.prepareStatement(sql);

pstmt.setString(1, "Alice");

pstmt.setString(2, "alice@example.com");

pstmt.executeUpdate();
Read (Select)

String sql = "SELECT * FROM users";

Statement stmt = conn.createStatement();

ResultSet rs = stmt.executeQuery(sql);

while (rs.next())

System.out.println(rs.getString("name") + " - " +


rs.getString("email"));

}
Update

String sql = "UPDATE users SET email = ? WHERE id = ?";

PreparedStatement pstmt = conn.prepareStatement(sql);

pstmt.setString(1, "newemail@example.com");

pstmt.setInt(2, 1);

pstmt.executeUpdate();
Delete

String sql = "DELETE FROM users WHERE id = ?";

PreparedStatement pstmt = conn.prepareStatement(sql);

pstmt.setInt(1, 1);

pstmt.executeUpdate();
Closing Resources Properly
Ensure that you always close resources to prevent memory leaks:

if (rs != null) rs.close();

if (stmt != null) stmt.close();

if (conn != null) conn.close();


Introduction to Servlets
• A Servlet is a Java program that runs on a web server and handles
requests from web clients (usually browsers).

• It’s a way to generate dynamic web content, such as HTML pages, by


processing data sent by the user.

Why use Servlets?

• Unlike static HTML, servlets can process user input, interact with
databases, and create responses based on user actions.
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 elements such as HTML, CSS, and JavaScript. The web
components typically execute in Web Server and respond to the HTTP
request.
CGI (Common Gateway Interface)

CGI technology enables the web server to call an external program and
pass HTTP request information to the external program to process the
request. For each request, it starts a new process
Disadvantages of CGI

• There are many problems in CGI technology:

1.If the number of clients increases, it takes more time to send


the response.

2.For each request, it starts a process, and the web server is


limited to start processes.

3.It uses platform-dependent language e.g. C, C++, perl.


Advantages of Servlet

There are many advantages of Servlet over CGI. The web container creates threads
for handling the multiple requests to the Servlet. Threads have many benefits
over the Processes such as they share a common memory area, are lightweight, and
the cost of communication between the threads are low.
The advantages of Servlet are as follows:
1.Better performance: because it creates a thread for each request, not process.
2.Portability: because it uses Java language.
3.Robust: JVM manages Servlets, so we don't need to worry about the memory leak,
Servlet Life Cycle
A servlet's lifecycle consists of three main stages:

• Initialization (init): The servlet is initialized and loaded.


• Service (service): The servlet handles requests (doGet, doPost,
etc.).
• Destruction (destroy): The servlet is cleaned up when the web
application shuts down.
Creating a Servlet in a Java Program
• Can use
• Servlet Interface
• HttpServlet Class
1. Servlet Interface
Definition: The Servlet interface is the core interface in the servlet API. It defines the basic methods that
every servlet must implement, regardless of the protocol (e.g., HTTP, FTP, etc.) being used.

Purpose: It provides a general contract for servlets. By itself, Servlet does not assume any specific
communication protocol, making it protocol-independent.

Methods in Servlet Interface:

 init(ServletConfig config): Initializes the servlet with configuration parameters.

 service(ServletRequest req, ServletResponse res): Processes client requests. This is the core method
every servlet must implement, and it handles requests and responses.

 destroy(): Called before the servlet is destroyed to release resources.

 getServletConfig(): Returns the servlet's configuration object (typically used for initialization parameters).

 getServletInfo(): Returns metadata about the servlet (e.g., author or version).


• When to Use Servlet Interface?

• Directly implementing the Servlet interface is rare. It’s generally more


cumbersome because you have to implement all methods, even if you don’t need
them. Instead, it’s more common to extend HttpServlet, which simplifies
working with HTTP-specific requests.
2. HttpServlet Class
Definition: HttpServlet is an abstract class provided in the javax.servlet.http package that extends the
GenericServlet class and implements the Servlet interface. (javax is now changed jakatra.servlet)

Purpose: It’s specifically designed to handle HTTP requests, which are commonly used for web
applications. HttpServlet provides useful methods like doGet, doPost, doPut, and doDelete that make
handling HTTP requests easier.

• Key HTTP Methods in HttpServlet:

 doGet(HttpServletRequest req, HttpServletResponse res): Handles HTTP GET requests.

 doPost(HttpServletRequest req, HttpServletResponse res): Handles HTTP POST requests.

 doPut(HttpServletRequest req, HttpServletResponse res): Handles HTTP PUT requests.

 doDelete(HttpServletRequest req, HttpServletResponse res): Handles HTTP DELETE requests.


• When to Use HttpServlet Class?

 Use HttpServlet when building a web application that primarily communicates using the HTTP
protocol.

 HttpServlet provides built-in HTTP methods (doGet, doPost, etc.) that simplify handling web-
based requests.
• It’s more efficient and simpler because you don’t have to handle each HTTP method in a
single service method as you would with the Servlet interface
Request and Response Methods
Servlets handle HTTP requests (like GET or POST) from users and
respond back.
• doGet() handles GET requests (like typing a URL in the browser).
• doPost() handles POST requests (like form submissions).
Writing the doGet() Method
• The doGet() method handles HTTP GET requests, which are typically
used to request data from the server (e.g., fetching a web page,
retrieving information).
Key Steps in doGet()
1. Set Content Type: res.setContentType("text/html"); - Specifies the
type of response (HTML in this case).
2. Write Response: Use PrintWriter to send content back to the client.
This could be HTML, JSON, XML, etc.
3. Close the Writer: Always close PrintWriter to ensure all data is
flushed to the client.
Content types
1. text/html: Used for sending HTML content. This is the default for
web pages.
Example: res.setContentType("text/html");
2. text/plain: Used for plain text files with no special formatting.
Example: res.setContentType("text/plain");
3. application/json: Used for sending JSON data, commonly in APIs.
Example: res.setContentType("application/json");
4. application/xml: Used for XML data.
Example: res.setContentType("application/xml");
5. text/css: Used for CSS (Cascading Style Sheets).
Example: res.setContentType("text/css");
6. text/javascript or application/javascript: Used for JavaScript files.
Example: res.setContentType("application/javascript");
7. image/png, image/jpeg, image/gif: Used for different types of
image files.
• res.setContentType("image/png");

• res.setContentType("image/jpeg");

• res.setContentType("image/gif");

8. application/pdf: Used for PDF documents.


Example: res.setContentType("application/pdf");
9. application/zip or application/x-zip-compressed: Used for ZIP files.
Example: res.setContentType("application/zip");
10. multipart/form-data: Used for file uploads in forms.
Example: In a request for handling file uploads
11. audio/mpeg and audio/ogg: Used for audio files.
• res.setContentType("audio/mpeg"); // For MP3 files

• res.setContentType("audio/ogg"); // For OGG files

12. video/mp4 and video/webm: Used for video files


• res.setContentType("video/mp4");

• res.setContentType("video/webm");
PrintWriter
• When a servlet generates a response, it can retrieve a PrintWriter object by
calling the getWriter() method on the HttpServletResponse object.
• This PrintWriter object provides a convenient way to write character data to
the response.
Steps to Use PrintWriter
• Set Content Type: Before getting the PrintWriter, set the content type for
the response with res.setContentType("text/html") (or another MIME type
depending on the content).
• Get the Writer: Use res.getWriter() to obtain the PrintWriter for the
response.
• Write Data: Use PrintWriter's print() or println() methods to write the
response data (e.g., HTML, JSON).
• Close the Writer: Always call out.close() to flush the output and release
resources.
PrintWriter Methods
print(): Writes data without adding a new line.
Example: out.print("Hello ");
println(): Writes data followed by a newline.
Example: out.println("World!");
printf(): Supports formatted output similar to System.out.printf.
Example: out.printf("Your score is %d points.", score);
Writing the doPost() Method
The doPost() method handles HTTP POST requests, which are used when the client
submits data to the server (e.g., form submissions, uploading files).
Key Steps in doPost()

1. Set Content Type: res.setContentType("text/html"); - Indicates the type of response.

2. Retrieve Parameters: Use req.getParameter("paramName"); to retrieve form data sent from the
client.

3. Write Response: Use PrintWriter to construct the response, typically confirming data submission
or displaying entered information.

4. Close the Writer: Always close PrintWriter.


Differences between doGet() and doPost()

 Purpose: doGet() is used for retrieving data, while doPost() is used for submitting data.

 Data Length: GET requests have limitations on the data length (URL length), while POST can send larger
amounts of data.

 URL Encoding: GET parameters are appended to the URL, while POST parameters are part of the request
body, making POST more secure for sensitive data.
Servlet Collaboration

• Servlet collaboration refers to one servlet interacting with another


servlet to fulfill a request. Two common techniques are:
 Request Dispatcher: Forwarding or including another servlet.
 Servlet Chaining: Sending a request to another servlet in a chain-like
manner.
public class FirstServlet extends HttpServlet { public class SecondServlet extends
HttpServlet {
protected void doGet(HttpServletRequest
request, HttpServletResponse response) protected void
throws ServletException, IOException { doGet(HttpServletRequest request,
request.setAttribute("message", "Hello HttpServletResponse response) throws
from FirstServlet"); ServletException, IOException {
RequestDispatcher dispatcher = String message = (String)
request.getRequestDispatcher("SecondServl request.getAttribute("message");
et");

dispatcher.forward(request, response); response.getWriter().println(message);


} }
}
}
ServletConfig vs ServletContext
 ServletConfig: Configuration settings for a specific servlet. It’s used to get
initialization parameters for the servlet.
 ServletContext: Shared configuration for the entire web application. It’s used for
application-wide parameters and resources.
public class ConfigContextServlet extends HttpServlet

public void init(ServletConfig config) throws ServletException

String servletParam = config.getInitParameter("servletParam");

System.out.println("Servlet Parameter: " + servletParam);

ServletContext context = config.getServletContext();

String contextParam = context.getInitParameter("contextParam");

System.out.println("Context Parameter: " + contextParam);

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException

response.getWriter().println("Check console for ServletConfig and ServletContext values.");

}
Java Server Pages
JavaServer Pages (JSP)
• JavaServer Pages (JSP) is a server-side technology that allows
developers to create dynamic, platform-independent web
applications by embedding Java code in HTML.
• JSP is built on top of Java Servlets, allowing for a more convenient
way to create web content.
• It can be thought of as an extension to Servlet because it provides
more functionality than servlet such as expression language, JSTL
(JavaServer Pages Standard Tag Library), etc.
• It is used to build dynamic web pages where the content is generated
on the server before being sent to the user's browser.
Advantages of JSP over Servlet
1) Extension to Servlet
2) Easy to maintain
3) Fast Development: No need to recompile and redeploy
4) Less code than Servlet
The Lifecycle of a JSP Page
• Translation of JSP Page
• Compilation of JSP Page
• Class loading (the class-loader loads class file)
• Instantiation (Object of the Generated Servlet is created).
• Initialization ( the container invokes jspInit() method).
• Request processing ( the container invokes _jspService() method).
• Destroy ( the container invokes jspDestroy() method).
• The JSP translator is a
part of the web server
which is responsible for
translating the JSP
page into Servlet.
• After that, Servlet
page is compiled by
the compiler and gets
converted into the
class file.
• Moreover, all the
processes that happen
in Servlet are
performed on JSP later
Directory structure of JSp
The JSP API

The JSP API consists of two packages:


• javax.servlet.jsp
• javax.servlet.jsp.tagext
javax.servlet.jsp package:
The javax.servlet.jsp package has two interfaces and classes.
The two interfaces are as follows:
• JspPage
• HttpJspPage
The classes are as follows:
•JspWriter
•PageContext
•JspFactory
•JspEngineInfo
•JspException
The JspPage interface
Methods of JspPage interface
1.public void jspInit():
It is invoked only once
during the life cycle of the JSP
when JSP page is requested
firstly. It is used to perform
initialization. It is same as the
init() method of Servlet interface.
2.public void jspDestroy():
It is invoked only once during
the life cycle of the JSP before
the JSP page is destroyed. It can
be used to perform some clean up
HttpJspPage interface

• The HttpJspPage interface provides the one life cycle method


of JSP. It extends the JspPage interface.
Method of HttpJspPage interface:

1.public void _jspService():


It is invoked each time when request for the JSP page
comes to the container. It is used to process the request.
The underscore _ signifies that you cannot override this method.
Instead, it's auto-generated based on the content and structure of your JSP.
In generated servlet it is declared as final.
JSP Scriptlet tag (Scripting elements)
In JSP, java code can be written inside the jsp page using the scriptlet tag. Let's
see what are the scripting elements first.
JSP Scripting elements
The scripting elements provides the ability to insert java code inside the jsp.
There are three types of scripting elements:
•scriptlet tag : The scriptlet tag allows embedding Java code
directly in the JSP page. This code is added to the generated servlet’
<% java source code %>
•expression tag: The expression tag is used to output the result of a
Java expression directly to the client’s web page.
<%= Java Expression %>
•declaration tag : The declaration tag is used to declare variables or
methods at the class level in the JSP-generated servlet
<%! Java Code %>
Simple jsp code :

<body>
<%
int counter = 10;
counter++;
out.println("Counter value: " + counter);
%>
</body>

Here out.println() will print on browser instead of console as like


System.out.println

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy