3、创建ActionJSP页面

在这里我们使用Struts作为WEB框架,当然可以使用Spring MVC以及WebWork2来作为WEB层框架。

主要任务:

[1]XDoclet标签到Person类中,这样可以方便的生成PersonForm

[2]使用XDoclet来创建JSP页面的主要代码。

[3]创建Action的测试以及Action

[4]运行Action测试

[5]修改JSP页面,使其可以运行

 

我们现在通过在Person对象的代码中添加XDoclet来方便的生成PersonForm对象,以便在Struts当中使用。


* @struts.form include-all="true" extends="BaseForm"

在这里我们让PersonForm对象扩展BaseForm对象。

 

下面我们生成主要的JSP页面代码。

利用ant compile命令来编译Person类。这样就可以生成PersonForm类。

进入extras/viewgen目录下,运行命令 ant –Dform.name=PersonForm来生成主要的JSP代码。这是你可以在extras/viewgen/build目录下看到如下文件:

PersonForm.property(主要元素的Label)

PersonForm.jsp(表单页面)

PersonFormList.jsp(列表页面)

Copy PersonForm.propertyweb/WEB-INF/classes/ApplicationResources_zh.property文件中。

Copy PersonForm.jspPersonFormList.jspweb/pages/目录下。

 

创建Action测试类:

我们利用StrutsTestCase可以创建Action的测试类。


package org.appfuse.webapp.action;

import org.appfuse.Constants;
import org.appfuse.webapp.form.PersonForm;

public class PersonActionTest extends BaseStrutsTestCase {
    
    public PersonActionTest(String name) {
        super(name);
    }

    public void testEdit() throws Exception {
        setRequestPathInfo("/editPerson");
        addRequestParameter("method""Edit");
        addRequestParameter("id""1");
        actionPerform();

        verifyForward("edit");
        assertTrue(request.getAttribute(Constants.PERSON_KEY) != null);
        verifyNoActionErrors();
    }

    public void testSave() throws Exception {
        setRequestPathInfo("/editPerson");
        addRequestParameter("method""Edit");
        addRequestParameter("id""1");

        actionPerform();

        PersonForm personForm =
            (PersonForm) request.getAttribute(Constants.PERSON_KEY);
        assertTrue(personForm != null);
        
        setRequestPathInfo("/savePerson");
        addRequestParameter("method""Save");

        // update the form from the edit and add it back to the request
        personForm.setLastName("Feltz");
        request.setAttribute(Constants.PERSON_KEY, personForm);

        actionPerform();

        verifyForward("edit");
        verifyNoActionErrors();
    }

    public void testRemove() throws Exception {
        setRequestPathInfo("/editPerson");
        addRequestParameter("method""Delete");
        addRequestParameter("id""2");
        actionPerform();

        verifyForward("mainMenu");
        verifyNoActionErrors();
    }
}

我们添加PERSON_KEYsrc/dao/**/Constants.java中,这个常量用来匹配formStruts配置文件中的名称。


    /**
     * The request scope attribute that holds the person form.
     */
    public static final String PERSON_KEY = "personForm";

接下来,我们在src/web/**/action目录中创建Action


package org.appfuse.webapp.action;

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

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

import org.appfuse.model.Person;
import org.appfuse.service.PersonManager;
import org.appfuse.webapp.form.PersonForm;

/**
 * @struts.action name="personForm" path="/editPerson" scope="request"
 *  validate="false" parameter="method" input="mainMenu"
 */
public final class PersonAction extends BaseAction {
    
    public ActionForward cancel(ActionMapping mapping, ActionForm form,
                                HttpServletRequest request,
                                HttpServletResponse response)
    throws Exception {
        return mapping.findForward("mainMenu");
    }

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

        ActionMessages messages = new ActionMessages();
        PersonForm personForm = (PersonForm) form;

        // Exceptions are caught by ActionExceptionHandler
        PersonManager mgr = (PersonManager) getBean("personManager");
        mgr.removePerson(personForm.getId());

        messages.add(ActionMessages.GLOBAL_MESSAGE,
                     new ActionMessage("person.deleted",
                                       personForm.getFirstName() + ' ' +
                                       personForm.getLastName()));

        // save messages in session, so they'll survive the redirect
        saveMessages(request.getSession(), messages);

        return mapping.findForward("mainMenu");
    }

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

        PersonForm personForm = (PersonForm) form;

        // if an id is passed in, look up the user - otherwise
        // don't do anything - user is doing an add
        if (personForm.getId() != null) {
            PersonManager mgr = (PersonManager) getBean("personManager");
            Person person = mgr.getPerson(personForm.getId());
            personForm = (PersonForm) convert(person);
            updateFormBean(mapping, request, personForm);
        }

        return mapping.findForward("edit");
    }

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

        // Extract attributes and parameters we will need
        ActionMessages messages = new ActionMessages();
        PersonForm personForm = (PersonForm) form;
        boolean isNew = ("".equals(personForm.getId()));

        if (log.isDebugEnabled()) {
            log.debug("saving person: " + personForm);
        }

        PersonManager mgr = (PersonManager) getBean("personManager");
        Person person = (Person) convert(personForm);
        mgr.savePerson(person);

        // add success messages
        if (isNew) {
            messages.add(ActionMessages.GLOBAL_MESSAGE,
                         new ActionMessage("person.added",
                                           personForm.getFirstName() + " " +
                                           personForm.getLastName()));

            // save messages in session to survive a redirect
            saveMessages(request.getSession(), messages);

            return mapping.findForward("mainMenu");
        else {
            messages.add(ActionMessages.GLOBAL_MESSAGE,
                         new ActionMessage("person.updated",
                                           personForm.getFirstName() + " " +
                                           personForm.getLastName()));
            saveMessages(request, messages);

            return mapping.findForward("edit");
        }
    }
}

在这里有时需要进行PersonPersonForm的转换,你可以使用ConvertUtil.convert() 或者 BeanUtils.copyProperties

现在我们在Action文件的头部加入XDoclet标签,这样可以自动的生成Struts配置文件。


/**
 * @struts.action name="personForm" path="/editPerson" scope="request"
 *  validate="false" parameter="method" input="mainMenu"
 
 * @struts.action name="personForm" path="/savePerson" scope="request"
 *  validate="true" parameter="method" input="edit"
 
 * @struts.action-forward name="edit" path="/WEB-INF/pages/personForm.jsp"
 */
public final class PersonAction extends BaseAction {

在程序中可能还会需要在页面上显示其他的文字信息,那么这些信息应该加入到资源文件当中,例如:

person.added=Information for <strong>{0}</strong> has been added successfully.
person.deleted=Information for <strong>{0}</strong> has been deleted successfully.
person.updated=Information for <strong>{0}</strong> has been updated successfully.

 

现在可以运行Action的测试了。

 

如果Action测试运行成功,那么你可以修改JSP页面,使它符合你对界面的要求。

相关文章: