Wednesday, March 25, 2009

Netbeans Spring Tutorials

Introduction to the Spring Framework

This document shows you how to construct a simple web MVC application using the Spring Framework. The application enables a user to enter her name in a text field, and upon clicking OK, the name is returned and displayed on a second page with a welcome greeting.

The Spring Framework is a popular open source application framework that can make J2EE development easier. It consists of a container, a framework for managing components, and a set of snap-in services for web user interfaces, transactions, and persistence. A part of the Spring Framework is Spring Web MVC, an extensible MVC framework for creating web applications.

The IDE provides built-in support for Spring Framework 2.5. Framework libraries are packaged with the IDE and are automatically added to the project classpath when the framework is selected. Configuration settings are provided, such as naming and mapping of the Spring Web MVC DispatcherServlet. The JSTL library is automatically registered. Support for Spring XML bean configuration files is also provided, including the following functionality:

  • Code completion. Invoked in Spring XML configuration files for Java classes as well as bean references.
  • Navigation. Hyperlinking of Java classes and properties mentioned in Spring bean definitions, as well as hyperlinking to other Spring bean references.
  • Refactoring. Renaming of references to Java classes in Spring XML configuration files.

For more information on the Spring Framework, visit http://www.springframework.org. For a more fine-grained explanation of how Spring Framework artifacts behave and interact with other objects in an application, visit the official Spring Framework Reference Documentation, or consult the Spring Framework API.

Contents

Content on this page applies to NetBeans IDE 6.1 and 6.5

To complete this tutorial, you need the following software and resources.

Software or Resource Version Required
NetBeans IDE version 6.1 or 6.5 Java
Java Development Kit (JDK) version 5 or 6
GlassFish application server
or
Tomcat servlet container
V2 or V3

version 6.x

Notes:

  • The Web and Java EE installation enables you to optionally install the GlassFish (V2 or V3) application server and the Apache Tomcat servlet container 6.0.18. You must install one of these (or register a different server in the IDE) to work through this tutorial.
  • If you need to compare your project with a working solution, you can download the sample application.
  1. helloView displayed in a browser

Setting up a New Project with Spring Web MVC Support

Creating a Spring Web MVC Skeleton Project

Start by creating a new project for a web application using the Spring Framework:

  1. Choose New Project (Ctrl-Shift-N) from the IDE's File menu. Under Categories select Java Web. (If you are using NetBeans 6.1, select Web.) Under Projects select Web Application. Click Next.
  2. In Project Name, type in HelloSpring. Click Next.
  3. In Step 3, Server and Settings, select the server you plan to work with from the Server drop-down list. Leave all other settings at their defaults and click Next.
  4. In Step 4, the Frameworks panel, select Spring Web MVC 2.5:
    Spring Web MVC 2.5 displayed in the Frameworks panel
    When you select Spring Web MVC 2.5, note that you can configure the name and mapping of the Spring dispatcher servlet under the Configuration tab. If you click the Libraries tab, note that JSTL libraries are by default added to the classpath during project creation.

    Click Finish. The IDE creates a project for the entire application, including all metadata, as well as the project's Ant build script which you can inspect from the Files window (Ctrl-2). You can view the template structure from the Projects window (Ctrl-1). Also note that four files open by default in the IDE's Source Editor: dispatcher-servlet.xml, applicationContext.xml, redirect.jsp, and index.jsp.

Running the Skeleton Project

Before making any changes to project files, try running the new project in the IDE:

  1. In the Projects window, right-click the project node and choose Run Project. The IDE automatically starts your server if it is not already running, builds then deploys the application to it. The application runs using the configuration data contained in dispatcher-servlet.xml. Note any output displayed in the IDE's Output window (Window > Output). The generated output completes with a BUILD SUCCESSFUL message:
    Output window displaying information when running the project
    The IDE's default browser starts up, and you see content from the welcome page view (/WEB-INF/jsp/index.jsp):
    Welcome page output displayed in browser

In order to understand what just took place, start by examining the project's deployment descriptor (web.xml). To open this file in the Source Editor, right-click the WEB-INF > web.xml node in the Projects window and choose Edit. The default entry point for the application is redirect.jsp:


redirect.jsp

Within redirect.jsp, there is a redirect statement that points all requests to index.htm:

<% response.sendRedirect("index.htm"); %>

In the deployment descriptor, note that all requests for URL patterns that match *.htm are mapped to Spring's DispatcherServlet:


dispatcher
org.springframework.web.servlet.DispatcherServlet
2



dispatcher
*.htm

The class of the dispatcher servlet, as shown above, is org.springframework.web.servlet.DispatcherServlet. This class is contained in the Spring libraries, which were added to the project classpath when the project was created. To verify this, in the Projects window drill down from the Libraries node:
DispatcherServlet class displayed in the Projects window

