CarDealer #9 – Spring MVC + JDBC Template + PostgreSQL (controller, view, xml)

Dziś przedstawię dalszą część mojej konfiguracji Spring MVC i JDBC Template dla projektu CarDealer. Struktura projektu i POM, a także model danych, DAO i serwis zostały omówione w poprzednim poście.

***

Today I am going to show you the rest of my Spring MVC and JDBC Template configuration for the CarDealer project.  In the previous post I have shown project’s structure and POM, as well as data model, DAO and service.

For English please scroll down

HomeController.java

package com.cardealer.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class HomeController {
 
  @RequestMapping(value ="/")
  public ModelAndView mainPage(){
     return new ModelAndView("home");
  }
}

Kontroler dla strony głównej wyświetla nam widok strony zawarty w pliku home (.jsp).

home.jsp (fragment)

</head>
<body>
<h1>Welcome to CarDealer!</h1>
<p>
${message}<br/>
<a href="${pageContext.request.contextPath}/listCars">Start application</a><br/>
</p>
</body>

Widok dla strony głównej. Dopasowałam na potrzeby projektu przykłady htmla znalezione w sieci. Tutaj przy kliknięciu w napis “Start application” nastąpi  po prostu przekierowanie do podstrony “/listCars”.

CarController.java

package com.cardealer.controller;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.cardealer.model.Car;
import com.cardealer.service.CarService;

@Controller
public class CarController {

 @Autowired
 CarService carService;

 @RequestMapping("/listCars")    
 public ModelAndView listCars() {
    List carList = carService.listCars();
    return new ModelAndView("carList", "carList", carList);
//ModelAndView(String viewName, String modelName, Object modelObject)
 }
}

Dla podstrony z tabelą aut (“/listCars”)  wywołuję metodę CarService – listCars, której wyniki wyświetlam w sposób określony w moim widoku zawartym w pliku carList(.jsp).

carList.jsp (fragment)

 <br /> <br /> <br /> <b>Car List</b><br /> <br />
 <table border="1">
 <tr>
 <td class="heading">Id</td>
 <td class="heading">Make</td>
 <td class="heading">Model</td>
 <td class="heading">Year</td>
 <td class="heading">Fuel</td>
 <td class="heading">Engine</td>
 <td class="heading">Gearbox</td>
 <td class="heading">Color</td>
 <td class="heading">Kilometer</td>
 </tr>
 <c:forEach var="carList" items="${carList}">
 <tr>
 <td>${carList.id}</td>
 <td>${carList.make}</td>
 <td>${carList.model}</td>
 <td>${carList.year}</td>
 <td>${carList.fuel}</td>
 <td>${carList.engine}</td>
 <td>${carList.gearbox}</td>
 <td>${carList.color}</td>
 <td>${carList.kilometer}</td>
 <td><a href="edit?id=${carList.id}">Edit</a></td>
 <td><a href="delete?id=${carList.id}">Delete</a></td>
 </tr>
 </c:forEach>

Fragment kodu dla widoku strony z tabelą aut. Etykiety poszczególnych pól:

 <td class="heading">Make</td>

A potem pobieranie ich wartości:

 <td>${carList.make}</td>

Aby aplikacja wystartowała niezbędne było też kilka plików konfiguracyjnych:

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
 <context-param>
 <param-name>contextConfigLocation</param-name>
 <param-value>/WEB-INF/spring/root-context.xml</param-value>
 </context-param>
 <listener>
 <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
 </listener>
 <servlet>
 <servlet-name>carServlet</servlet-name>
 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
 <init-param>
 <param-name>contextConfigLocation</param-name>
 <param-value>/WEB-INF/spring/servlet-context.xml</param-value>
 </init-param>
 <load-on-startup>1</load-on-startup>
 </servlet>
 <servlet-mapping>
 <servlet-name>carServlet</servlet-name>
 <url-pattern>/</url-pattern>
 </servlet-mapping>
</web-app>

Co dopasowałam w web.xml?

  • contextConfigLocation – podałam lokalizacje plików root-context i servlet-context
  • servlet-name

root-context.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="
 http://www.springframework.org/schema/beans 
 http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">
</beans>

servlet-context.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
 xmlns:context="http://www.springframework.org/schema/context"
 xsi:schemaLocation="http://www.springframework.org/schema/beans 
 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
 http://www.springframework.org/schema/context 
 http://www.springframework.org/schema/context/spring-context-3.0.xsd">

<!-- telling container to take care of annotations stuff -->
 <context:annotation-config />

<!-- declaring base package -->
 <context:component-scan base-package="com.cardealer" />

<!-- adding view resolver to show jsp's on browser -->
 <bean id="viewResolver"
 class="org.springframework.web.servlet.view.InternalResourceViewResolver">
 <property name="prefix" value="/WEB-INF/views/" />
 <property name="suffix" value=".jsp" />
 </bean>

<!-- declare beans -->
 <bean id="carDaoSpring" class="com.cardealer.spring.dao.CarDAOSpringImpl" />
 <bean id="carService" class="com.cardealer.service.CarServiceImpl" />

<!-- declare datasource bean -->
 <bean id="dataSource"
 class="org.springframework.jdbc.datasource.DriverManagerDataSource">
 <property name="driverClassName" value="org.postgresql.Driver" />
 <property name="url" value="jdbc:postgresql://localhost:5432/cardealer" />
 <property name="username" value="postgres" />
 <property name="password" value="password" />
 </bean>
</beans>

Co dopasowałam w pliku servlet-context.xml?

  • base-package=”com.cardealer”
  • bean-id = “viewResolver”  – katalog z widokami: tutaj pliki jsp w WEB-INF/views
  • bean-id = “carDAOSpring” – klasa z implementacją DAO
  • bean-id = “carService” –  klasa z implementacją sewisu
  • bean-id = “dataSource” – konfiguracja bazy danych: driver, url, użytkownik i hasło

