UNIT-5
UNIT-5
UNIT-5
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.
Ex path: jdbc:mysql://localhost:3306/mydatabase
3. Create a Statement
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"));
}
Statement
Used for executing simple SQL queries.
PreparedStatement pstmt
ResultSet rs = pstmt.executeQuery();
CallableStatement
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 (?, ?)";
pstmt.setString(1, "Alice");
pstmt.setString(2, "alice@example.com");
pstmt.executeUpdate();
Read (Select)
ResultSet rs = stmt.executeQuery(sql);
while (rs.next())
}
Update
pstmt.setString(1, "newemail@example.com");
pstmt.setInt(2, 1);
pstmt.executeUpdate();
Delete
pstmt.setInt(1, 1);
pstmt.executeUpdate();
Closing Resources Properly
Ensure that you always close resources to prevent memory leaks:
• 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 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:
Purpose: It provides a general contract for servlets. By itself, Servlet does not assume any specific
communication protocol, making it protocol-independent.
service(ServletRequest req, ServletResponse res): Processes client requests. This is the core method
every servlet must implement, and it handles requests and responses.
getServletConfig(): Returns the servlet's configuration object (typically used for initialization parameters).
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.
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");
• 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()
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.
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
}
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
<body>
<%
int counter = 10;
counter++;
out.println("Counter value: " + counter);
%>
</body>