The way you're working seems correct. If you're following the MVC model 2,
you should let servlets and JSP's collaborate.
The Model View Controller contains the following elements :
- JSP : takes care of the presentation and nothing else. Hence, this is the View.
- Model : these are the classes that refer to the objects known by the users of you application : Customer, Invoice, Product. So, these are the
Java Beans.
- Controller : the controller takes care of the requests, decides upon the request which response must be given. The controller is the servlet or a series of servlets.
Then there is one more thing you ought to know : the MVC Model 2 should work with DAO's or Data Access Objects. Each Java Bean should have a corresponding DAO (so, if your application has a Customer, there should be a CustomerDAO as well). The DAO's contain the data layer of your application. They contain the SQL statements necessary to extract the records from the database, and translate the resultsets into java beans.
I'll give an example :
The LandDAO has a method zoekLand() (searchCountry()) which returns an ArrayList of country; I'm not giving all the lines of course; it would become unreadable
public ArrayList zoekLand()
throws SQLException
{
ArrayList landLijst = new ArrayList();
StringBuffer zoekString = new StringBuffer();
zoekString.append("select * from land");
try {
con = getConnection();
ps = con.prepareStatement(zoekString.toString());
rs = ps.executeQuery();
while (rs.next())
{
Land land = new Land(rs);
landLijst.add(land);
}
} catch (SQLException SQLEx)
(...)
return landLijst ;
} // end zoekLand
The ArrayList is returned to the servlet which has used the zoekLand() method; the ArrayList is then placed in the session of the request
ArrayList landLijst = landDao.zoekLand();
HttpSession session = request.getSession(false);
session.setAttribute("landLijst", landLijst);
With the requestDispatcher you give the control to the JSP. And how does the JSP get the values of the ArrayLIst ? With these lines of code which you should place at the beginning of the JSP :
<%@ page import = "org.brukkerlin.adres.Land" %>
<%@ page import = "java.util.Iterator" %>
<jsp:useBean id="servletPath" class="java.lang.String" scope="request"/>
<jsp:useBean id="landLijst" class="java.util.ArrayList" scope="session"/>