Chapter 6. Writing Java Web Applications

IN THIS CHAPTER

  • The Model-View-Controller pattern

  • The Spring Framework

  • Writing a simple Web application

Even the most dynamic Flex user interface needs live data to make it more valuable than just a static page. Web applications typically get their data from an application server that handles requests from the user interface and then returns the requested data for the user interface to display. Java is well-suited to meet this need. Java application servers and Web application frameworks have been around for a number of years now and provide a stable back-end base upon which to build your dynamic Web applications.

In this chapter, you build a simple Web application to receive the request from the Flex client. The Web applications you build throughout this book use a popular open-source Java application framework called Spring. This chapter starts with a look at the Model-View-Controller pattern, followed by an introduction to the Spring Framework. After that, you write a simple Web application using Spring and then compile and deploy it to a server by using an Ant build script.

The Model-View-Controller Pattern

In software development, an architectural pattern refers to a proven, repeatable way to describe the structure of an application. Java Web applications are typically written by using the Model-View-Controller (MVC) architectural pattern. The objective of using the MVC pattern is to separate the user interface from the data and business logic so that changes to one don't require changes to the other. For example, if a Web application is written with a JSP/HTML user interface, and the requirements for the next version include changing the user interface to Flex, using the MVC pattern would allow the user interface portion of the application to be replaced without touching the business logic.

The MVC pattern divides application code into three parts:

  • The model consists of the objects representing the application's data and the business logic code that handles and manipulates those objects.

  • The view consists of the code and user interface elements that together make up the user interface for the application.

  • The controller consists of the code that handles communication to the model about actions taken on the user interface elements in the view (for example, a request to the model for data when a user interface button is clicked).

Typically, some event in the user interface sends a request to a controller. The controller retrieves the parameters for the request and then passes them on to the business logic in the model. The model retrieves or manipulates data based on the parameters passed on by the controller and then returns the requested data to the controller. Finally, the controller places the data into the view and then returns that view to the user.

The Spring Framework

The Spring Framework is a lightweight Java framework whose purpose is to make developing complex Java applications easier and to allow a programmer to create loosely coupled, highly reusable code. Loosely coupled means that code modules are as independent of one another as possible. This makes it easier to alter one part of an application without touching other parts. This is invaluable in large software projects but also desirable in smaller projects where modules that interact with one another are subject to frequent changes. Without loosely coupled code, changes to one module would likely require changes to one or more other modules. This can lead to maintenance problems, as it becomes harder and harder to keep up with all the required changes.

Spring's most widely used feature is known as dependency injection. Dependency injection allows the Spring Framework to provide an object with the other objects it needs to work instead of the object needing to create or locate those objects itself. When an object that's managed by the Spring Framework (known in Spring terminology as a Spring bean) needs some other object to do its work, the Spring container provides the needed object. The Spring container is said to inject the object with its dependencies so that they're available to the object when needed.

The Spring Framework consists of a number of modules, and going into detail about them would require a book of its own. But because Spring is modular, you can pick and choose the pieces you want to use and ignore the others or you can use different pieces of the framework as they become appropriate. For the first application, you use a handful of Spring modules. As the applications grow in size and complexity, more pieces of the Spring Framework enter the picture.

For the first Web application, the following Spring modules are used:

  • Application context. The Spring application context module builds upon Spring's core. It provides the basic Spring functionality, such as dependency injection, as well as support for more advanced functionality, such as remote services.

  • Spring MVC. This is the Spring Framework's implementation of the Model-View-Controller pattern. It includes a number of classes and interfaces that help create applications that follow the MVC paradigm.

  • Spring Web. Spring's Web module contains support for using MVC code within Spring's application context. It also contains functionality that allows form fields and other request parameters in a Web application to be bound directly to server-side Java objects and provides integration with various view technologies.

The Spring Framework can be downloaded from the Spring Framework Web site at http://springframework.org/download. As of this writing, the latest stable version of Spring is 2.5.5. Click the Download link for the latest release to go to the download file listing page, as shown in Figure 6.1. Click the link labeled spring-framework-<version>-with-dependencies.zip (for example, spring-framework-2.5.5-with-dependencies.zip). Save the archive to your machine and then extract it to a directory of your choice.

Note

Updates to the Spring Framework are likely, so use the current version available.

Each of the Spring Framework modules is packaged in its own JAR file. The core Spring modules, such as the application context module, are located in the spring.jar file in the dist directory of the Spring Framework distribution. Other Spring modules, such as Spring Web MVC, are located in their own JAR files in the distmodules directory. The Spring Framework distribution also comes packaged with other libraries that can be used for such things as application logging and using JSP tag libraries in Web applications.

Documentation for the Spring Framework can be found in the docs folder of the Spring Framework distribution. Plenty of valuable examples and reference materials are found there. It's worth spending some time going through these materials to get a feel for what the Spring Framework provides.

The file listing page on the Spring Framework download Web site contains a few different options for download. Download the -with-dependencies version, which contains everything needed to run and build the Spring Framework.

Figure 6.1. The file listing page on the Spring Framework download Web site contains a few different options for download. Download the -with-dependencies version, which contains everything needed to run and build the Spring Framework.

Writing a Simple Web Application

Now that you know a little more about Spring Framework and what it provides, it's time to write a simple Web application using Spring — a Spring Web application version of the classic "Hello, World!" application. First, you create a new project inside your Eclipse workspace. Next, you configure the project properties. Finally, you write the code and configuration files for the application.

The project directory structure

A Java Web application project typically consists of Java source files, XML configuration files, JSP files, and Web assets, such as HTML and image files. Using a consistent directory structure for all your Java Web application projects helps speed development by separating these various pieces into well-known areas. It also helps you reuse Ant build files by allowing you to put common, generic paths into your build files and separating out project-specific settings into a properties file that the build file can import.

The Web application projects in this book all use a consistent directory structure. Some projects may have pieces that others don't, but they all share a few basic pieces. Figure 6.2 shows the project directory structure for the simple Web application you write in this chapter. This structure is created for you by Eclipse when you start developing your Web application.

Typically, the top-level directory has the same name as your application. Below this directory, there are three other directories:

  • The bin directory contains the compiled Java class files.

  • The src directory contains Java source code files.

  • The web directory contains non-Java files for the application, including XML configuration files, JSP pages, and images. Below this web folder is a WEB-INF folder, which contains configuration files for the Web application and any other resources needed by the Web application that shouldn't be directly accessible through the Web browser (for example, JSP views that should be served up only by calls to services on the server). Below the WEB-INF folder is a lib folder, which contains library JAR files needed by the Web application.