The DispatcherServlet handles incoming requests based on configuration settings found in dispatcher-servlet.xml. Open dispatcher-servlet.xml by clicking on its tab in the Source Editor. Note the following code:




indexController






Three beans are defined in this file: indexController, viewResolver, and urlMapping. When the DispatcherServlet receives a request that matches *.htm such as index.htm, it looks for a controller within urlMapping that can accommodate the request. Above, you see that there is a mappings property that links /index.htm to indexController.

The runtime environment then searches for the definition of a bean named indexController, which is conveniently provided by the skeleton project. Note that indexController extends ParameterizableViewController. This is another class provided by Spring, which simply returns a view. Above, note that p:viewName="index" specifies the logical view name, which is resolved using the viewResolver by prepending /WEB-INF/jsp/ and appending .jsp to it. This allows the runtime to locate the file within the WAR file of the application, and respond with the welcome page view (/WEB-INF/jsp/index.jsp).

Overview of the Application

The application you create is comprised of two JSP pages (which are named views in Spring Web MVC terminology). The first view contains an HTML form with an input field asking for the user's name. The second view is a page that simply displays a hello message containing the user's name.

The views are managed by a controller, which receives requests to the application and decides which views to return. It also passes to the views any information that they need to display (this is called a model). This application's controller is named HelloController.

In a complex web application, the business logic is not contained directly in the controller. Instead, another entity, named a service, is used by the controller whenever it needs to perform business logic. In our application, the business logic is the computation of the hello message, so for this purpose you create a HelloService.

Implementing a Service

Now that you are sure your environment is set up properly, you can begin extending the skeleton project according to your needs. Start by creating the HelloService class.

  1. In the Projects window, right-click the project node and choose New > Java Class.
  2. In the New Java Class wizard that displays, enter HelloService for Class Name, and type in service for Package Name to create a new package for the class. Click Finish. The IDE creates the new class and opens it in the Source Editor. Also note that the Projects window automatically updates to reflect changes.

The HelloService class performs a very simple service. It takes a name as a parameter, and prepares and returns a String that includes the name. In the Source Editor, create the following sayHello() method for the class (changes in bold):

public class HelloService {

public String sayHello(String name) {
return "Hello " + name + "!";
}

}

Implementing the Controller and Model

