Show List

MVC Architecture in Servlets

MVC (Model-View-Controller) is an architecture pattern that separates an application into three parts: the model, the view, and the controller. This pattern is often used in web applications to separate business logic (model) from presentation logic (view) and user input handling (controller).

In a Servlet-based MVC architecture, the model represents the business logic and data, the view represents the presentation logic, and the controller handles user input and updates the model and view as needed. Here's an example of how to implement an MVC architecture using Servlets:

  • Model: The model represents the business logic and data of the application. In this example, we'll create a simple User class to represent a user's data:
java
Copy code
public class User { private String username; private String password; public User(String username, String password) { this.username = username; this.password = password; } public String getUsername() { return username; } public String getPassword() { return password; } }
  • View: The view represents the presentation logic of the application. In this example, we'll create a JSP (JavaServer Pages) page to display a login form:
jsp
Copy code
<html> <head> <title>Login</title> </head> <body> <h1>Login</h1> <form action="login" method="post"> Username: <input type="text" name="username"><br> Password: <input type="password" name="password"><br> <input type="submit" value="Login"> </form> </body> </html>
  • Controller: The controller handles user input and updates the model and view as needed. In this example, we'll create a Servlet to handle user login requests:
java
Copy code
@WebServlet("/login") public class LoginServlet extends HttpServlet { private List<User> users = new ArrayList<>(); public LoginServlet() { // Create some test users users.add(new User("admin", "admin")); users.add(new User("user", "password")); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Display the login form request.getRequestDispatcher("login.jsp").forward(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String username = request.getParameter("username"); String password = request.getParameter("password"); // Find the user with the specified username and password User user = null; for (User u : users) { if (u.getUsername().equals(username) && u.getPassword().equals(password)) { user = u; break; } } if (user != null) { // If the user is found, set a session attribute and redirect to the home page HttpSession session = request.getSession(); session.setAttribute("user", user); response.sendRedirect("home.jsp"); } else { // If the user is not found, display an error message request.setAttribute("error", "Invalid username or password"); request.getRequestDispatcher("login.jsp").forward(request, response); } } }

In this example, the LoginServlet class acts as the controller. When the user submits the login form, the doPost() method is called. The method retrieves the username and password parameters from the request, finds the corresponding user in the model (the users list in this case), and sets a session attribute with the user data. If the user is not found, an error message is displayed.

The doGet() method is used to display the login form when the user visits the login page. It simply forwards the request to the JSP file that contains the login form.

  • Home page: Finally, we'll create a JSP file to display the home page once the user has successfully logged in:
jsp
Copy code
<html> <head> <title>Home</title> </head> <body> <h1>Welcome, <%= user.getUsername() %>!</h1> <a href="logout">Logout</a> </body> </html>

In this JSP file, we use the user session attribute to display a welcome message to the user and a logout link. When the user clicks the logout link, we'll use another Servlet to invalidate the session and redirect the user to the login page:

java
Copy code
@WebServlet("/logout") public class LogoutServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(false); if (session != null) { session.invalidate(); } response.sendRedirect("login"); } }

In this example, the LogoutServlet class acts as a simple controller to handle the logout request. When the user clicks the logout link, the doGet() method is called. The method invalidates the user's session (if one exists) and redirects the user back to the login page.

By using an MVC architecture, we've separated the business logic, presentation logic, and user input handling of our application. This makes our code more modular and easier to maintain and update.


    Leave a Comment


  • captcha text