A typical Java Web application directory structure contains folders for Java source code, Web application code, and compiled Java class files. Using a standardized directory structure is a best practice when developing a Java Web application.

Figure 6.2. A typical Java Web application directory structure contains folders for Java source code, Web application code, and compiled Java class files. Using a standardized directory structure is a best practice when developing a Java Web application.

Note

When you're using JBoss, library JAR files must be placed directly in the WEB-INFlib folder. They can't be placed in subfolders beneath the WEB-INFlib folder. Other application servers, such as IBM's Websphere, do allow subfolders for library JAR files.

Now that you've seen what the directory structure for a Java Web application project looks like, you can set up a project in Eclipse.

Creating an Eclipse project

Although you can create this directory structure on your own, because you're using the Eclipse IDE, you can let Eclipse set up this directory structure for you by creating a new project in Eclipse. Eclipse creates much of the necessary directory structure by using a wizard. Once the project has been created, you can add any other needed folders and files as necessary within the Eclipse environment.

To create a new project in Eclipse, follow these steps:

  1. Open Windows Explorer by choosing Start

    Creating an Eclipse project
    All Programs
    Creating an Eclipse project
    Accessories
    Creating an Eclipse project
    Windows Explorer
    .

  2. Navigate to the Eclipse install directory and then double-click eclipse.exe. Eclipse launches. If you didn't click the Use this as the default and don't ask again check box the first time you ran Eclipse, Eclipse again asks you to choose a workspace directory.

  3. Leave the default value in place and then click OK.

  4. Create a new project by choosing File

    Creating an Eclipse project
    New
    Creating an Eclipse project
    Project or right-clicking within the Project Explorer view and choosing New
    Creating an Eclipse project
    Project from the popup menu
    . The New Project dialog box, as shown in Figure 6.3, opens.

  5. Click the arrow next to Spring to expand it, choose Spring Project, and then click Next. The New Spring Project dialog box, as shown in Figure 6.4, opens.

  6. Type a name for the project and then click Finish. The dialog box closes, and the newly created project appears in the Project Explorer view.

In the New Spring Project dialog box, the default values in the Source Folder Name and Output Folder Name text fields are src and bin, respectively. These names match the names discussed in the previous section. Eclipse creates these directories for you when you create a new project, and Eclipse can also automatically compile the Java code in the src directory and then output the compiled Java class files to the bin directory as you work.

The New Project dialog box in Eclipse is the first step in creating a new project. Eclipse supports many different types of projects out of the box, and you can add more types by using plug-ins.

Figure 6.3. The New Project dialog box in Eclipse is the first step in creating a new project. Eclipse supports many different types of projects out of the box, and you can add more types by using plug-ins.

Take a few minutes to explore the newly created project. Click the arrow to the left of the project name in the Project Explorer view to expand the project, as shown in Figure 6.5.

When you create a new Spring project in Eclipse, it adds a few elements to the project automatically:

  • The Spring Elements item lets you visualize the relationships among your Spring beans.

  • The JRE System Library item includes all the standard Java libraries from your installed JDK. These libraries are what Eclipse uses to compile your Java code.

  • The src folder is the place where you add your Java source code.

Even though the New Spring Project dialog box contains an item for an output folder named bin, this item doesn't appear in the expanded project. This is because Java class files are binary and won't ever be edited.

The New Spring Project dialog box contains settings for creating a new Spring project. The default values conform to standard Spring project development practices and shouldn't be changed for most applications.

Figure 6.4. The New Spring Project dialog box contains settings for creating a new Spring project. The default values conform to standard Spring project development practices and shouldn't be changed for most applications.

Eclipse automatically adds a few necessary elements to newly created projects.

Figure 6.5. Eclipse automatically adds a few necessary elements to newly created projects.

Configuring the Eclipse project

Before diving into coding, you have some project configuration steps to do. Once the project has been configured, you can write, compile, deploy, and test your first application.

To configure the Eclipse project, follow these steps in Eclipse:

  1. Right-click your project in the Project Explorer view and then choose New

    Configuring the Eclipse project
    Folder from the popup menu. The New Folder dialog box, as shown in Figure 6.6, opens.

    The New Folder dialog box allows you to add new folders to your project. You can type nested folder paths here (for example, webWEB-INFlib) and then Eclipse creates the entire structure for you.

    Figure 6.6. The New Folder dialog box allows you to add new folders to your project. You can type nested folder paths here (for example, webWEB-INFlib) and then Eclipse creates the entire structure for you.

  2. Type webWEB-INFlib in the Folder name text field and then click Finish. The New Folder dialog box closes, and the newly created folder structure is added to the project, as shown in Figure 6.7.

  3. Right-click the lib folder and then choose Import from the popup menu. The Import dialog box, as shown in Figure 6.8, opens.

  4. Click the arrow next to the General item to expand it, choose File System from the list, and then click Next. The Import dialog box, as shown in Figure 6.9, opens.

  5. Click the Browse button next to the From directory text field. The Import from directory dialog box, as shown in Figure 6.10, opens.

    Folders are displayed in the project in a nested structure much like Windows Explorer.

    Figure 6.7. Folders are displayed in the project in a nested structure much like Windows Explorer.

    The Import dialog box allows you to import resources for your project from a variety of sources.

    Figure 6.8. The Import dialog box allows you to import resources for your project from a variety of sources.

  6. Navigate to your extracted Spring Framework directory, select it, and then click OK. The directory appears in the left pane of the Import dialog box, as shown in Figure 6.11. Clicking the Spring Framework directory displays its contents in the right pane of the dialog box. Clicking the arrow next to the directory name on the left expands it to display its subfolders.

  7. Click the arrow next to the Spring Framework directory in the left pane to expand it, click the dist folder in the left pane, and then click the check box next to spring.jar, which is in the right pane.

  8. Click the arrow next to the dist folder in the left pane to expand it, click the modules folder in the left pane and then click the check box next to spring-webmvc.jar, which is in the right pane, as shown in Figure 6.12.

  9. Click the arrow next to the lib folder under the expanded Spring Framework folder in the left pane to expand it, click the j2ee folder in the left pane, and then click the check box next to jstl.jar, which is in the right pane, as shown in Figure 6.13.

    The Import dialog box lets you bring resources from your computer's file system into your project. Resources are copied from their original locations into your project's directory structure.

    Figure 6.9. The Import dialog box lets you bring resources from your computer's file system into your project. Resources are copied from their original locations into your project's directory structure.

    The Import from directory dialog box allows you to choose directories and resources to import into your project.

    Figure 6.10. The Import from directory dialog box allows you to choose directories and resources to import into your project.

    Once you've chosen your extracted Spring Framework directory, it appears in the left pane of the Import dialog box, and its contents appear in the right pane. Clicking the arrow next to the directory in the left pane expands it to display its subfolders.

    Figure 6.11. Once you've chosen your extracted Spring Framework directory, it appears in the left pane of the Import dialog box, and its contents appear in the right pane. Clicking the arrow next to the directory in the left pane expands it to display its subfolders.

  10. Click the jakarta-taglibs folder under the expanded lib folder in the left pane and then click the check box next to standard.jar, which is in the right pane, as shown in Figure 6.14. The spring.jar, spring-webmvc.jar, jstl.jar, and standard.jar libraries contain all the pieces of the Spring Framework that you need for this application. As you move on to more complex projects where more pieces of Spring are needed, you can use this same import process to easily bring them into your projects.

  11. Click Finish. The Spring Framework libraries you just added appear beneath the webWEB-INFlib folder in subfolders, as they were in the Spring Framework directory.

  12. Drag the JAR files from their subfolders directly into the webWEB-INFlib folder, right-click each of the empty folders, and then choose Delete from the popup menu. When you finish, the Project Explorer view should look like the one in Figure 6.15, with all the JAR files appearing directly within the lib folder and the empty subfolders gone. Dragging the JAR files directly into the webWEB-INFlib folder is required because library JAR files for a Web application must be placed directly in the lib directory under WEB-INF in order to be found by JBoss.