You can use a SimpleFormController to handle user data and determine which view to return.

  1. Open the New File wizard by pressing Ctrl-N (⌘-N on Mac). Under Categories select Spring Framework; under File Types select Simple Form Controller. Click Next.
  2. Name the class HelloController and create a new package for it by typing controller in the Package text field. Click Finish. The IDE creates the new class and opens it in the Source Editor.
  3. Specify controller properties by uncommenting the setter methods that display by default in the class template. Make changes as follows (changes in bold):
    public HelloController() {
    setCommandClass(Name.class);
    setCommandName("name");
    setSuccessView("helloView");
    setFormView("nameView");
    }
    Setting the FormView enables you to set the name of the view that is used to display the form. This is the page that contains the text field allowing users to enter their name. Setting the SuccessView likewise lets you set the name of the view that should display upon a successful submit. When you set the CommandName you define the name of the command in the model. In this case, the command is the form object with request parameters bound onto it. Setting the CommandClass allows you set the name of the command class. An instance of this class gets populated and validated upon each request.

    Note that an error is flagged for Name in the setCommandClass() method:
    The Source Editor displaying an error for setCommandClass()
    You need to create the Name class as a simple bean to hold information for each request.
  4. In the Projects window, right-click on the project node and choose New > Java Class. The New Java Class wizard displays. Enter Name for the Class Name, and for Package select controller from the drop-down list. Click Finish. The Name class is created and opened in the Source Editor.
  5. For the Name class, create a field named value, then create accessor methods for this field. Type in the following (changes in bold):
    public class Name {

    private String value;
    The IDE can create accessor methods for you. In the Source Editor, right-click on value and choose Insert Code (or press Alt-Insert; Ctrl-I on Mac) to open the Generate Code popup menu. Then choose Getter and Setter.
    The Generate Code popup menu displayed in Source Editor
  6. In the dialog that displays, select the value : String option, then click OK. The getValue() and setValue() methods are added to the Name class:
    public String getValue() {
    return value;
    }

    public void setValue(String value) {
    this.value = value;
    }
  7. Click back to HelloController in the Source Editor and notice the previous error badge has disappeared due to the fact that you created the Name class. Delete the doSubmitAction() method and uncomment the onSubmit() method. The onSubmit() method enables you to create your own ModelAndView, which is what is required here. Make the following changes:
    @Override
    protected ModelAndView onSubmit(Object command) throws Exception {
    Name name = (Name)command;
    ModelAndView mv = new ModelAndView(getSuccessView());
    mv.addObject("helloMessage", helloService.sayHello(name.getValue()));
    return mv;
    }
    As indicated above, the command is recast as a Name object. An instance of ModelAndView is created, and the success view is obtained using a getter in SimpleFormController. Finally, the model is populated with data. The only item in our model is the hello message obtained from the HelloService created earlier. You use the addObject() method to add the hello message to the model under the name helloMessage.
  8. Fix import errors by right-clicking in the Source Editor and choosing Fix Imports (Ctrl-Shift-I; ⌘-Shift-I on Mac). The following import statement is added to the top of the file:
    import org.springframework.web.servlet.ModelAndView;
    Not all errors are fixed however, because the class still cannot identify the HelloService class, nor make use of its sayHello() method.
  9. Within HelloController, declare a private field named HelloService:
    private HelloService helloService;
    Then create a public setter method for the field:
    public void setHelloService(HelloService helloService) {
    this.helloService = helloService;
    }
    Finally, right-click again in the Source Editor and choose Fix Imports. Note that the following statement is added to the top of the file:
    import service.HelloService;
    All errors should now be fixed.
  10. Register HelloService in applicationContext.xml. Open applicationContext.xml in the Source Editor and enter the following bean declaration:
    Spring support in the IDE includes code completion within XML configuration files for Java classes as well as bean references. To invoke code completion, press Ctrl-Space when working in the Source Editor:
    Code completion invoked when pressing Ctrl-Space
  11. Register HelloController in dispatcher-servlet.xml. Open dispatcher-servlet.xml in the Source Editor and enter the following bean declaration:

Implementing the Views

To implement the view for this project, you need to create two JSP classes. The first, which you will call nameView.jsp, serves as the welcome page and allows a user to input a name. The other page, helloView.jsp, displays a greeting message that includes the input name. Begin by creating helloView.jsp.

  1. In the Projects window, right-click the WEB-INF > jsp node and choose New > JSP. The New JSP File wizard opens. Name the file helloView. Click Finish. The new JSP file is created in the jsp folder and opens in the Source Editor.
  2. In the Source Editor, change the file's title to Hello, and change the output message to retrieve the helloMessage of the ModelandView object that is created in HelloController:


    <strong>Hello</strong>


    ${helloMessage}



  3. Create another JSP File in the same manner as above, but name it nameView.
  4. In the Source Editor, add the following tag library declaration to nameView.jsp:
    <%@taglib uri="http://www.springframework.org/tags" prefix="spring" %>
    This imports the Spring tag library, which contains tags useful when implementing views as JSP pages.
  5. Change the contents of the and

    tags to read: Enter Your Name.

  6. Enter the following code beneath the h2 tags:


    Name:






    spring:bind allows you to bind a bean property. The bind tag provides a bind status and value, which you use as the name and value of the input field. This way, when the form is submitted, Spring will know how to extract the submitted value. Here, our command class (controller.Name) has a value property, therefore you set the path to value.

    spring:nestedPath enables you to prepend a specified path to a bean. So, when used with spring:bind as shown above, the path to the bean becomes: name.value. As you recall, the command name of HelloController is name. Therefore, this path refers to the value property of a bean named name in the page scope.
  7. Change the relative entry point for the application. Currently, the project entry point is still index.htm which, as described in Running the Skeleton Project above, redirects to WEB-INF/jsp/index.jsp. You can specify an entry point for the project when it is deployed and run. In the Projects window, right-click the project node and choose Properties. The Project Properties dialog displays. Under Categories select Run. In the Relative URL field, type in /hello.htm, then click OK.

    At this moment you may wonder where the mapping of hello.htm to HelloController is located. You have not added a mapping to the urlMapping bean, as is the case for index.htm, the skeleton project's welcome page. This is possible with a bit of Spring magic provided by the following bean definition in dispatcher-servlet.xml:

    This bean is reponsible for automatically creating an URL mapping for all controllers registered in the file. It takes the fully-qualified class name of the controller (in our case, controller.HelloController) and strips the package name and Controller suffix, then uses the result as a URL mapping. Therefore, for HelloController it creates a hello.htm mapping. This magic however does not work for controllers that are included in the Spring Framework, such as ParameterizableViewController. They require an explicit mapping.
  8. In the Projects window right-click the project node and choose Run. This compiles, deploys and runs the project. Your default browser opens, displaying hello.htm as the project's nameView:
    nameView displayed in a browser
    Enter your name in the text field and click enter. The helloView displays with a greeting message: