I am trying to create a dummy project of Online Book Ordering System to practice JSP. Am trying to follow MVC in it.
By definition, in MVC any changes in model must not need any changes in View/Controller.
In Model, I created Customer class (having customer attribute and its getter-setters) and CustomerCollection class (which performs CRUD on customer data)
In Controller, I have a Controller servlet which invokes CustomerCollection, accesses Customer data and adds the list of customers as an attribute of request.
In view, I have JSP which accesses the list of custoemers added by controller and displays it in the page as follows:
<table id="customerTable">
<tr id="customerTableHeaderRow">
<th>Id</th>
<th>First name</th>
<th>Last name</th>
<th>Address</th>
<th>Phone number</th>
<th>Gender</th>
</tr>
<%
for(Customer customer: customers)
{
%>
<tr class="customerTableRow">
<td><%= customer.getId() %></td>
<td><%= customer.getFirstName() %></td>
<td><%= customer.getLastName() %></td>
<td><%= customer.getAddress() %></td>
<td><%= customer.getPhoneNumber() %></td>
<td><%= customer.getGender() %></td>
</tr>
<%
}
%>
</table>
However now I believe that when I make any changes to my database, like adding any column to a customers table, I have to modify for loop in view to display the content of that column too which is not good.
So whats wrong here? Am doing it wrong? Or is there any standard way to do the same?
In MVC approach, the JSP file should not contain any line of Java code, you should be using JSTL and the servlet class should not contain any JDBC code, you should use DAO. So basically you are implementing it right, just need to make few changes as below.
By naming convention your CustomerCollection should be CustomerDAO.
Replace Scriptlets with JSTL and EL.
Customes in jsp can be accessed as below.