Click the spring.jar and spring-webmvc.jar libraries to be imported from the dist and distmodules folders, respectively, under the extracted Spring Framework folder.

Figure 6.12. Click the spring.jar and spring-webmvc.jar libraries to be imported from the dist and distmodules folders, respectively, under the extracted Spring Framework folder.

Although you added the Spring libraries to your project, Eclipse doesn't use them to compile your Java code unless you explicitly configure it to do so. Eclipse uses a setting called the Java Build Path to tell it where Java source code is kept, where Java class files should be output, and where libraries needed to compile the Java source code into Java class files can be found. The Java Build Path in Eclipse is essentially the same as the classpath that needs to be set when compiling Java classes manually by using the JDK's Java compiler. You need to configure this setting next.

Choose the jstl.jar library to be imported from the libj2ee folder under the extracted Spring Framework folder.

Figure 6.13. Choose the jstl.jar library to be imported from the libj2ee folder under the extracted Spring Framework folder.

Choose the standard.jar library to be imported from the libjakarta-taglibs folder under the extracted Spring Framework folder.

Figure 6.14. Choose the standard.jar library to be imported from the libjakarta-taglibs folder under the extracted Spring Framework folder.

After you drag the library JAR files from their subfolders into the webWEB-INFlib folder and then delete the emptied subfolders, the Project Explorer view should look like this.

Figure 6.15. After you drag the library JAR files from their subfolders into the webWEB-INFlib folder and then delete the emptied subfolders, the Project Explorer view should look like this.

To configure the Java Build Path for your project, follow these steps:

  1. Right-click your project in the Project Explorer view and then choose Properties from the popup menu. The Properties dialog box opens.

  2. Click Java Build Path in the left navigation pane of the Properties dialog box. The Java Build Path tabbed section opens in the right pane, as shown in Figure 6.16.

    Choosing Java Build Path in the left pane of the Properties dialog box opens the Java Build Path tabbed section in the right pane.

    Figure 6.16. Choosing Java Build Path in the left pane of the Properties dialog box opens the Java Build Path tabbed section in the right pane.

  3. Click the Libraries tab. A list of library JAR files and class folders appears. As shown in Figure 6.17, the JRE System Library from the installed JDK is already included in this list.

  4. Click the Add JARs button. The JAR Selection dialog box opens.

  5. Click jstl.jar, spring-webmvc.jar, spring.jar, and standard.jar, as shown in Figure 6.18, and then click OK. The files are added to the library list, as shown in Figure 6.19.

  6. Click the Add External JARs button. The JAR Selection dialog box opens.

  7. Navigate to the client folder within your JBoss installation, choose the servlet-api.jar file, and then click OK. The servlet-api.jar library is added to the library list, as shown in Figure 6.20.

    Note

    If you have JAR files that need to be deployed with your application, you import them into your project first and then add them to the build path using the Add JARs button. For JAR files that don't need to be deployed with your application, simply add them to the build path for your project by using the Add External JARs button. This allows Eclipse to use the JAR library to compile your Java code, but it doesn't copy it into your project. In this case, you need to package and deploy the Spring Framework JAR files with the application, but the servlet-api.jar file is already part of the JBoss server, so you don't need to deploy it with your application.

  8. Click OK. The Properties dialog box closes.

The JRE System Library from your installed JDK is automatically added to the JAR files and class folders list in the Library tab.

Figure 6.17. The JRE System Library from your installed JDK is automatically added to the JAR files and class folders list in the Library tab.

Click the jstl.jar, spring-webmvc.jar, spring.jar, and standard.jar files in the JAR Selection dialog box to add them to the build library path for your project.

Figure 6.18. Click the jstl.jar, spring-webmvc.jar, spring.jar, and standard.jar files in the JAR Selection dialog box to add them to the build library path for your project.

The JAR files now appear in the build library path.

Figure 6.19. The JAR files now appear in the build library path.

The servlet-api.jar is added to the build library path. The entry shows the full path to the JAR on your computer. This indicates that the JAR file hasn't been copied into the project but instead is referenced externally.

Figure 6.20. The servlet-api.jar is added to the build library path. The entry shows the full path to the JAR on your computer. This indicates that the JAR file hasn't been copied into the project but instead is referenced externally.

Writing the Web application

Now that the Eclipse project has been configured, it's time to start writing the application. Using the Spring Framework Web MVC module, this application follows the Model-View-Controller (MVC) pattern. Here's how the pieces of the application fit into the pattern:

  • The model represents the data and business logic for the application. In this case, there isn't any real business logic, just data: the "Hello, World!" message.

  • The controller receives requests from the user interface, passes the parameters from the request off to the business logic and receives the requested data, and then passes that data back to the user interface view. A Java class implementing Spring Web MVC's Controller interface handles that task.

  • The view is the user interface for the application, and the view contains the data from the model. The view for this application is a JSP that receives the "Hello, World!" message and displays it.

The Model and Controller

Spring's Controller interface contains a single method, handleRequest, that receives requests from the user interface and responds with the requested data. Eclipse can create the stub of a controller for you by using a wizard.

