📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.
✅ Some premium posts are free to read — no account needed. Follow me on Medium to stay updated and support my writing.
🎓 Top 10 Udemy Courses (Huge Discount): Explore My Udemy Courses — Learn through real-time, project-based development.
▶️ Subscribe to My YouTube Channel (172K+ subscribers): Java Guides on YouTube
Learn complete Servlet at https://www.javaguides.net/p/servlet-tutorial.html
What we will build?
Tools and technologies used
- IDE - STS/Eclipse Neon.3
- JDK - 1.8 or later
- Apache Tomcat - 8.5
- Servlet - 2.5+
- MySQL - mysql-connector-java-8.0.13.jar
Development Steps
- Create Eclipse Dynamic web project
- Add Dependencies
- Project Structure
- MySQL Database Setup
- Create a JavaBean - Login.java
- Create a LoginDao.java
- Create LoginServlet.java
- Create a login.html
- Create a loginsuccess.html
- Demo
1. Create an Eclipse Dynamic Web Project
5. Make sure that the target runtime is set to Apache Tomcat with the currently supported version.
2. Add Dependencies
- servlet-api.2.3.jar
- mysql-connector-java-8.0.13.jar
3. Project Structure
4. MySQL Database Setup
CREATE TABLE `login` (
`username` varchar(45) NOT NULL,
`password` varchar(45) DEFAULT NULL,
PRIMARY KEY (`username`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
INSERT INTO `demo`.`login` (`username`, `password`) VALUES ("Ramesh", "Ramesh");
5. Create a JavaBean - LoginBean.java
import java.io.Serializable;
public class LoginBean implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1 L;
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
6. Create a LoginDao.java
package net.javaguides.login.database;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import net.javaguides.login.bean.LoginBean;
public class LoginDao {
public boolean validate(LoginBean loginBean) throws ClassNotFoundException {
boolean status = false;
Class.forName("com.mysql.jdbc.Driver");
try (Connection connection = DriverManager
.getConnection("jdbc:mysql://localhost:3306/demo?useSSL=false", "root", "root");
// Step 2:Create a statement using connection object
PreparedStatement preparedStatement = connection
.prepareStatement("select * from login where username = ? and password = ? ")) {
preparedStatement.setString(1, loginBean.getUsername());
preparedStatement.setString(2, loginBean.getPassword());
System.out.println(preparedStatement);
ResultSet rs = preparedStatement.executeQuery();
status = rs.next();
} catch (SQLException e) {
// process sql exception
printSQLException(e);
}
return status;
}
private void printSQLException(SQLException ex) {
for (Throwable e: ex) {
if (e instanceof SQLException) {
e.printStackTrace(System.err);
System.err.println("SQLState: " + ((SQLException) e).getSQLState());
System.err.println("Error Code: " + ((SQLException) e).getErrorCode());
System.err.println("Message: " + e.getMessage());
Throwable t = ex.getCause();
while (t != null) {
System.out.println("Cause: " + t);
t = t.getCause();
}
}
}
}
}
7. Create a LoginServlet.java
Let's create LoginServlet to process HTTP request parameters and redirect to the appropriate HTML page based on the employee login status.
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import net.javaguides.login.bean.LoginBean;
import net.javaguides.login.database.LoginDao;
/**
* @email Ramesh Fadatare
*/
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1 L;
private LoginDao loginDao;
public void init() {
loginDao = new LoginDao();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
LoginBean loginBean = new LoginBean();
loginBean.setUsername(username);
loginBean.setPassword(password);
try {
if (loginDao.validate(loginBean)) {
response.sendRedirect("loginsuccess.html");
} else {
HttpSession session = request.getSession();
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import net.javaguides.login.bean.LoginBean; import net.javaguides.login.database.LoginDao; /** * @email Ramesh Fadatare */ @WebServlet("/login") public class LoginServlet extends HttpServlet { private static final long serialVersionUID = 1 L; private LoginDao loginDao; public void init() { loginDao = new LoginDao(); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String username = request.getParameter("username"); String password = request.getParameter("password"); LoginBean loginBean = new LoginBean(); loginBean.setUsername(username); loginBean.setPassword(password); try { if (loginDao.validate(loginBean)) { response.sendRedirect("loginsuccess.html"); } else { HttpSession session = request.getSession(); } } catch (ClassNotFoundException e) { e.printStackTrace(); } } }
8. Create a login.html
- username
- password
<!DOCTYPE html> <html> <head> <meta charset="ISO-8859-1"> <title>Insert title here</title> </head> <body> <div align="center"> <h1>Employee Login Form</h1> <form action="login" method="post"> <table style="with: 100%"> <tr> <td>UserName</td> <td><input type="text" name="username" /></td> </tr> <tr> <td>Password</td> <td><input type="password" name="password" /></td> </tr> </table> <input type="submit" value="Submit" /> </form> </div> </body> </html>
9. Create a loginsuccess.html
<!DOCTYPE html> <html> <head> <meta charset="ISO-8859-1"> <title>Insert title here</title> </head> <body> <div align="center"> <h1>You have logined successfully</h1> </div> </body> </html>
Comments
Post a Comment
Leave Comment