
Login and Logout Using JSP, Servlet and MySQL
To Login and Logout Using JSP, Servlet and MySQL, you can follow the steps below:
- Create a MySQL database to store user information. The database should have a table named “users” with columns for username and password.
- Create a JSP page named “login.jsp” that includes a login form. The login form should include fields for username and password.
- When the user submits the login form, the data should be sent to a Servlet named “LoginServlet”. In the Servlet, you can retrieve the username and password from the request parameters and check if they match the values stored in the “users” table in the database. If the username and password match, you can store the username in a session attribute and redirect the user to a protected page. Otherwise, you can display an error message and ask the user to try again.
- Create a JSP page named “welcome.jsp” that will be displayed when the user successfully logs in. In this page, you can retrieve the username from the session attribute and display a welcome message.
- Create a logout Servlet named “LogoutServlet”. In this Servlet, you can invalidate the session and redirect the user to the login page.
Below is the sample code for the LoginServlet:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class LoginServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String username = request.getParameter(“username”);
String password = request.getParameter(“password”);
String dbUsername = “”;
String dbPassword = “”;
try {
// connect to MySQL database
Class.forName(“com.mysql.jdbc.Driver”);
Connection con = DriverManager.getConnection(“jdbc:mysql://localhost:3306/mydatabase”, “root”, “”);
// retrieve username and password from the database
PreparedStatement ps = con.prepareStatement(“select * from users where username=? and password=?”);
ps.setString(1, username);
ps.setString(2, password);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
dbUsername = rs.getString(“username”);
dbPassword = rs.getString(“password”);
}
// close the database connection
rs.close();
ps.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
// check if the username and password match
if (username.equals(dbUsername) && password.equals(dbPassword)) {
HttpSession session = request.getSession();
session.setAttribute(“username”, username);
response.sendRedirect(“welcome.jsp”);
} else {
PrintWriter out = response.getWriter();
out.println(“Invalid username or password. Please try again.”);
RequestDispatcher rd = request.getRequestDispatcher(“login.jsp”);
rd.include(request, response);
}
}
}
And here is the sample code for the LogoutServlet:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class LogoutServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession();
session.invalidate();
response.sendRedirect(“login.jsp”);
}
}
Note that you will need to add the necessary mappings for the Servlets in the web.xml file of your web application.
Login and Logout Using JSP, Servlet and MySQL more ways
- Using a Filter: Instead of checking if the user is logged in on every JSP page, you can use a filter to intercept all requests to protected pages and check if the user is logged in. If the user is not logged in, you can redirect them to the login page. Here is a sample code for the filter:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class AuthenticationFilter implements Filter {
public void init(FilterConfig config) throws ServletException {}
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
HttpSession session = request.getSession(false);
String loginURI = request.getContextPath() + “/login.jsp”;
boolean loggedIn = session != null && session.getAttribute(“username”) != null;
boolean loginRequest = request.getRequestURI().equals(loginURI);
if (loggedIn || loginRequest) {
chain.doFilter(request, response);
} else {
response.sendRedirect(loginURI);
}
}
public void destroy() {}
}
To use this filter, you need to add the following code to the web.xml file:
<filter-name>AuthenticationFilter</filter-name>
<filter-class>AuthenticationFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>AuthenticationFilter</filter-name>
<url-pattern>/protected/*</url-pattern>
</filter-mapping>
This code specifies that the filter should be applied to all requests that start with “/protected/”.
- Using JSTL: JSTL (JavaServer Pages Standard Tag Library) is a collection of custom tags that can simplify JSP development. You can use JSTL to check if the user is logged in and display different content based on their login status. Here is a sample code:
<%@ taglib uri=”http://java.sun.com/jsp/jstl/core” prefix=”c” %>
<%@ taglib uri=”http://java.sun.com/jsp/jstl/functions” prefix=”fn” %>
<%@ page session=”false” %>
<c:choose>
<c:when test=”${not empty sessionScope.username}”>
<p>Welcome, ${sessionScope.username}!</p>
<a href=”logout”>Logout</a>
</c:when>
<c:otherwise>
<form action=”login” method=”post”>
<label for=”username”>Username:</label>
<input type=”text” id=”username” name=”username”>
<br>
<label for=”password”>Password:</label>
<input type=”password” id=”password” name=”password”>
<br>
<input type=”submit” value=”Login”>
</form>
</c:otherwise>
</c:choose>
This code uses the <c:choose> tag to display different content based on whether the user is logged in or not. The ${not empty sessionScope.username} expression checks if the “username” attribute is present in the session scope.
A Java Bean is a reusable software component that follows a set of conventions, such as having a public default constructor and getter and setter methods for its properties. To use a Java Bean in your application, you can follow these steps:
- Create a Java class that implements the conventions of a Java Bean. For example, you can define a class with private fields and public getter and setter methods:
public class Person {
private String name;
private int age;
public Person() {}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
- Instantiate the Java Bean by calling its default constructor:
- Set the properties of the Java Bean using its setter methods:
person.setAge(30);
- Retrieve the values of the properties using the getter methods:
int age = person.getAge();
By following these steps, you can use a Java Bean in your application to encapsulate data and behavior in a reusable component.
Download Any Jobs Application Form For 500 + |
Download Jobs Application Form For Every Jobs |
Resume Templates Top 20 in MS Word – CV Format |
Disclaimer Confirm everything before applying for a job or giving an advance to a similar officer. We are not responsible for any damage or loss.
Thank you very much for sharing, I learned a lot from your article. Very cool. Thanks. nimabi