In Java development, classes are divided into smaller groups of related functionality called packages. Packages for Web applications are typically named following a pattern that describes the company or organization the code is being written for, the specific project the code is part of, and what functionality the code provides. For example, the application in this chapter uses the package com.wiley.jfib.ch06.helloworld.service for the controller. Controllers are often referred to as services, as they service the requests of clients.

Note

For more on packages and other Java concepts, see Chapter 1.

To create the controller class, follow these steps:

  1. Right-click the src folder of your project in the Project Explorer view and then choose New

    The Model and Controller
    Package from the popup menu. The New Java Package dialog box opens.

  2. Type com.wiley.jfib.ch06.helloworld.service in the Name text field, as shown in Figure 6.21, and then click Finish. The new package appears under the project's src folder in the Project Explorer, as shown in Figure 6.22.

  3. Right-click the newly created package and then choose New

    The Model and Controller
    Class from the popup menu. The New Java Class dialog box, as shown in Figure 6.23, opens. The Source folder and Package text fields are already filled in for you with the correct values.

  4. Type HelloWorldService in the Name text field.

    Type the package name in the Name text field of the New Java Package dialog box.

    Figure 6.21. Type the package name in the Name text field of the New Java Package dialog box.

    The newly created package appears under the src folder of your project in the Project Explorer view.

    Figure 6.22. The newly created package appears under the src folder of your project in the Project Explorer view.

    The New Java Class dialog box, with the Source folder and Package text fields already filled in with the correct values

    Figure 6.23. The New Java Class dialog box, with the Source folder and Package text fields already filled in with the correct values

  5. Click the Add button next to the Interfaces list box. The Implemented Interfaces Selection dialog box opens.

  6. Type Controller in the Choose interfaces text field. As you type, the Matching items list box fills in potential matches, as shown in Figure 6.24.

  7. Choose Controller - org.springframework.web.servlet.mvc from the list box and then click OK. The Implemented Interfaces Selection dialog box closes, and the Controller interface is added to the Interfaces list box in the New Java Class dialog box, as shown in Figure 6.25.

  8. Click the Generate comments check box and then click Finish. The New Java Class dialog box closes, and the newly created HelloWorldService class opens in the editor, as shown in Figure 6.26.

As you type in the Choose interfaces text field of the Implemented Interfaces Selection dialog box, the Matching items list begins to fill in with interfaces that match what you type.

Figure 6.24. As you type in the Choose interfaces text field of the Implemented Interfaces Selection dialog box, the Matching items list begins to fill in with interfaces that match what you type.

It's worth taking a look at the various pieces of this Java class before moving on. It may help you to display the line numbers for the file to make it easier to follow along. To show the line numbers, right-click the left margin of the editor and then choose Show Line Numbers from the popup menu. The line numbers appear in the left margin of the editor.

Eclipse also has a feature called folding, which allows you to expand or collapse sections of the file, such as import statements, comment blocks, and code blocks. This feature makes working with large Java files easier. When you're interested in only one particular piece of code, you can use folding to collapse the rest. Folded blocks of code have a small + button next to them, which can be clicked to expand them. Expanded blocks can be folded again by clicking the small – button next to them. In this case, being able to see all the code in this small file is more useful for walking through the various pieces. You can quickly expand all folded sections in a Java file by right-clicking the left margin of the editor again and then choosing Folding

As you type in the Choose interfaces text field of the Implemented Interfaces Selection dialog box, the Matching items list begins to fill in with interfaces that match what you type.
After you select an interface in the Implemented Interfaces Selection dialog box, it appears in the Interfaces list box in the New Java Class dialog box. A Java class can have multiple interfaces.

Figure 6.25. After you select an interface in the Implemented Interfaces Selection dialog box, it appears in the Interfaces list box in the New Java Class dialog box. A Java class can have multiple interfaces.

Once you've finished with the New Java Class dialog box, the newly created Java class stub is opened in the editor.

Figure 6.26. Once you've finished with the New Java Class dialog box, the newly created Java class stub is opened in the editor.

Line 4 of the HelloWorldService Java class is the package statement, which lets Java know what package the class is in. Lines 6 through 10 are import statements. Import statements are used to inform this class of the locations of other classes it needs. On its own, a class has access only to other classes in the same package and any classes in the standard java.lang package that's part of the JDK. For HelloWorldService, four other classes are also needed:

  • javax.servlet.HttpServletRequest. This class represents the request coming from an HTTP client, such as a Web browser, to the server. It contains information about the client's locale, any cookies relevant to the application, authentication information, and other information the server may need to know about the client. An instance of this class is passed as a parameter to HelloWorldService's handleRequest method.

  • javax.servlet.HttpServletResponse. This class represents the response going from the server to the HTTP client. This typically includes things that a Web browser might need to know, such as server status codes and HTTP headers. An instance of this class is passed as a parameter to HelloWorldService's handleRequest method.

  • org.springframework.web.servlet.ModelAndView. This class is a convenient container for both the model data packaged up for use by the view and a reference to the view itself. An instance of this class is returned by HelloWorldService's handleRequest method.

  • org.springframework.web.servlet.mvc.Controller. This interface is implemented by HelloWorldService.

Line 16 is the class declaration. The class declaration contains the name of the class, the name of the class it extends (optional), and the names of any interfaces it implements (optional). Extending a class means adding functionality to or modifying functionality in an existing class. When a Java class extends another class, it has access to all the public member variables and methods in the extended class and can override those public methods with its own implementations. Unless otherwise specified, all Java classes extend the Object class in the java.lang package. HelloWorldService extends Object, so there's no extends statement in the class declaration. An interface in Java is a set of one or more methods without implementations. When a Java class implements an interface, it's then required to provide an implementation for any methods in the interface. In this example, HelloWorldService implements the Controller interface from the org.springframework.web.servlet.mvc package. The Controller interface has one method: handleRequest. Because HelloWorldService implements Controller, it needs to provide an implementation for the handleRequest method. Eclipse provides a default implementation of handleRequest when it generates the stub class file.

Note

For more on Java syntax, see Chapter 1.

You can now change the default implementation of handleRequest with code that returns a "Hello, World!" message to the client. To do this, you change the handleRequest method so that it looks like this:

/* (non-Javadoc)
 * @see org.springframework.web.servlet.mvc.
   Controller#handleRequest(javax.servlet.http.HttpServletRequest,
   javax.servlet.http.HttpServletResponse)
 */
@Override
public ModelAndView handleRequest(HttpServletRequest arg0,
          HttpServletResponse arg1) throws Exception {
     // the message for the client
     return new ModelAndView("WEB-INF/jsp/hello-world.jsp",
          "message","Hello, World!");
}

