JSP login page with database Connectivity :-


Login page (login.jsp)



<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
Simple login Example using servlet jsp and mysql(mariadb) database connectivity
<br> Create a test database, student table and insert some user
information in it.
<br>
<br>

<form action="LoginController" method="post">
Enter username :<input type="text" name="username"> <br>
Enter password :<input type="password" name="password"><br>
<input type="submit" value="Login">
</form>

</body>
</html>



Login controller (LoginController.java)

	
package com.candid;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@WebServlet("/LoginController")
public class LoginController extends HttpServlet {

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String un = request.getParameter("username");
String pw = request.getParameter("password");

//Connect to mysql(mariadb) and verify username password

try {
Class.forName("org.mariadb.jdbc.Driver");
// loads driver
Connection c = DriverManager.getConnection("jdbc:mariadb://localhost:3306/test", "root", "root"); // gets a new connection

PreparedStatement ps = c.prepareStatement("select userName,pass from student where userName=? and pass=?");
ps.setString(1, un);
ps.setString(2, pw);

ResultSet rs = ps.executeQuery();

while (rs.next()) {
response.sendRedirect("success.html");
return;
}
response.sendRedirect("error.html");
return;
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
}
	


success page (success.html)

	
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
Login success
</body>
</html>
	


error page (error.html)

	
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
Invalid username or password, Please try again with valid
</body>
</html>
	

Previous Next