Retrieving and Displaying User Data
After establishing a connection to the database, the next step is to retrieve the user data and display it in the servlet's response.
Retrieving User Data
To retrieve user data from the database, you can use the java.sql.ResultSet
interface, which represents the result of a SQL query. Here's an example of how to retrieve user data and store it in a Java object:
public class User {
private int id;
private String username;
private String email;
// Getters and setters
}
try (Connection connection = dataSource.getConnection();
PreparedStatement statement = connection.prepareStatement("SELECT * FROM users WHERE id = ?")) {
statement.setInt(1, userId);
ResultSet resultSet = statement.executeQuery();
if (resultSet.next()) {
User user = new User();
user.setId(resultSet.getInt("id"));
user.setUsername(resultSet.getString("username"));
user.setEmail(resultSet.getString("email"));
// Process the user data
}
} catch (SQLException e) {
// Handle the exception
}
In this example, we're creating a User
class to represent the user data retrieved from the database. We then use a PreparedStatement
to execute a SQL query and retrieve the user data, which is then stored in a User
object.
Displaying User Data
Once you have the user data, you can display it in the servlet's response. You can use the javax.servlet.http.HttpServletResponse
interface to generate the response, which can be in the form of HTML, JSON, or any other desired format.
Here's an example of how to display the user data in an HTML response:
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><body>");
out.println("<h1>User Data</h1>");
out.println("<p>Username: " + user.getUsername() + "</p>");
out.println("<p>Email: " + user.getEmail() + "</p>");
out.println("</body></html>");
}
In this example, we're using the HttpServletResponse
object to generate an HTML response that displays the user's username and email.
By combining the database retrieval and response generation, you can effectively retrieve and display user data in your Java Servlet application.