Here's an example Java web application using JDBC to retrieve data from a PostgreSQL database and display it on a web page:
-
First, you need to add the PostgreSQL JDBC driver to your project's classpath. You can download it from the PostgreSQL website and include the JAR file in your project's lib folder.
-
Create a Java servlet class that will handle HTTP requests from the client and fetch data from your PostgreSQL database:
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class DataServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
try {
// Load the PostgreSQL JDBC driver
Class.forName("org.postgresql.Driver");
// Connect to the database
Connection con = DriverManager.getConnection("jdbc:postgresql://localhost:5432/your_database_name", "username", "password");
// Create a statement to execute the SQL query
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT data_field FROM your_table_name");
// Loop through the result set and output data to the web page
while (rs.next()) {
String data = rs.getString("data_field");
out.println("<p>" + data + "</p>");
}
} catch (Exception e) {
out.println("Error: " + e.getMessage());
}
}
}
- Map this servlet class to a URL pattern in your web.xml file:
<servlet>
<servlet-name>DataServlet</servlet-name>
<servlet-class>DataServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>DataServlet</servlet-name>
<url-pattern>/data</url-pattern>
</servlet-mapping>
- Create a JSP file that will send an HTTP GET request to the servlet and display the data on the web page:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Display Data</title>
</head>
<body>
<h1>Data from PostgreSQL Database</h1>
<div id="data"></div>
<script>
// Send an HTTP GET request to the servlet to fetch the data
var xhr = new XMLHttpRequest();
xhr.open('GET', '/your-web-app-name/data');
xhr.onload = function() {
if (xhr.status === 200) {
// Output the data to the web page
document.querySelector('#data').innerHTML = xhr.responseText;
}
};
xhr.send();
</script>
</body>
</html>
When you access this JSP page in your web browser, it will send an HTTP GET request to the servlet, which will connect to your PostgreSQL database, execute an SQL query, and output the data to the web page. The JSP page will then display this data on the web page using JavaScript.