Java Bo&Yang
          java的交流從這里開始
          posts - 8,comments - 6,trackbacks - 0

          今天得到一本書名為《Struts Kick Start》的書,于是開始學習Struts,并學習了第一個范例。
          Hello.jsp

          <%@ page contentType="text/html; charset=GBK" %>
          <%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
          <%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
          <%@ taglib uri="/WEB-INF/struts-logic.tld" prefix="logic" %>
          <html:html locale="true">
            
          <head>
              
          <title><bean:message key="hello.jsp.title"/></title>
              
          <html:base/>
            
          </head>
            
          <body bgcolor="white"><p>
              
          <h2><bean:message key="hello.jsp.page.heading"/></h2><p>
              
          <html:errors/><p>
              
          <logic:present name="com.javaby.hello" scope="request">
                
          <h2>
                  Hello 
          <bean:write name="com.javaby.hello" property="person" />!<p>
                
          </h2>
              
          </logic:present>

              
          <html:form action="/HelloWorld.do?action=gotName" focus="person">
                
          <bean:message key="hello.jsp.prompt.person"/>
                
          <html:text property="person" size="16" maxlength="16"/><br>
                
          <html:submit property="submit" value="Submit"/>
                
          <html:reset/>
              
          </html:form><br>

              
          <html:img page="/struts-power.gif" alt="Powered by Struts"/>

            
          </body>
          </html:html>
          這是一個簡單的輸入一個名稱,返回hello+<名稱>的例子,頁面中很多Struts的自定義標記。
          <bean:message key="hello.jsp.prompt.person"/>在表單中打印提示信息,key定義在property文件中。
          而開始的幾行
          <%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
          <%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
          <%@ taglib uri="/WEB-INF/struts-logic.tld" prefix="logic" %>
          則是定義jsp頁面使用的標記庫。
          Application.properties文件
             ; Application Resources for the "Hello" Sample application
          ;
          ; Application Resources that are specific to the Hello.jsp file

          hello.jsp.title 
          = Hello - A first Struts program
          hello.jsp.page.heading 
          = Hello World! A first Struts application
          hello.jsp.prompt.person 
          = Please enter a name to say hello to :

          ; Validation and error messages 
          for HelloForm.java and HelloAction.java

          com.javaby.hello.dont.talk.to.atilla 
          = I told you not to talk to Atilla!!!
          com.javaby.hello.no.person.error 
          = Please enter a <i>PERSON</i> to say hello to!
          Struts表單中的數據被填裝到一個被稱為FormBean的java bean中,HelloForm.java
          package com.javaby.hello;

          import javax.servlet.http.HttpServletRequest;

          import org.apache.struts.action.ActionError;
          import org.apache.struts.action.ActionErrors;
          import org.apache.struts.action.ActionForm;
          import org.apache.struts.action.ActionMapping;

          /**
           * Form bean for Chapter 03 sample application, "Hello World!"
           *
           * @author Kevin Bedell
           
          */

          public final class HelloForm extends ActionForm {

              
          // --------------------------------------------------- Instance Variables

              
          /**
               * The person we want to say "Hello!" to
               
          */

              
          private String person = null;


              
          // ----------------------------------------------------------- Properties

              
          /**
               * Return the person to say "Hello!" to
               *
               * @return String person the person to say "Hello!" to
               
          */

              
          public String getPerson() {

                  
          return (this.person);

              }


              
          /**
               * Set the person.
               *
               * @param person The person to say "Hello!" to
               
          */

              
          public void setPerson(String person) {

                  
          this.person = person;

              }


              
          // --------------------------------------------------------- Public Methods

              
          /**
               * Reset all properties to their default values.
               *
               * @param mapping The mapping used to select this instance
               * @param request The servlet request we are processing
               
          */

              
          public void reset(ActionMapping mapping, HttpServletRequest request) {
                  
          this.person = null;
              }


              
          /**
               * Validate the properties posted in this request. If validation errors are
               * found, return an <code>ActionErrors</code> object containing the errors.
               * If no validation errors occur, return <code>null</code> or an empty
               * <code>ActionErrors</code> object.
               *
               * @param mapping The current mapping (from struts-config.xml)
               * @param request The servlet request object
               
          */

              
          public ActionErrors validate(ActionMapping mapping,
                                           HttpServletRequest request) 
          {

                  ActionErrors errors 
          = new ActionErrors();

                  
          if ((person == null|| (person.length() < 1))
                      errors.add(
          "person"new ActionError("com.javaby.hello.no.person.error"));

                  
          return errors;

              }


          }

          Action類HelloAction.java
          package com.javaby.hello;

          import javax.servlet.RequestDispatcher;
          import javax.servlet.ServletException;
          import javax.servlet.http.HttpServletRequest;
          import javax.servlet.http.HttpSession;
          import javax.servlet.http.HttpServletResponse;

          import org.apache.struts.action.Action;
          import org.apache.struts.action.ActionError;
          import org.apache.struts.action.ActionErrors;
          import org.apache.struts.action.ActionForm;
          import org.apache.struts.action.ActionForward;
          import org.apache.struts.action.ActionMapping;

          import org.apache.struts.util.MessageResources;

          import org.apache.commons.beanutils.PropertyUtils;


          /**
           * The <strong>Action</strong> class for our "Hello" application.<p>
           * This is the "Controller" class in the Struts MVC architecture.
           *
           * @author Kevin Bedell
           
          */


          public final class HelloAction extends Action {

              
          /**
               * Process the specified HTTP request, and create the corresponding HTTP
               * response (or forward to another web component that will create it).
               * Return an <code>ActionForward</code> instance describing where and how
               * control should be forwarded, or <code>null</code> if the response has
               * already been completed.
               *
               * @param mapping The ActionMapping used to select this instance
               * @param actionForm The optional ActionForm bean for this request (if any)
               * @param request The HTTP request we are processing
               * @param response The HTTP response we are creating
               *
               * @exception Exception if business logic throws an exception
               
          */

              
          public ActionForward execute(ActionMapping mapping,
                                                                   ActionForm form,
                                           HttpServletRequest request,
                                           HttpServletResponse response)
              throws Exception 
          {

                  
          /*
                   * This Action is executed either by calling
                   *
                   * /hello.do  - when loading the initial page
                   * - or -
                   * /hello.do?action=getName - whenever we post the form
                   *
                   
          */


                  
          // If this is first time, go straight to page
                  String action = request.getParameter("action");
                        
          if (action == null{
                            
          return (mapping.findForward("SayHello"));
                  }


                  
          // These "messages" come from the ApplicationResources.properties file
                        MessageResources messages = getResources(request);

                        
          /*
                   * Validate the request parameters specified by the user
                   * Note: Basic field validation done in HelloForm.java
                   *       Business logic validation done in HelloAction.java
                   
          */

                        ActionErrors errors 
          = new ActionErrors();
                  String person 
          = (String)
                      PropertyUtils.getSimpleProperty(form, 
          "person");

                  String badPerson 
          = "Atilla the Hun";

                  
          if (person.equals(badPerson)) {
                      errors.add(
          "person",
                         
          new ActionError("com.javaby.hello.dont.talk.to.atilla", badPerson ));
                            saveErrors(request, errors);
                        
          return (new ActionForward(mapping.getInput()));
                  }


                  
          /*
                   * Having received and validated the data submitted from the View,
                   * we now update the model
                   
          */

                  HelloModel hm 
          = new HelloModel();
                  hm.setPerson(person);
                  hm.saveToPersistentStore();

                  
          /*
                   * If there was a choice of View components that depended on the model
                   * (oe some other) status, we'd make the decisoin here as to which
                   * to display. In this case, there is only one View component.
                   *
                   * We pass data to the View components by setting them as attributes
                   * in the page, request, session or servlet context. In this case, the
                   * most appropriate scoping is the "request" context since the data
                   * will not be nedded after the View is generated.
                   *
                   * Constants.HELLO_KEY provides a key accessible by both the
                   * Controller component (i.e. this class) and the View component
                   * (i.e. the jsp file we forward to).
                   
          */


                  request.setAttribute( Constants.HELLO_KEY, hm);

                  
          // Remove the Form Bean - don't need to carry values forward
                  request.removeAttribute(mapping.getAttribute());

                        
          // Forward control to the specified success URI
                        return (mapping.findForward("SayHello"));

              }

          }

          Action類的主要方法是execute()。而值得一提的是與Model組件的交互,在HelloModel hm=new HelloModel();一段中Controller建立了一個新的Model組件,為其設定了數值,同時調用一個方法將數據保存到永久性存儲中。另外,request.setAttribute(Constants.HELLO_KEY,hm);完成了將Model實例設置為request的一個屬性,并傳遞到View組件中,request.removeAttribute(mapping.getAttribute());則在request中刪除表單bean。
          HelloModel.java
          package com.javaby.hello;

          /**
           * <p>This is a Model object which simply contains the name of the perons we
           * want to say "Hello!" to.<p>
           *
           * In a more advanced application, this Model component might update
           * a persistent store with the person name, use it in an argument in a web
           * service call, or send it to a remote system for processing.
           *
           * @author Kevin Bedell
           
          */

          public class HelloModel {

              
          // --------------------------------------------------- Instance Variables

              
          /**
               * The new person we want to say "Hello!" to
               
          */

              
          private String _person = null;

              
          // ----------------------------------------------------------- Properties

              
          /**
               * Return the new person we want to say "Hello!" to
               *
               * @return String person the person to say "Hello!" to
               
          */

              
          public String getPerson() {
                  
          return this._person;
              }


              
          /**
               * Set the new person we want to say "Hello!" to
               *
               * @param person The new person we want to say "Hello!" to
               
          */

              
          public void setPerson(String person) {

                  
          this._person = person;

              }


              
          // --------------------------------------------------------- Public Methods

              
          /**
               * This is a stub method that would be used for the Model to save
               * the information submitted to a persistent store. In this sample
               * application it is not used.
               
          */

              
          public void saveToPersistentStore() {

                  
          /*
                   * This is a stub method that might be used to save the person's
                   * name to a persistent store if this were a real application.
                   *
                   * The actual business operations that would exist within a Model
                   * component would be dependedn upon the rquirements of the application.
                   
          */

              }




          }

          通過使用屬性向View傳遞數據Constants.java
          package com.javaby.hello;

          /**
           * Constants to be used in the Hello World! Example
           * Chapter 03 of "Struts Kickstart"
           *
           * @author Kevin Bedell
           
          */


          public final class Constants {

             
          /**
               * The application scope attribute used for passing a HelloModel
               * bean from the Action class to the View component
               
          */

              
          public static final String HELLO_KEY = "com.javaby.hello";

          }

          完成代碼編寫之后,還要整合組件,struts-config.xml
          <?xml version="1.0" encoding="UTF-8"?>
          <!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.1//EN" "http://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd">
          <struts-config>
            
          <form-beans>
              
          <form-bean name="HelloForm" type="com.javaby.hello.HelloForm"/>
            
          </form-beans>
            
          <action-mappings>
              
          <action name="HelloForm" path="/HelloWorld" type="com.javaby.hello.HelloAction" scope="request" validate="true" input="/Hello.jsp">
                
          <forward name="SayHello" path="/Hello.jsp"/>
              
          </action>
            
          </action-mappings>
            
          <message-resources parameter="com.javaby.hello.Application"/>
          </struts-config>
          這里如果使用JBuilder編寫struts-config.xml文件要方便很多,完全圖形化操作。這個就是完整的一個很簡單的Struts應用。
          posted on 2005-07-19 15:44 Java BY 閱讀(382) 評論(0)  編輯  收藏 所屬分類: Bo java學習筆記
          主站蜘蛛池模板: 育儿| 买车| 宝坻区| 玉山县| 根河市| 门头沟区| 莱州市| 西宁市| 屏南县| 茂名市| 泰安市| 视频| 绥棱县| 会昌县| 兰考县| 东阳市| 宜黄县| 锡林浩特市| 长宁县| 贵定县| 仁怀市| 祁门县| 元氏县| 马尔康县| 黔西县| 隆回县| 鄂伦春自治旗| 同仁县| 齐齐哈尔市| 密山市| 东安县| 页游| 广水市| 大同县| 齐河县| 伽师县| 灵宝市| 南乐县| 武宣县| 城口县| 锦屏县|