Raible's Wiki

Raible Designs
Wiki Home
News
Recent Changes

AppFuse

Homepage
  - Korean
  - Chinese
  - Italian
  - Japanese

QuickStart Guide
  - Chinese
  - French
  - German
  - Italian
  - Korean
  - Portuguese
  - Spanish
  - Japanese

User Guide
  - Korean
  - Chinese

Tutorials
  - Chinese
  - German
  - Italian
  - Korean
  - Portuguese
  - Spanish

FAQ
  - Korean

Latest Downloads

Other Applications

Struts Resume
Security Example
Struts Menu

Set your name in
UserPreferences


Referenced by
Articles
Articles_cn
Articles_pt
Articles_zh
CreateActions
CreateActions_pt
CreateActions_zh
SpringControllerUnit...
SpringControllers_ko
ValidationAndListSpr...
...and 1 more




JSPWiki v2.2.33

[RSS]


Hide Menu

SpringControllers


This is version 4. It is not the current version, and thus it cannot be edited.
[Back to current version]   [Restore this version]


Part III: Creating Controllers and JSPs - A HowTo for creating Spring Controllers and JSPs in the AppFuse architecture.
This tutorial depends on Part II: Creating new Managers.

About this Tutorial

This tutorial will show you how to create a Spring Controller and JSP. It'll also demonstrate writing a JUnit Test to test the Controller. The Controller we create will talk to the PersonManager we created in the Creating Managers tutorial. This tutorial will simplify everything - we will not actually be rendering any data or making the UI look pretty. The next tutorial will show you how to integrate your new JSPs into your webapp.
I will tell you how I do stuff in the Real World in text like this.

Let's get started by creating a new Controller and JSP in AppFuse's architecture. If you haven't installed the Spring MVC module at this point, do so by running ant install-springmvc.

Table of Contents

  • [1] Create a skeleton JSP using XDoclet
  • [2] Create a new ControllerTest to test our Controller
  • [3] Create a new Controller
  • [4] Display the JSP in a browser and run the ControllerTest

Create a skeleton JSP using XDoclet [#2]

In this step, we'll generate a skeleton or our JSP for displaying information from the Person object. I say skeleton because it'll just be the <form> itself. It will contain table rows and Struts' <html:text> tags for each property in Person.java. The tool that we use to do this was written by Erik Hatcher. It's basically just a single class (FormTagsHandler.java) and a couple of XDoclet templates (FormKeys.xdt and Form_jsp.xdt). All these files are located in extras/viewgen.

Here are the simple steps to generating the JSP and a properties file containing the labels for the form elements:

  • From the command-line, navigate to "extras/viewgen"
  • Execute ant -Dform.name=Person to generate three files in extras/viewgen/build:
    • Person.properties (labels for your form elements)
    • personForm.jsp (skeleton JSP file for viewing a single Person)
    • personList.jsp (skeleton JSP file for viewing a list of People)
  • Copy the contents of Person.properties into web/WEB-INF/classes/ApplicationResources.properties. Here is an example of what you might add to ApplicationResources.properties:
# -- person form --
person.firstName=First Name
person.id=Id
person.lastName=Last Name
  • Copy personForm.jsp to web/personForm.jsp. Copy PersonFormList.jsp to web/personList.jsp. Notice that each of the new filename's first character is lowercase.

We copy the JSPs to the web folder instead of web/pages because the pages directory ends up in WEB-INF/pages when the application is packaged into a WAR file. This is a recommended practice when building secure web applications.

The container provides security for all files below WEB-INF. This applies to client requests, but not to forwards from the DispatchServlet. Placing all JSPs below WEB-INF ensures they are only accessed through Controllers, and not directly by the client or each other. This allows security to be moved up into the Controller, where it can be handled more efficiently, and out of the base presentation layer.

The web application security for AppFuse specifies that all *.html url-patterns should be protected. This guarantees 1) all Controllers are protected, and 2) you must go through a Controller to get to a JSP (or at least the ones in pages).

All this is to say that putting the personForm.jsp in the web folder will allow us to view it without making a Tile for it. We'll get to that in the next tutorial.