The Spring Web MVC module's ModelAndView object holds both the model and the view and allows the controller to return both at once. The constructor used here for the ModelAndView object has three parameters. The first parameter is the location of the view. The view for HelloWorldService is a JSP page named hello-world.jsp located in the WEB-INF/jsp folder. The second parameter is the name of the model. The view uses this name to retrieve the model. The model for this request is named message. The final parameter is the model itself. The data being returned to the client in this case is the string "Hello, World!"

The View

Now that you've got a controller that can handle a request and return data, you need to create the view that displays the data. For this example, you write a simple JSP page to act as the view.

To create the JSP page for the view, follow these steps:

  1. Right-click the web/WEB-INF folder in the Project Explorer view and then choose New

    The View
    Folder from the popup menu. The New Folder dialog box opens.

  2. Type jsp in the Folder name text field and then click Finish. The New Folder dialog box closes, and the newly created folder appears below the WEB-INF folder in the Project Explorer view.

  3. Right-click the web/WEB-INF/jsp folder in the Project Explorer view and then choose New

    The View
    Other from the popup menu. The Select a wizard dialog box opens.

  4. Click the arrow next to Web to expand it, click JSP, and then click Next. The New JavaServer Page wizard, as shown in Figure 6.27, opens.

  5. Type hello-world.jsp in the File name text field and then click Next. The Select JSP Template screen, as shown in Figure 6.28, opens.

    The first screen of the New JavaServer Page wizard is where you give the JSP file a name.

    Figure 6.27. The first screen of the New JavaServer Page wizard is where you give the JSP file a name.

    The second screen of the New JavaServer Page wizard allows you to choose a template for your JSP. Templates include many of the required HTML tags and JSP directives, allowing you to concentrate on filling in the details.

    Figure 6.28. The second screen of the New JavaServer Page wizard allows you to choose a template for your JSP. Templates include many of the required HTML tags and JSP directives, allowing you to concentrate on filling in the details.

  6. Click New JSP File (xhtml) in the JSP template list and then click Finish. The New JavaServer Page wizard closes, and the newly created JSP is opened in the editor, as shown in Figure 6.29.

A JSP is basically just a regular HTML or XHTML file with a few special tags that have meaning to the server. When a JSP is requested, the server actually compiles the JSP into a Java class file in much the same way that a regular Java file is compiled. The code in the compiled JSP then outputs HTML or XHTML to a browser to be displayed.

Take a look at lines 2 and 3 of the hello-world.jsp file. These lines are referred to as a JSP directive. A JSP directive is a special tag that begins with the characters <%@. There are many types of JSP directives. This one is called a page directive, which tells the server what language the code on the page is written in (java, in this case), what the returned content MIME type is (text/html), and the character set used by the page (ISO-8859-1). Page directives can also be used to import Java classes into the page, much like the import statement in a Java file.

Now that you have a JSP stub, you need to get your model data into it and display it. You do that by adding some more JSP directives to the page to retrieve the data and then another to output it in the page.

After you complete the New JavaServer Page wizard, the newly created JSP appears in the editor. The template chosen in the last step of the wizard provides the basic HTML tags and JSP directives, allowing you to concentrate on filling in the details.

Figure 6.29. After you complete the New JavaServer Page wizard, the newly created JSP appears in the editor. The template chosen in the last step of the wizard provides the basic HTML tags and JSP directives, allowing you to concentrate on filling in the details.

Add the following line of code immediately after the page directive in the JSP file:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

This is a tag library (taglib) directive. A tag library is a set of custom tags that provides extended functionality to JSP pages outside the built-in functionality. This example uses the Java Server Pages Standard Tag Library (JSTL) to add tags that allow you to access and output data in the model more easily. The prefix attribute of the taglib directive specifies the namespace prefix that the tag libraries' tags use. This is necessary because different tag libraries might include tags with the same name. The prefix ensures that the server knows which tag library a given tag belongs to. This JSP uses the prefix c to identify tags contained in the JSTL tag library. The uri attribute tells the server where the description of the tag library can be found. The server uses this description to validate that tags used in the JSP follow the correct syntax. The code for the JSTL tag library itself is contained in the jstl.jar file you previously imported into the project. The JAR file needs to be deployed to the server with the application in order for the JSTL tag libraries to be available to the application at runtime.

Change the text in the title tag to something more descriptive than Insert title here and then add this line of code to the empty space between the start and end <body> tags:

<c:out value="${message}"/>

The c prefix indicates that this is a tag from the JSTL tag library: the out tag. The out tag simply outputs the contents of its value attribute to the JSP. The value attribute of this tag is a variable reference to a variable named message. A variable reference contains the name of some variable surrounded by ${}. Notice that message is also the name you gave your model in the HelloWorldService controller. This tag reads the value of message from the model and then outputs its value to the JSP view.

Wiring the pieces together

You now have a controller that provides model data to a JSP view. To get everything working together, you need to create and edit some configuration files.

The first configuration file is web.xml. This file is the application descriptor file used by all Java Web applications. Among other things, web.xml contains entries for any Java servlets in the Web application and the URL patterns that map to those servlets.

In standard Spring Web MVC applications, you generally don't need to write servlets yourself. Spring provides a servlet, the DispatcherServlet, that receives incoming requests and passes those along to the appropriate controller. The controllers do the work of gathering the data into the model and then packaging it up for the view.

The Spring DispatcherServlet is configured in web.xml. The controllers are configured in one or more Spring configuration files. These are additional XML files that provide definitions for the controller classes and URL mappings that tell the DispatcherServlet which controller is responsible for which URL.

To create the web.xml configuration file, follow these steps:

  1. Right-click the web/WEB-INF/ folder in the Project Explorer view and then choose New

    Wiring the pieces together
    Other from the popup menu. The Select a wizard dialog box opens.

  2. Click the arrow next to XML to expand it, click XML in the submenu, and then click Next. The New XML File wizard, as shown in Figure 6.30, opens.

  3. Type web.xml in the File name text field and then click Next. The Create XML File From screen, as shown in Figure 6.31, opens.

  4. Click the Create XML file from an XML template radio button and then click Next. The Select XML Template screen, as shown in Figure 6.32, opens.

  5. Click the xml declaration template in the list and then click Finish. The New XML File wizard closes, and the newly created web.xml file opens in the editor.

The XML schema definition for web.xml can be found online at http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd. There are a number of tags and attributes that can be found in a web.xml file, too numerous to go through in their entirety here. For the HelloWorld application, only the following basic structure is required:

