Model objects in MVC using JSP and Servlet.
In the previous tutorial, we have seen an Example of the Login Application which was an MVC pattern implementation. In that example, we will explain Model Objects in MVC and Request Dispatcher. The user enters a username and password which is then passed to the servlet. The servlet then gives the username and password to our business logic class which then return true or false telling us the user is authenticated, or not. The authenticated user will be redirected to the successful login page, and the non-authenticated user will remain on the same login page.
In this tutorial, we will display a username on the success.jsp page
MVC Example Continued:
We are using here our MVC previous tutorial example to continue with it; you can download its source from here, or you can also start from the previous Simple MVC Login Application tutorial.
To display the user on success.jsp page, we should have to store it somewhere in the database or some form of data structure, in this example, we will create a Hashmap to store key value attributes of the user we will do this in our LoginService.java class because it is our business logic class. We will also create a class named “user.java” to store a user detail in the form of objects; technically it will be the data transfer object for us which will provide us a mechanism to move data in the form of an object from one resource to another (resource => .jsp or .java files).
The flow of control is shown in the figure below.

Explanation of MVC example
The user will enter the details (id and pass)in Login.jsp which will be given to LoginServlet.java class which is the controller in our case; this will pass the user id and pass to the LoginService.Java class, which can be accessed locally in the authenticate method of this class. Authentication result will be boolean on the basis of which LoginServlet (controller) will decide which page to show login.jsp or success.jsp if it will be the success.jsp then LoginServlet (controller) collect the user details in one data transfer object using the user.java, the controller will also store this object in the session object to access it in the success.jsp page. For more details, you can also read comments in the below given source.
Login.jsp:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | <%@ 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> <form action="LoginServlet" method="post"> <% /* Here action="LoginServlet" and method="post" is used to redirect this JSP on the doPost method of LoginServlet.java on the click of button submit" */ %> UserId:<input type="text" name="userId"/> <br> Password:<input type="password" name="pass"/> <br> <input type="submit"/> </form> </body> </html> |
LoginServlet.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 | package org.uzair.beginnersheep; 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; /** * Servlet implementation class LoginServlet */ @WebServlet("/LoginServlet") public class LoginServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String userId,password; userId = request.getParameter("userID"); password = request.getParameter("pass"); LoginService loginService = new LoginService(); boolean result = loginService.authenticate(userId, password); /*loginService.authenticate() method call will give the control to the boolean authenticate() function of LoginService.java class*/ //redirect code block if(result){ user objectUser = new user(); objectUser = loginService.getUserDetails(userId); /* * here we have all the user details in form of user object * now we have to pass these details to the success,jsp * we can do this by putting our object in scope * we will use session cope * because we have to access these details in another JSP page for the same use * we can also use application scope if we have to deal with multiple users * * */ request.getSession().setAttribute("user",objectUser); response.sendRedirect("success.jsp"); return; }else{ response.sendRedirect("login.jsp"); return; } } } |
LoginService.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | package org.uzair.beginnersheep; import java.util.HashMap; public class LoginService { HashMap<String, String> user = new HashMap<String, String>(); public LoginService (){ //constructor implementation user.put("1", "Suraish"); user.put("2", "Sara"); user.put("3", "Sumaira"); } public boolean authenticate(String Id,String pass){ /* * here we are only checking that user has entered some password or not * on the bases of it we are returning true or false * *you can also use your database code here to authenticate the user from database * * */ if((pass==null)||pass.trim()==""){ return false; } return true; } public user getUserDetails(String userId){ user objUser= new user(); objUser.setUserName(user.get(userId)); objUser.setUserId(userId); return objUser; } } |
user.java
Our model in this example which is called the data transfer object, because it transfers the data to the controller, view, and business logic layers.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | package org.uzair.beginnersheep; // this is a java been public class user { private String userName; private String userId; public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } } |
success.jsp displaying user using the session object
Finally success.jsp page which will display the username in it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1" import ="org.uzair.beginnersheep.user"%> <!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>Success</title> </head> <body> <h3>Login Successful!</h3> <% /* here we will get the userObject from the LoginServlet.java doPast method */ user newUserObject = (user) session.getAttribute("user"); %> Hello <%=newUserObject.getUserName()%>! </body> </html> |
Request Dispatcher in the MVC
to understand request dispatcher with MVC just edit two files LoginServlet.java and success.jsp
as follow. For more details, you can also read comments in the below-given source.
Download the full source to understand the directory structure of this example.
LoginServlet.java with RequestDispatcher object
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 | package org.uzair.beginnersheep; import java.io.IOException; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class LoginServlet */ @WebServlet("/LoginServlet") public class LoginServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String userId,password; userId = request.getParameter("userID"); password = request.getParameter("pass"); LoginService loginService = new LoginService(); boolean result = loginService.authenticate(userId, password); /*loginService.authenticate() method call will give the control to the boolean authenticate() function of LoginService.java class*/ //redirect code block if(result){ user objectUser = new user(); objectUser = loginService.getUserDetails(userId); /* * here we have all the user details in form of user object * now we have to pass these details to the success,jsp * we can do this by putting our object in scope * we will use session cope * because we have to access these details in another JSP page for the same use * we can also use application scope if we have to deal with multiple users * * */ /* * request.getSession().setAttribute("user",objectUser); * response.sendRedirect("success.jsp"); * * we can do the re direct without telling the browser * by using the request dispatcher object * * */ request.setAttribute("user", objectUser); RequestDispatcher dispatcher = request.getRequestDispatcher("success.jsp"); dispatcher.forward(request, response); return; }else{ response.sendRedirect("login.jsp"); return; } } } |
success.jsp displaying user using the request object
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1" import ="org.uzair.beginnersheep.user"%> <!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>Success</title> </head> <body> <h3>Login Successful!</h3> <% /* here we will get the userObject from the LoginServlet.java doPast method */ /* user newUserObject = (user) session.getAttribute("user"); */ user newUserObject = (user) request.getAttribute("user"); %> Hello <%=newUserObject.getUserName()%>! </body> </html> |
Now you can download and run the source easily.
Download the full source to understand the directory structure of this example.
Summary:
In this tutorial, we have seen the user object as our Model in MVC which is acting as DTO data transfer object. We have also learned request dispatcher object. There is more to learn in upcoming tutorials.