<html>
<head><title>Login</title></head>
<body>
<h2>Login Page</h2>
<form action="JdbcLogin" method="post">
Username: <input type="text" name="username" /><br/>
Password: <input type="password" name="password" /><br/>
<input type="submit" value="Login" />
</form>
<%
String error = (String)[Link]("error");
if (error != null) {
%>
<p style="color:red;"><%= error %></p>
<% } %>
</body>
</html>
login page for the test page
package test;
import [Link].*;
public class DBConnection {
public static Connection getConnection() throws Exception {
String url = "jdbc:postgresql://localhost:5432/demo";
String user = "postgres";
String pass = "123";
[Link]("[Link]");
return [Link](url, user, pass);
}
}
DataBase connection
package test;
import [Link];
import [Link].*;
import [Link];
@WebServlet("/jdbchome")
public class HomeServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws
IOException {
HttpSession session = [Link](false);
if (session != null && [Link]("username") != null) {
[Link]("text/html");
[Link]().println("<h2>Welcome, " +
[Link]("username") + "</h2>");
[Link]().println("<a href='Jdbclogout'>Logout</a>");
} else {
[Link]("[Link]");
}
}
}
home page
package test;
import [Link].*;
import [Link];
import [Link].*;
import [Link];
import [Link].*;
@WebServlet("/JdbcLogin")
public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws
IOException, ServletException {
String username = [Link]("username").trim();
String password = [Link]("password").trim();
[Link]("Login attempt for: " + username);
try (Connection conn = [Link]()) {
PreparedStatement ps = [Link]("SELECT * FROM userlogin
WHERE userid=? AND password=?");
[Link](1, username);
[Link](2, password);
[Link]("Executing: " + [Link]());
ResultSet rs = [Link]();
if ([Link]()) {
[Link]("Login successful for: " + username);
HttpSession session = [Link]();
[Link]("username", username);
[Link]("jdbchome");
} else {
[Link]("Login failed for: " + username);
[Link]("error", "Invalid username or password");
RequestDispatcher rd = [Link]("[Link]");
[Link](req, res);
}
} catch (Exception e) {
[Link]();
[Link]("error", "Database error. Please try again.");
RequestDispatcher rd = [Link]("[Link]");
[Link](req, res);
}
}
}
[Link] page
package test;
import [Link];
import [Link].*;
import [Link];
@WebServlet("/Jdbclogout")
public class LogoutServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws
IOException {
HttpSession session = [Link](false);
if (session != null) {
[Link]();
}
[Link]("[Link]");
}
}
logout page