<web-app>
     <servlet>
          <servlet-name></servlet-name>
          <servlet-class></servlet-class>
          <load-on-startup></load-on-startup>
     </servlet>
     <servlet-mapping>
          <servlet-name></servlet-name>
          <url-pattern></url-pattern>
     </servlet-mapping>
</web-app>
The first screen of the New XML File wizard is where you give the XML file a name.

Figure 6.30. The first screen of the New XML File wizard is where you give the XML file a name.

The second screen of the New XML File Wizard allows you to create a new XML file from a template.

Figure 6.31. The second screen of the New XML File Wizard allows you to create a new XML file from a template.

The <web-app> tag is the topmost tag of the web.xml file and is required. It has attributes for the Web application version and the XML schema definition location. The <web-app> tag contains two child tags:

  • The <servlet> tag contains child tags that define the servlet name, Java class, and whether the servlet should be loaded when the server starts up.

  • The <servlet-mapping> tag contains child tags that map a servlet name to a URL pattern.

The Select XML Template screen allows you to choose an XML template.

Figure 6.32. The Select XML Template screen allows you to choose an XML template.

The entire web.xml file for the HelloWorld application is shown in the listing below. Add this code to the web.xml file in your project and then save the file:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4"
 xmlns="http://java.sun.com/xml/ns/j2ee"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
 http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" >
 <servlet>
 <servlet-name>spring-dispatcher</servlet-name>
 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
 <load-on-startup>1</load-on-startup>
 </servlet>

 <servlet-mapping>
 <servlet-name>spring-dispatcher</servlet-name>
 <url-pattern>*.htm</url-pattern>
 </servlet-mapping>
</web-app>

One servlet is being defined in the <servlet> tag, and that servlet is being mapped to a single URL pattern in the <servlet-mapping> tag. The servlet is named spring-dispatcher and is a Spring DispatcherServlet. The servlet is mapped to the URL pattern *.htm. This pattern matches any incoming server request that ends in .htm. Wildcard characters such as * are allowed in mappings, and you can make a mapping as general or as specific as necessary for your application. For the HelloWorld application, all requests ending in .htm go through the DispatcherServlet. It's possible to simply use * for the URL pattern. However, mapping specific suffixes to specific servlets makes adding more servlets easier.

Now that configuration of the DispatcherServlet in web.xml is complete, you need a Spring beans configuration file to tell the DispatcherServlet which requests to map to your controller. Follow the same steps you just used to create web.xml to create another XML file in the webWEB-INF directory. Name the file spring-dispatcher-servlet.xml. This file derives its name from the value of the <servlet-name> tag for the DispatcherServlet in web.xml, followed by –servlet.xml.

The XML schema definition for the Spring beans configuration file can be found at www.springframework.org/schema/beans/spring-beans-2.5.xsd. As with web.xml, there are too many tags and attributes to fully cover here. For the HelloWorld application, only the following basic structure is required:

<beans>
     <bean></bean>
</beans>

The <beans> tag is the topmost tag of the spring-dispatcher-servlet.xml file and is required. It has attributes for the XML schema definition location. The <beans> tag contains one <bean> tag for each controller to be mapped to a URL. The name attribute maps to the URL the controller should handle, and the class attribute maps to the controller Java class.

The entire spring-dispatcher-servlet.xml file for the HelloWorld application is shown in the following listing. Add this code to the spring-dispatcher-servlet.xml file in your project and then save the file:

<?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-2.5.xsd">
     <bean name="/hello-world.htm"
     class="com.wiley.jfib.ch06.helloworld.service.HelloWorldService"/>
</beans>

In this file, the HelloWorldService class is mapped to the URL /hello-world.htm by using the name attribute. When a request comes into the server for /hello-world.htm, it's first passed to the DispatcherServlet, as it matches the *.htm pattern mapped to that servlet. The DispatcherServlet then looks up which controller should handle the specific request by using the information in spring-dispatcher-servlet.xml. Because /hello-world.htm is mapped to the HelloWorldService controller, the request is handed off to that controller, which packages the requested data into the model and then sends it off to be displayed in the view.

All the application code and configuration is now complete. The last step is to create an Ant build script to compile, package, and deploy the application. After that, the application is ready to run under JBoss.

Writing the Ant build script

Although it's possible to compile, package, and deploy your Web application manually by using tools included with the JDK, such an approach doesn't provide an easily adaptable and maintainable build strategy. If more library JAR files are added to your application's build path or the Web application becomes part of a larger Java enterprise application that needs to be deployed to many different application servers, keeping up with long compilation commands, multiple batch files, and deployment paths becomes an error-prone process. Fortunately, thanks to Apache Ant, it's not necessary to manually build your application.

Ant uses an XML build file that contains one or more projects, each of which in turn contains one or more targets. An Ant target is a grouping of related tasks, which are individual units of work in an Ant target. For example, many Ant build files contain a target named build. The build target might contain tasks that create output directories and compile Java code.

Projects in an Ant build file are groupings of targets for a particular application. In addition to the targets for building and deploying the application, projects can contain properties that can be substituted into targets and tasks by using variables. Properties can also be defined in a separate properties file that can be included in the build file. This makes it easier to change the value of a property if needed, as you need to change the value in only one place rather than throughout the build file. Projects can also contain path resources that group sets of files under a single ID, which can then be referenced by other parts of the build file.

The Ant build file for the HelloWorld application contains a couple of properties, a path resource, and two targets. One of the properties is a reference to an external properties file, which you create now. The properties file simply contains a set of name-value pairs.

To create the build.properties file, follow these steps:

  1. Right-click the jfib-ch06-p01 project in the Project Explorer view and then choose New

    Writing the Ant build script
    File from the popup menu. The New File dialog box opens.

  2. Type helloworld-build.properties in the File name text field and then click Finish. The New File dialog box closes, and the helloworld-build.properties file opens in the editor.

The code listing for the helloworld-build.properties file is as follows:

# Ant build properties for helloworld
src.dir=src
web.dir=web
build.dir=${web.dir}/WEB-INF/classes

name=helloworld

appserver.home=${env.JBOSS_HOME}/server/default
appserver.lib=${appserver.home}/lib
deploy.path=${appserver.home}/deploy

The first three properties are related to the compiling of the Java code. The src.dir property tells the build script where the source code for the application can be found. The web.dir property tells the build script where the Web code and configuration files can be found. Finally, the build.dir property tells the build scripts where to output the compiled Java classes. This property makes use of the previously defined web.dir property by using the ${} variable substitution notation.

