My application has the following patterns: a FrontController, Command, Service, and DAO.
The problem im having is that I want to display a list of users (and their avatars) on my homepage. How do I get my jsp page to automatically call the ListMembersCommand upon page load without a get/post request?
You don’t. What you do is you call the controller and have if forward to the JSP. You never call the JSPs directly themselves.
So, what you end up with is:
The Controller can fetch whatever is necessary and populate the request appropriately before called the JSP to render it all.
Addenda –
Here is a simple Servlet, mapped to /MyServlet :
And here is an associated JSP placed at /WEB-INF/jsp/members.jsp:
In your browser, you hit: http://yourhost/yourapp/MyServlet
The servlet, acting as a controller, takes the request, acts on it (in this case getting a list of all of the members from the database using a simple DAO pattern), and then puts the results in to the request with the tag “members” (the
request.setAttribute("members", members)does this).One the request is properly populated with interesting information, the servlet forward to the JSP.
Note in this case the JSP is located below the WEB-INF directory. JSPs located within WEB-INF are NOT accessible at all from the browser. So a request to http://yourhost/yourapp/WEB-INF/jsp/members.jsp will simply fail.
But they are accessible internally.
So, the Servlet forwards to members.jsp, and members.jsp renders, locating the
membersvalue from the request (${members} in the JSTL c:forEach tag), and the c:forEach iterates across that list, populating themembervariable, and from there filling out the rows in the table.This is a classic “controller first” pattern which keeps the JSP out of the way. It also helps maintain that the JSPs only live in the View layer of MVC. In this simple example, Member and the List is the model, the Servlet in the Controller, and the JSP is the view.