MiniHR 01.set up the demo website

来源:互联网 发布:java 反射 编辑:程序博客网 时间:2024/06/05 14:52
MiniHR:

1.web folder:
c:\workspace\MiniHR\src
c:\workspace\MiniHR\WebContent\readme.txt
c:\workspace\MiniHR\WebContent\lib
c:\workspace\MiniHR\WebContent\WEB-INF\classes
c:\workspace\MiniHR\WebContent\WEB-INF\web.xml
c:\workspace\MiniHR\WebContent\WEB-INF\struts-config.xml

2.import all struts 1.3.10 jars to \MiniHR\WebContent\lib

3.
index.jsp
search.jsp
SearchForm.java
SearchAction.java
EmployeeSearchService.java
Employee.java
web.xml
struts-config.xml
validation.xml(copied from struts 1.3.10)
MessageResources.properties

------------------------------------------------------------------------------------

index.jsp

<%@ taglib uri="http://struts.apache.org/tags-html" prefix="html" %><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>ABC, Inc. Human Resource Portal</title></head><body><font size="+1">ABC, Inc. Human Resource Portal</font><br><hr width="100%" noshade="true">&#149; Add an Employee<br>&#149; <html:link forward="search">Search for Employees</html:link></body></html>

search.jsp

<%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean" %><%@ taglib uri="http://struts.apache.org/tags-html" prefix="html" %><%@ taglib uri="http://struts.apache.org/tags-logic" prefix="logic" %><html><head><title>ABC, Inc. Human Resource Portal - Employee Search</title></head><body><font size="+1">ABC, Inc. Human Resource Portal - Employee Search</font><br><hr width="100%" noshade="true"><html:errors/><html:form action="/search"><table><tr><td align="right"><bean:message key="label.search.name"/>:</td><td><html:text property="name"/></td></tr><tr><td></td><td>-- or --</td></tr><tr><td align="right"><bean:message key="label.search.ssNum"/>:</td><td><html:text property="ssNum"/>(xxx-xx-xxxx)</td></tr><tr><td></td><td><html:submit/></td></tr></table></html:form><logic:present name="searchForm" property="results"><hr width="100%" size="1" noshade="true"><bean:size id="size" name="searchForm" property="results" /><logic:equal name="size" value="0"><center><font color="red"><b>No Employees Found</b></font></center></logic:equal><logic:greaterThan name="size" value="0"><table border="1"><tr><th>Name</th><th>Social Secutiry Number</th></tr><logic:iterate id="result" name="searchForm" property="results"><tr><td><bean:write name="result" property="name"/></td><td><bean:write name="result" property="ssNum"/></td></tr></logic:iterate></table></logic:greaterThan></logic:present></body></html>

SearchForm.java