At this point, you won't be able to view the JSP in your browser because the validation code (at the bottom of the page) requires that the JSP is invoked from the DispatchServlet. Therefore, we need to create a Controller for this JSP, and we should practice TDD and write our Test before we write our Controller.

Create a new ControllerTest to test our Controller [#3]

To create a JUnit Test for our Controller, start by creating a PersonControllerTest.java file in the test/web/**/action directory.
As usual, copy → save as an existing ControllerTest (i.e. UserControllerTest). Replace [Uu]ser with [P]erson.


package org.appfuse.webapp.action;

public class PersonControllerTest extends BaseControllerTestCase {
    private static Log log = LogFactory.getLog({personFormControllerTest.class);
    private PersonFormController c;
    private MockHttpServletRequest request;
    private ModelAndView mv;

    protected void setUp() {
        // needed to initialize a user
        super.setUp();
        c = (UserFormControllerctx.getBean("personFormController");
    }

    protected void tearDown() {
        c = null;
    }

    public void testEdit() throws Exception {
        log.debug("testing edit...");
        request = newGet("/editUser.html");
        request.addParameter("username""tomcat");

        mv = c.handleRequest(request, new MockHttpServletResponse());

        assertEquals("userForm", mv.getViewName());
    }
}

Nothing will compile at this point (ant compile) since we need to create the PersonFormController that we're referring to in this test.

Create a new Controller [#4]

Now we have to create a Controller to talk to our Manager and retrieve/save our data. In src/web/**/action, create a PersonFormController.java file with the following contents:


package org.appfuse.webapp.action;

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

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;


/**
 * Implementation of <strong>Action</strong> that interacts with the {@link
 * PersonForm} and retrieves values.  It interacts with the {@link
 * PersonManager} to retrieve/persist values to the database.
 *
 * @struts.action name="personForm" path="/editPerson" scope="request"
 *  validate="false" parameter="action" input="mainMenu"
 */
public final class PersonAction extends BaseAction {
    private static Log log = LogFactory.getLog(PersonAction.class);

    public ActionForward execute(ActionMapping mapping, ActionForm form,
                                 HttpServletRequest request,
                                 HttpServletResponse response)
    throws Exception {
        if (log.isDebugEnabled()) {
            log.debug("Entering 'execute' method");
        }

        // return nothing (yet)
        return null;
    }
}

We're not putting much in PersonAction at this point because we just want to 1) render the JSP and 2) verify our Test runs. The XDoclet tags (beginning with @struts.action) will generate the following XML in the build/appfuse/WEB-INF/struts-config.xml file (when you run ant webdoclet):


<action path="/editPerson" type="org.appfuse.webapp.action.PersonAction"
    name="personForm" scope="request"  input="mainMenu"
    parameter="action" unknown="false" validate="false">
</action>

I formatted the XML above the the purposes of the tutorial. No content has changed.

Now we need to change the "action" attribute in the <personForm.jsp> to be action="editPerson".


<html:form action="editPerson" method="post" styleId="personForm"
  focus="" onsubmit="return validatePersonForm(this)">

Everything is almost done for this tutorial, let's get to running our tests!

Display the JSP in a browser and run the ActionTest [#5]

To test the JSP visually in your browser, save everything, run ant deploy, start Tomcat, and navigate to http://localhost:8080/appfuse/personForm.jsp. You should see something similar to the following image in your browser:

personForm-plain.png
There is also a deploy-web target in build.xml that will allow you to just deploy the files in the web directory. Nothing gets compiled or generated when you use this target.

Now, if you stop Tomcat and run ant test-cactus -Dtestcase=PersonAction, that should work too!

BUILD SUCCESSFUL
Total time: 51 seconds
Look in your console's log for PersonAction.execute(33) | Entering 'execute' method. This is the log.debug statement we put in our execute method. You should also be able to view personForm.jsp (make sure Tomcat is running and you've logged into AppFuse) and click the "Save" button to see the same debug message.

Next Up: Part IV: Configuring Tiles and Action CRUD methods - Integrating personForm.jsp with Tiles, replacing execute with different CRUD methods (add, edit, delete), customizing the JSP so it looks good and finally - writing a WebTest to test the JSPs functionality.



Go to top   More info...   Attach file...
This particular version was published on 06-Nov-2006 13:52:37 MST by MattRaible.