Tuesday, September 27, 2011

Scaffolding a Spring Web MVC application

We saw in earlier two posts that using project command you can create a Java project, and by using persistence setup command you can setup a persistence provider (Hibernate, OpenJPA, and so on).

It's important to note the following when using Spring Roo:
- You don't need to remember commands because Roo is a very user-friendly development tool. You can look at all the Roo commands and their brief description using help command.
- Also, Roo offers auto-completion features - which means you partially type a command or an argument name, and Roo auto-completes it for you.

You can scaffold a Spring Web MVC application from JPA entities using controller all command.

Step 1: Download ch04_web-app.roo script from the Google Code project for Spring Roo 1.1 Cookbook (http://code.google.com/p/spring-roo-cookbook/downloads/list).  Execute ch04_web-app.roo script using script command of Spring Roo. A Roo script contains a sequence of commands which are executed when you execute script command, as shown here:

roo> script --file ch04_web-app.roo

Executing ch04_web-app.roo script creates flight-app Roo project, sets up Hibernate as persistence provider, configures MySQL as the database for the application, creates Flight and FlightDescription JPA entities and defines many-to-one relationship between Flight and FlightDescription entities. If you are using a different database than MySQL or your connection settings are different than what is specified in the script, then modify the script accordingly.


Step 2: Execute controller all command:

.. roo> controller all --package ~.web

The controller all command creates JSPX views, controllers, copies custom tags, default themes, and so on. The package argument specifies the location where the Spring Web MVC controllers are created by Roo.

Step 3. You can now convert the project into an Eclipse IDE project using perform eclipse command. The perform eclipse command generates .project and .classpath files required by Eclipse IDE.

Step 4. You can also run the flight-app application in embedded Tomcat container by exiting the Roo shell (by executing quit command) and executing mvn tomcat:run goal from the command prompt. Now, you access the web application by going to the following URL: http://localhost:8080/flight-app

The following figure shows how the scaffolded web application looks like:


By default, the scaffolded web application allows you to perform CRUD operations on JPA entities, and to search entities based on the dynamic finder methods that you added to them.

No comments:

Post a Comment