strtus 简单例子

来源:互联网 发布:债券销售岗 知乎 编辑:程序博客网 时间:2024/06/07 02:28

配置

strtus包

xml

strtus_config.xml

model

aciotn

view

 

1、

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE web-app
  PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"
  "http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">

<web-app>
  <display-name>HelloApp Struts Application</display-name>
 
  <!-- Standard Action Servlet Configuration  -->
  <servlet>
    <servlet-name>action</servlet-name>
    <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
    <init-param>
      <param-name>config</param-name>
      <param-value>/WEB-INF/struts-config.xml</param-value>
    </init-param>
     <load-on-startup>2</load-on-startup>
  </servlet>

  <!-- Standard Action Servlet Mapping -->
  <servlet-mapping>
    <servlet-name>action</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>
   
 <!-- The Usual Welcome File List -->
  <welcome-file-list>
    <welcome-file>hello.jsp</welcome-file>
  </welcome-file-list>

  <!-- Struts Tag Library Descriptors -->
  <taglib>
    <taglib-uri>/WEB-INF/struts-bean.tld</taglib-uri>
    <taglib-location>/WEB-INF/struts-bean.tld</taglib-location>
  </taglib>

  <taglib>
    <taglib-uri>/WEB-INF/struts-html.tld</taglib-uri>
    <taglib-location>/WEB-INF/struts-html.tld</taglib-location>
  </taglib>

  <taglib>
    <taglib-uri>/WEB-INF/struts-logic.tld</taglib-uri>
    <taglib-location>/WEB-INF/struts-logic.tld</taglib-location>
  </taglib>

</web-app>

 

2、

<?xml version="1.0" encoding="ISO-8859-1" ?>

<!DOCTYPE struts-config PUBLIC
          "-//Apache Software Foundation//DTD Struts Configuration 1.1//EN"
          "http://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd">

<!--
     This is the Struts configuration file for the "Hello!" sample application
-->

<struts-config>
 
    <!-- ======== Form Bean Definitions =================================== -->
    <form-beans>
        <form-bean name="HelloForm" type="hello.HelloForm"/>
    </form-beans>

  <!-- ========== Action Mapping Definitions ============================== -->
  <action-mappings>
    <!-- Say Hello! -->
    <action    path      = "/HelloWorld"
               type      = "hello.HelloAction"
               name      = "HelloForm"
               scope     = "request"
               validate  = "true"
               input     = "/hello.jsp"
     >
        <forward name="SayHello" path="/hello.jsp" />
    </action>
  </action-mappings>
 

  <!-- ========== Message Resources Definitions =========================== -->

  <message-resources parameter="hello.application"/>

</struts-config>

 

3、

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 UserName to say hello to :
hello.jsp.page.hello=Hello


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

hello.dont.talk.to.monster=We don't want to say hello to Monster!!!
hello.no.username.error=Please enter a <i>UserName</i> to say hello to!

 4、

package hello;
public class PersonBean {

    private String userName = null;

    public String getUserName() {
        return this.userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }

    /**
     * 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(i.e. database) if this were a real application.
         *
         * The actual business operations that would exist within a Model
         * component would depend upon the requirements of the application.
         */
    }
}

 

5、package hello;
public class PersonBean {

    private String userName = null;

    public String getUserName() {
        return this.userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }

    /**
     * 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(i.e. database) if this were a real application.
         *
         * The actual business operations that would exist within a Model
         * component would depend upon the requirements of the application.
         */
    }
}

 

6package hello;

import javax.servlet.http.HttpServletRequest;

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

public final class HelloForm extends ActionForm {

    private String userName = null;

    public String getUserName() {
        return (this.userName);
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }
  
    /**
     * Reset all properties to their default values.
     */
    public void reset(ActionMapping mapping, HttpServletRequest request) {
        this.userName = 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.
     */
    public ActionErrors validate(ActionMapping mapping,
                                 HttpServletRequest request) {

        ActionErrors errors = new ActionErrors();

        if ((userName == null) || (userName.length() < 1))
            errors.add("username", new ActionMessage("hello.no.username.error"));

        return errors;
    }
}

 

6

package 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.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.util.MessageResources;

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.
     */
    public ActionForward execute(ActionMapping mapping,
                                 ActionForm form,
                                 HttpServletRequest request,
                                 HttpServletResponse response)
    throws Exception {

        // 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
         */
        ActionMessages errors = new ActionMessages();
        String userName = (String)((HelloForm) form).getUserName();

        String badUserName = "Monster";

        if (userName.equalsIgnoreCase(badUserName)) {
           errors.add("username", new ActionMessage("hello.dont.talk.to.monster", badUserName ));
           saveErrors(request, errors);
           return (new ActionForward(mapping.getInput()));
        }

        /*
         * Having received and validated the data submitted
         * from the View, we now update the model
         */
        PersonBean pb = new PersonBean();
        pb.setUserName(userName);
        pb.saveToPersistentStore();

        /*
         * If there was a choice of View components that depended on the model
         * (or some other) status, we'd make the decision 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 neaded after the View is generated.
         *
         * Constants.PERSON_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.PERSON_KEY, pb);

        // 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"));

    }
}

 

7

package hello;

public final class Constants {

   /**
     * The application scope attribute under which our user database
     * is stored.
     */
    public static final String PERSON_KEY = "personbean";

}

 

 

8

<%@ 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="personbean" scope="request">
       <h2>
         <bean:message key="hello.jsp.page.hello"/>
         <bean:write name="personbean" property="userName" />!<p>
       </h2>
    </logic:present>

    <html:form action="/HelloWorld.do" focus="userName" >

      <bean:message key="hello.jsp.prompt.person"/>
      <html:text property="userName" 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>

原创粉丝点击