package com.jamesholmes.struts;import java.util.List;import javax.servlet.http.HttpServletRequest;import org.apache.struts.action.ActionErrors;import org.apache.struts.action.ActionForm;import org.apache.struts.action.ActionMapping;import org.apache.struts.action.ActionMessage;public class SearchForm extends ActionForm {    private static final long serialVersionUID = 1L;    private String name = null;    private String ssNum = null;    private List results = null;    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public String getSsNum() {        return ssNum;    }    public void setSsNum(String ssNum) {        this.ssNum = ssNum;    }    public List getResults() {        return results;    }    public void setResults(List results) {        this.results = results;    }    @Override    // Reset form fields.    public void reset(ActionMapping mapping, HttpServletRequest request) {        this.name = null;        this.ssNum = null;        this.results = null;    }    @Override    // Validate form data.    public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {        ActionErrors errors = new ActionErrors();        boolean nameEntered = false;        boolean ssNumEntered = false;        // Determine if name has been entered.        if (name != null && name.length() > 0) {            nameEntered = true;        }        // Determine if social security number has been entered.        if (ssNum != null & ssNum.length() > 0) {            ssNumEntered = true;        }        // Validate that either name or social security number has been entered.        if (!nameEntered && !ssNumEntered) {            errors.add(null, new ActionMessage("error.search.criteria.missing"));        }        // Validate format of social security number if it has been entered.        if (ssNumEntered && !isValidSsNum(ssNum.trim())) {            errors.add("ssNum",                    new ActionMessage("error.search.ssNum.invalid"));        }        return errors;    }    // Validate format of social security number.    private static boolean isValidSsNum(String ssNum) {        if (ssNum.length() < 11) {            return false;        }        for (int i = 0; i < 11; i++) {            if (i == 3 || i == 6) {                if (ssNum.charAt(i) != '-') {                    return false;                }            } else if ("0123456789".indexOf(ssNum.charAt(i)) == -1) {                return false;            }        }        return true;    }}


SearchAction.java

package com.jamesholmes.struts;import java.util.ArrayList;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.apache.struts.action.Action;import org.apache.struts.action.ActionForm;import org.apache.struts.action.ActionForward;import org.apache.struts.action.ActionMapping;public class SearchAction extends Action {@Overridepublic ActionForward execute(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response) throws Exception {EmployeeSearchService service = new EmployeeSearchService();ArrayList results;SearchForm searchForm = (SearchForm) form;// Perform employee search based on what criteria was entered.String name = searchForm.getName();if (name != null && name.trim().length() > 0) {results = service.searchByName(name);} else {results = service.searchBySsNum(searchForm.getSsNum().trim());}// Place search results in SearchForm for access by JSP.searchForm.setResults(results);// Forward control to this Action's input page.return mapping.getInputForward();}}

EmployeeSearchService.java

package com.jamesholmes.struts;import java.util.ArrayList;public class EmployeeSearchService {    /* Hard-coded sample data. Normally this would come from a real data source such as a database. */    private static Employee[] employees =    {        new Employee("Bob Davidson", "123-45-6789"),        new Employee("Mary Williams", "987-65-4321"),        new Employee("Jim Smith", "111-11-1111"),        new Employee("Beverly Harris", "222-22-2222"),        new Employee("Thomas Frank", "333-33-3333"),        new Employee("Jim Davidson", "444-44-4444")    };    // Search for employees by name.    public ArrayList searchByName(String name) {        ArrayList resultList = new ArrayList();        for (int i=0; i < employees.length; i++) {            if (employees[i].getName().toUpperCase().indexOf(name.toUpperCase())!= -1) {                resultList.add(employees[i]);            }        }        return resultList;    }    // Search for employee by social security number.    public ArrayList searchBySsNum(String ssNum) {        ArrayList resultList = new ArrayList();        for (int i=0; i < employees.length; i++) {            if (employees[i].getSsNum().equals(ssNum)) {                resultList.add(employees[i]);            }        }        return resultList;    }}

Employee.java

package com.jamesholmes.struts;public class Employee {    private String name;    private String ssNum;    public Employee(String name, String ssNum) {        this.name = name;        this.ssNum = ssNum;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public String getSsNum() {        return ssNum;    }    public void setSsNum(String ssNum) {        this.ssNum = ssNum;    }}

web.xml

<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">    <display-name>MiniHR</display-name>    <!-- 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>1</load-on-startup>    </servlet>    <!-- Action Servlet Mapping -->    <servlet-mapping>        <servlet-name>action</servlet-name>        <url-pattern>*.do</url-pattern>    </servlet-mapping>    <!-- The Welcome File List -->    <welcome-file-list>        <welcome-file>/index.jsp</welcome-file>    </welcome-file-list>    <!-- StrutsTag Library Descriptors    <taglib>        <tablib-uri>/WEB-INF/tlds/struts-bean.tld</tablib-uri>        <tablib-location>/WEB-INF/tlds/struts-bean.tld</tablib-location>    </taglib>    <taglib>        <tablib-uri>/WEB-INF/tlds/struts-html.tld</tablib-uri>        <tablib-location>/WEB-INF/tlds/struts-html.tld</tablib-location>    </taglib>    <taglib>        <tablib-uri>/WEB-INF/tlds/struts-logic.tld</tablib-uri>        <tablib-location>/WEB-INF/tlds/struts-logic.tld</tablib-location>    </taglib>    --></web-app>

struts-config.xml

<?xml version="1.0" encoding="ISO-8859-1" ?><!DOCTYPE struts-config PUBLIC          "-//Apache Software Foundation//DTD Struts Configuration 1.3//EN"          "http://struts.apache.org/dtds/struts-config_1_3.dtd"><struts-config>    <!-- Form Beans Configuration -->    <form-beans>        <form-bean name="searchForm" type="com.jamesholmes.struts.SearchForm" />    </form-beans>    <global-exceptions>        <!-- sample exception handler        <exception            key="expired.password"            type="app.ExpiredPasswordException"            path="/changePassword.jsp"/>        end sample -->    </global-exceptions>    <!-- Global Forwards Configuration -->    <global-forwards>        <forward            name="search"            path="/search.jsp"/>    </global-forwards>    <!-- Action Mapping Configuration -->    <action-mappings>        <action            path="/search"            type="com.jamesholmes.struts.SearchAction"            name="searchForm"            scope="request"            validate="true"            input="/search.jsp">        </action>    </action-mappings>    <!-- Message Resources Configuration -->    <message-resources parameter="com.jamesholmes.struts.MessageResources" /><!-- =============================================== Plug Ins Configuration -->  <!-- ======================================================= Tiles plugin -->  <!--     This plugin initialize Tiles definition factory. This later can takes some parameters explained here after. The plugin first read parameters from web.xml, thenoverload them with parameters defined here. All parameters are optional.     The plugin should be declared in each struts-config file.       - definitions-config: (optional)            Specify configuration file names. There can be several comma    separated file names (default: ?? )       - moduleAware: (optional - struts1.1)            Specify if the Tiles definition factory is module aware. If true            (default), there will be one factory for each Struts module.If false, there will be one common factory for all module. In this            later case, it is still needed to declare one plugin per module.            The factory will be initialized with parameters found in the first            initialized plugin (generally the one associated with the default            module).  true : One factory per module. (default)  false : one single shared factory for all modules   - definitions-parser-validate: (optional)        Specify if xml parser should validate the Tiles configuration file.  true : validate. DTD should be specified in file header (default)  false : no validation  Paths found in Tiles definitions are relative to the main context.      To use this plugin, download and add the Tiles jar to your WEB-INF/lib      directory then uncomment the plugin definition below.    <plug-in className="org.apache.struts.tiles.TilesPlugin" >      <set-property property="definitions-config"                       value="/WEB-INF/tiles-defs.xml" />      <set-property property="moduleAware" value="true" />    </plug-in>  -->  <!-- =================================================== Validator plugin -->  <plug-in className="org.apache.struts.validator.ValidatorPlugIn">    <set-property        property="pathnames"        value="/WEB-INF/validation.xml"/>  </plug-in></struts-config>

validation.xml (copied from struts 1.3.10)

<?xml version="1.0" encoding="ISO-8859-1" ?><!--    Licensed to the Apache Software Foundation (ASF) under one or more    contributor license agreements.  See the NOTICE file distributed with    this work for additional information regarding copyright ownership.    The ASF licenses this file to You under the Apache License, Version 2.0    (the "License"); you may not use this file except in compliance with    the License.  You may obtain a copy of the License at            http://www.apache.org/licenses/LICENSE-2.0       Unless required by applicable law or agreed to in writing, software    distributed under the License is distributed on an "AS IS" BASIS,    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.    See the License for the specific language governing permissions and    limitations under the License.--><!DOCTYPE form-validation PUBLIC     "-//Apache Software Foundation//DTD Commons Validator Rules Configuration 1.3.0//EN"     "http://jakarta.apache.org/commons/dtds/validator_1_3_0.dtd"><form-validation><!--     This is a minimal Validator form file with a couple of examples.-->    <global>        <!-- An example global constant        <constant>            <constant-name>postalCode</constant-name>            <constant-value>^\d{5}\d*$</constant-value>        </constant>        end example-->    </global>    <formset>        <!-- An example form -->        <form name="logonForm">            <field                property="username"                depends="required">                    <arg key="logonForm.username"/>            </field>            <field                property="password"                depends="required,mask">                    <arg key="logonForm.password"/>                    <var>                        <var-name>mask</var-name>                        <var-value>^[0-9a-zA-Z]*$</var-value>                    </var>            </field>        </form>    </formset>    <!-- An example formset for another locale -->    <formset language="fr">        <constant>            <constant-name>postalCode</constant-name>            <constant-value>^[0-9a-zA-Z]*$</constant-value>        </constant>        <!-- An example form -->        <form name="logonForm">            <field                property="username"                depends="required">                    <arg key="logonForm.username"/>            </field>            <field                property="password"                depends="required,mask">                    <arg key="logonForm.password"/>                    <var>                        <var-name>mask</var-name>                        <var-value>^[0-9a-zA-Z]*$</var-value>                    </var>            </field>        </form>   </formset></form-validation>

MessageResources.properties

# Label Resourceslabel.search.name=Namelabel.search.ssNum=Social Security Number# Error Resourceserror.search.criteria.missing=<li>Search Criteria Missing</li>error.search.ssNum.invalid=<li>Invalid Social Security Number</li>errors.header=<font color="red"><b>Validation Error(s)</b></font><ul>errors.footer=</ul><hr width="100%" size="1" noshade="true">