Co dalej?

Jest to oczywiście początek moich zmagań ze Spring MVC. Na razie dostępna jest tylko jedna metoda – wyświetlająca dane z bazy danych w widoku na stronie. Teraz będę pracować nad udostępnieniem kolejnych funkcji z poziomu przeglądarki. Na początku będzie to zapis do bazy danych, czyli dodanie i usuwanie auta.

 

***

HomeController.java

package com.cardealer.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class HomeController {
 
  @RequestMapping(value ="/")
  public ModelAndView mainPage(){
     return new ModelAndView("home");
  }
}

The home page controller directs us to page view specified in home (.jsp) file.

home.jsp (snippet)

</head>
<body>
<h1>Welcome to CarDealer!</h1>
<p>
${message}<br/>
<a href="${pageContext.request.contextPath}/listCars">Start application</a><br/>
</p>
</body>

The view for my main page. I have adjusted example htmls found online to my project’s needs. Here, when you click on “Start application” you will be redirected to “/listCars” page.

CarController.java

package com.cardealer.controller;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.cardealer.model.Car;
import com.cardealer.service.CarService;

@Controller
public class CarController {

 @Autowired
 CarService carService;

 @RequestMapping("/listCars")    
 public ModelAndView listCars() {
    List carList = carService.listCars();
    return new ModelAndView("carList", "carList", carList);
//ModelAndView(String viewName, String modelName, Object modelObject)
 }
}

For page with car list (“/listCars”) I call CarService’s listCars method, that results are shown on the page in a way specified in my view in carList(.jsp) file.

carList.jsp (snippet)

 <br /> <br /> <br /> <b>Car List</b><br /> <br />
 <table border="1">
 <tr>
 <td class="heading">Id</td>
 <td class="heading">Make</td>
 <td class="heading">Model</td>
 <td class="heading">Year</td>
 <td class="heading">Fuel</td>
 <td class="heading">Engine</td>
 <td class="heading">Gearbox</td>
 <td class="heading">Color</td>
 <td class="heading">Kilometer</td>
 </tr>
 <c:forEach var="carList" items="${carList}">
 <tr>
 <td>${carList.id}</td>
 <td>${carList.make}</td>
 <td>${carList.model}</td>
 <td>${carList.year}</td>
 <td>${carList.fuel}</td>
 <td>${carList.engine}</td>
 <td>${carList.gearbox}</td>
 <td>${carList.color}</td>
 <td>${carList.kilometer}</td>
 <td><a href="edit?id=${carList.id}">Edit</a></td>
 <td><a href="delete?id=${carList.id}">Delete</a></td>
 </tr>
 </c:forEach>

Code snippet for view for the page that displays list of cars. Defining labels for fields:

 <td class="heading">Make</td>

And getting its values:

 <td>${carList.make}</td>

In order to run the application, a few configuration files were also required.

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
 <context-param>
 <param-name>contextConfigLocation</param-name>
 <param-value>/WEB-INF/spring/root-context.xml</param-value>
 </context-param>
 <listener>
 <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
 </listener>
 <servlet>
 <servlet-name>carServlet</servlet-name>
 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
 <init-param>
 <param-name>contextConfigLocation</param-name>
 <param-value>/WEB-INF/spring/servlet-context.xml</param-value>
 </init-param>
 <load-on-startup>1</load-on-startup>
 </servlet>
 <servlet-mapping>
 <servlet-name>carServlet</servlet-name>
 <url-pattern>/</url-pattern>
 </servlet-mapping>
</web-app>

What have I adjusted in web.xml?

  • contextConfigLocation – I provided the location for root-context and servlet-context
  • servlet-name

root-context.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="
 http://www.springframework.org/schema/beans 
 http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">
</beans>

servlet-context.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
 xmlns:context="http://www.springframework.org/schema/context"
 xsi:schemaLocation="http://www.springframework.org/schema/beans 
 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
 http://www.springframework.org/schema/context 
 http://www.springframework.org/schema/context/spring-context-3.0.xsd">

<!-- telling container to take care of annotations stuff -->
 <context:annotation-config />

<!-- declaring base package -->
 <context:component-scan base-package="com.cardealer" />

<!-- adding view resolver to show jsp's on browser -->
 <bean id="viewResolver"
 class="org.springframework.web.servlet.view.InternalResourceViewResolver">
 <property name="prefix" value="/WEB-INF/views/" />
 <property name="suffix" value=".jsp" />
 </bean>

<!-- declare beans -->
 <bean id="carDaoSpring" class="com.cardealer.spring.dao.CarDAOSpringImpl" />
 <bean id="carService" class="com.cardealer.service.CarServiceImpl" />

<!-- declare datasource bean -->
 <bean id="dataSource"
 class="org.springframework.jdbc.datasource.DriverManagerDataSource">
 <property name="driverClassName" value="org.postgresql.Driver" />
 <property name="url" value="jdbc:postgresql://localhost:5432/cardealer" />
 <property name="username" value="postgres" />
 <property name="password" value="password" />
 </bean>
</beans>

What have I adjusted in servlet-context.xml?

  • base-package=”com.cardealer”
  • bean-id = “viewResolver”  – catalogue with views: here jsp files in WEB-INF/views
  • bean-id = “carDAOSpring” – DAO implementation class
  • bean-id = “carService” –  service implementation class
  • bean-id = “dataSource” – data base configuration: data base data: driver, url, user and password

What’s next?

That’s just a start of my struggles with Spring MVC. Currently only one method is available – displaying data from DB on the site. Now I am going to work on making next functions available from browser level. First, inserting and deleting car to/from the database.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s