The final four properties are related to packaging and deploying the compiled application to the JBoss server. The name property defines the name of the application; the build script packages the application into a WAR file called ${name}.war. The appserver.home property tells the build script where to locate the base of the JBoss installation. There are two things to notice about this property. First, notice the ${env.JBOSS_HOME} variable substitution used here. It's possible to set a build file property that allows you to access environment variables on your computer. This property accesses the value of the JBOSS_HOME environment variable you set when you configured JBoss. Second, notice that you're setting appserver.home to the default server instance under the JBoss installation.

It's possible to have multiple server configurations configured under JBoss, and applications need to be deployed to one or more of these specific configurations rather than just deployed to JBoss in general. The appserver.lib property uses the appserver.home property to tell the build script where the JBoss server libraries are. Remember that the application needs JBoss's servlet-api.jar file to build. Finally, the deploy.path property tells the build script where to place the built and packaged application. The JBoss server configuration deploys any applications in its deploy directory when it starts up.

Now that the properties file is in place, the Ant build file can be created. By convention, Ant build files are always named build.xml.

To create the build.xml file, follow these steps:

  1. Right-click the jfib-ch06-p01 project in the Project Explorer view and then choose New

    Writing the Ant build script
    Other from the popup menu. The Select a wizard dialog box opens.

  2. Click the arrow next to XML to expand it, click XML in the submenu, and then click Next. The New XML File wizard opens.

  3. Type build.xml in the File name text field and then click Next. The Create XML File From screen opens.

  4. Click the Create XML file from an XML template radio button and then click Next. The Select XML Template screen opens.

  5. Click the xml declaration template in the list and then click Finish. The New XML File wizard closes, and the newly created build.xml file opens in the editor.

The code listing for the build.xml file is as follows:

<?xml version="1.0" encoding="UTF-8"?>
<project name="helloworld" basedir="." default="usage">
     <property environment="env"/>
     <property file="helloworld-build.properties"/>

     <path id="cp">
          <fileset dir="${web.dir}/WEB-INF/lib">
               <include name="*.jar"/>
          </fileset>
          <fileset dir="${appserver.lib}">
               <include name="servlet-api.jar"/>
          </fileset>
          <pathelement path="${build.dir}"/>
     </path>

     <target name="usage">
          <echo message=""/>
          <echo message="${name} build file"/>
          <echo message="-----------------------------------"/>
          <echo message=""/>
          <echo message="Available targets are:"/>
          <echo message=""/>
          <echo message="build --> Build the application"/>
          <echo message="deploy      --> Deploy application as a WAR file"/>
          <echo message=""/>
     </target>

     <target name="build" description="Compile main source tree java files">
          <mkdir dir="${build.dir}"/>
          <javac destdir="${build.dir}" source="1.5" target="1.5"
          debug="true" deprecation="false" optimize="false"
          failonerror="true">
               <src path="${src.dir}"/>
               <classpath refid="cp"/>
          </javac>
     </target>

     <target name="deploy" depends="build" description="Deploy application as a WAR file">
          <war destfile="${name}.war"
                webxml="${web.dir}/WEB-INF/web.xml">
               <fileset dir="${web.dir}">
                      <include name="**/*.*"/>
               </fileset>
          </war>
          <copy todir="${deploy.path}" preservelastmodified="true">
               <fileset dir=".">
                      <include name="*.war"/>
               </fileset>
        </copy>
  </target>
</project>

This listing looks long, but it's really fairly simple when broken down into its basic parts:

  • The first <property> tag sets the system environment to the variable env. This property allows you to use variables, such as ${env.JBOSS_HOME}, used in the helloworld-build.properties file.

  • The second <property> tag loads the properties located in the helloworld-build.properties file. It's important that this property is listed after the environment property, as the environment property is used in the helloworld-build.properties file.

  • The <path> tag puts together a few sets of files and assigns the list to a variable named cp. You can see from the <fileset> and <pathelement> tags inside the <path> tag that this set includes all the JAR files in the WEB-INF/lib directory, the servlet-api.jar file from the JBoss server, and the compiled class files from the HelloWorld application. This set of files is used as the classpath when compiling the application.

  • The first <target> tag defines the usage target. This is the default target, which is run if Ant is executed with no target specified. The usage target simply prints out a list of available targets in this build file to the console.

  • The second <target> tag defines the build target. This target contains two tasks. The first, the mkdir task, creates the output directory for the compiled Java classes if it doesn't already exist. The second, the javac task, invokes the Java compiler to compile the source code in the source directory by using libraries in the classpath referenced by the cp variable defined earlier in the <path> tag. The failonerror attribute of the javac task ensures that the build won't continue if there are errors in the source code.

  • The final <target> tag defines the deploy target. This target also contains two tasks. The first, the war task, packages up all the files for the Web application into a WAR file by using the name defined in the properties file. The second, the copy task, copies the WAR file into the JBoss deploy directory. The <target> tag has a depends attribute that lists build as a dependency. That means that the deploy target depends on the build target having been run. If the build target hasn't been run and code has changed in the meantime, the deploy target actually runs the build target first to make sure that the compiled code is up to date before packaging and deploying the application.

To run the Ant build script from within Eclipse, you need to add it to the Ant view in your project. To add the build script to the Ant view, follow these steps:

  1. Choose Window

    Writing the Ant build script
    Show View
    Writing the Ant build script
    Other
    . The Show View dialog box, as shown in Figure 6.33, opens.

    Choose the Ant view in the Show View dialog box.

    Figure 6.33. Choose the Ant view in the Show View dialog box.

  2. Click the arrow next to Ant to expand it, click Ant in the expanded menu, and then click OK. The Ant view, as shown in Figure 6.34, opens.

    The Ant view is where the build file for your application appears, allowing you to run build targets from within Eclipse.

    Figure 6.34. The Ant view is where the build file for your application appears, allowing you to run build targets from within Eclipse.

  3. Click the Add Buildfiles button in the Ant view. The Add Buildfiles button is the leftmost button in the Ant view, depicting an ant next to a plus sign. The Buildfile Selection dialog box opens.

  4. Click the arrow next to the project name to expand it, click the build.xml file, as shown in Figure 6.35, and then click OK. The Buildfile Selection dialog box closes, and the build file is added to the Ant view, as shown in Figure 6.36.

Choose the build.xml file for your project in the Buildfile Selection dialog box to add it to the Ant view.

Figure 6.35. Choose the build.xml file for your project in the Buildfile Selection dialog box to add it to the Ant view.

Click the arrow next to the build file entry in the Ant view to expand it and see the available build targets. The three targets you saw in the build.xml file appear here. Double-click the usage target to run it. Eclipse switches to the Console view, and the messages defined in the <echo> tags in the usage target print out in the console, as shown in Figure 6.37. Click the Ant tab to switch back to the Ant view.

