The idea behind MVC is to separate business layers, data, and views from one another. So in our case, we will not download data directly at the view level. The controller will forward DAO data to the view. Dao will, however, be blank, we will not download data from the database because we are not here:)

The design of the application is very similar to the examples in the previous chapters, but we get a few new elements. I assume that you have an already working application that we will be expanding now. We will start by creating separate packages for DAO and domain classes. Then we create a normal POJO class as shown below. Objects of this class will represent cars whose data will be displayed. The constructor parameterized in this example is not necessary, it is used for its own convenience. We need to have at least getters in the field because in the view layer we will use the JSTL tags that require it.

I now create such a fake DAO that will return the sample data. We need two methods – one returning a single car, the other returning the whole list:

We will have two views – one displaying a list of cars, the other displaying only Polonaise. ;)So I create two controllers:

A little note for those who already a little bit of Spring MVC know: “Yes, I know I should use AOP and @Autowired here instead of just declaring a dao class object (and it’s still at the method level !!!), but I commit such blasphemy to not complicate life beginners :)

The new element that appears here is model.addAttribute with object passing, or in the second object list controller. We previously only provided a text message. Actually we can give anything here, the difference will only be to access these data at the view level. Remember we need to use JSTL tags in the view, if we pass an object and we want to reference the view level to its fields, then those fields must have getters.

I also added two JSP files for two separate views. Below is a view showing the data of one car:

Note that in front of the object field I give the name that I passed the object to in the Show One class (line 24). Effect:

Below the JSP file code for displaying the list of cars:

The c: forEach construct is not a Spring element. These are standard JSTLs that you could use in a composite application such as Servlets and JSPs. Remember to indicate what prefix c is (in me in line 6). Without this, nothing will appear.


Previous articleArray variables
Next articleThe simplest form