Now double-click the deploy target to run it. Study the output of the console, as shown in Figure 6.38, and notice that because the build target has never been run, the deploy target launches the build target first. The ability to chain dependencies like this in your build files is a very powerful advantage over building manually. Using dependencies like this, you can ensure that you never deploy outdated code to your application server.

The build file appears in the Ant view with the name of the project as defined in build.xml.

Figure 6.36. The build file appears in the Ant view with the name of the project as defined in build.xml.

The console output from running the usage target of the Ant build

Figure 6.37. The console output from running the usage target of the Ant build

The console output from the deploy target demonstrates its dependency on the build target. Because the build target had not yet been run, the deploy target launched it before proceeding with its own tasks.

Figure 6.38. The console output from the deploy target demonstrates its dependency on the build target. Because the build target had not yet been run, the deploy target launched it before proceeding with its own tasks.

Once the application has been successfully deployed, you can start up JBoss and see the application in action. To start JBoss and test your application, follow these steps:

  1. Switch to the Servers view by clicking the Servers tab.

  2. Click the Start the Server button. Eclipse switches to the Console view while JBoss starts up. Once the server startup has completed, Eclipse switches back to the Servers view and shows the state of the JBoss server as Started, as shown in Figure 6.39.

  3. Open your Web browser, typehttp://localhost:8080/helloworld/hello-world.htm in the address bar, and then press Enter. You should see the screen shown in Figure 6.40.

Once the JBoss server has started successfully, the Servers view shows its state as Started.

Figure 6.39. Once the JBoss server has started successfully, the Servers view shows its state as Started.

This screen indicates that the HelloWorld application has been successfully deployed to JBoss.

Figure 6.40. This screen indicates that the HelloWorld application has been successfully deployed to JBoss.

You may be curious about the URL. Web applications are deployed to their own application context on the server. That way, multiple applications can be run on the same server without having conflicting resource names (index.html, for example). By default, the application context URL path is the name of the application. In this case, the application is deployed as helloworld.war, so the application context name is helloworld. Therefore, it can be said that the URL points to the resource hello-world.htm within the application context helloworld on the localhost server.

If for some reason you receive an error instead of the screen in Figure 6.40, there are a couple of things you can do to check your work and see what went wrong:

  • Be sure you typed the URL correctly in the browser's address bar. Remember to include a colon between localhost and 8080 and that the URL ends in hello-world.htm, not hello-world.html.

  • Double-check that there were no compilation errors in your code by looking for red X icons in the left margin of the HelloWorldService editor. If you've misspelled any keywords, forgotten parentheses or semicolons, or made other errors, you can correct them in the editor and then rebuild and deploy the application by using Ant as described earlier. You don't need to restart JBoss; it detects that the application WAR file has been updated and redeploys it on the fly.

  • Switch to the Console view by clicking the Console tab. If the Console view isn't open, you can open it by choosing Window

    This screen indicates that the HelloWorld application has been successfully deployed to JBoss.

Enhancing the Web application

While the HelloWorld application builds, deploys, and runs, it's otherwise not very interesting. Adding the ability to accept input from the user interface is the next logical step for this application.

Open the HelloWorldService file by double-clicking it in the Project Explorer view. Replace the existing handleRequest method with the following:

/**
 *
 */
package com.wiley.jfib.ch06.helloworld.service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

/**
 * @author Chuck
 *
 */
public class HelloWorldService implements Controller {
/* (non-Javadoc)
      * @see org.springframework.web.servlet.mvc.
      Controller#handleRequest(javax.servlet.http.HttpServletRequest,
      javax.servlet.http.HttpServletResponse)
       */
      @Override
      public ModelAndView handleRequest(HttpServletRequest arg0,
                   HttpServletResponse arg1) throws Exception {
             // Receive the language parameter from the client
             String language = arg0.getParameter("lang");
             String message = "";

             // customize the message based on the language
             if(language == null)
                    message = "I don't know what language you speak!";
             else if("english".equalsIgnoreCase(language))
                    message = "Hello, World!";
             else if("spanish".equalsIgnoreCase(language))
                    message = "Hola, mundo!";
             else if("french".equalsIgnoreCase(language))
                    message = "Bonjour, monde!";
             else if("german".equalsIgnoreCase(language))
                    message = "Hallo, Welt!";
             else if("italian".equalsIgnoreCase(language))
                    message = "Ciao, mondo!";
             else
                    message = "I'm sorry. I don't speak your language.";

             // return the message for the client
             return new ModelAndView("WEB-INF/jsp/hello-world.jsp",
             "message",message);
      }

 }

The handleRequest method now attempts to retrieve a parameter named lang from the client's request. The message returned to the client is customized based on the language received, if any.

Save the file and then click the Ant tab below the editors to switch back to the Ant view. Double-click the deploy target to rebuild and redeploy the application.

If you didn't stop the JBoss server, you may notice that the Console view switches back to the JBoss server console after a few moments. JBoss is able to detect applications that have been updated and then reload them on the fly. This means you don't have to stop and restart JBoss to deploy changes to your application. If you had previously stopped JBoss, restart it by switching to the Servers view and then clicking the Start the Server button.

Open your Web browser and then type the same URL you used previously: http://localhost:8080/helloworld/hello-world.htm. Instead of the "Hello, World!" message, you see a message stating, "I don't know what language you speak!" Now change the URL by adding ?lang=spanish to the end and then press Enter. The part of the URL after the question mark is called the query string. The query string is one way of passing parameters to the server. The application now greets you in Spanish, as shown in Figure 6.41.

The application is now able to display a dynamic message based on the lang parameter of the query string.

Figure 6.41. The application is now able to display a dynamic message based on the lang parameter of the query string.

Summary

In this chapter, you wrote, built, deployed, and ran a complete Java Web application by using the Spring Framework's Web MVC module. First, you learned the basics of the Model-View-Controller architectural pattern. The model refers to the data and business logic of the application. The view is the user interface in which the model data is displayed. The controller is the service code that handles requests from the clients, gathers data from the model, and packages it up to be displayed in the view. Next, you learned about the Spring Framework and the various modules and functionality it provides. After that, you set up a Spring project in Eclipse and then configured it for writing a Spring Web MVC application. Finally, you wrote a simple Web application by using Spring Web MVC, built and deployed the application with an Ant build file, and added the ability to accept query string parameters to enhance the application.

Although the application in this chapter is rudimentary, the concepts, code, and configuration files used here are a good starting point for any Web application. Most Web applications include the same basic building blocks that make up this application and add to them or build upon them as needed. With these basics in hand, you can move on to building larger and more complex Web applications.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.159.116