Как использовать внешний JS-файл в приложении Struts 1.1 и вызвать функцию Javascript на событие onclick? - PullRequest
0 голосов
/ 04 августа 2010

Я хочу использовать ajax и javascript в приложении Struts 1.1, потому что я хочу создать сетку данных с помощью вставки, обновления, удаления.

Ответы [ 2 ]

3 голосов
/ 26 марта 2011

Создание динамической сетки с использованием Struts-1, Jsp, Java, Javascript

Grid.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html"%>
<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
<%@ taglib uri="/WEB-INF/struts-logic.tld" prefix="logic" %>
<script type="text/javascript" src="scripts/scrollabletable.js"></script>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<%@page import="java.util.ArrayList"%>
<%@page import="sme.struts.actionform.Grid_form"%>
<html:html>
<script type="text/javascript">
function adddata()
{
document.forms[0].action="Grid.do?parameter=add"
document.forms[0].submit()
document.forms[0].add.disabled=true
return true
}
</script>
<head>
<html:base />

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>My Grid</title>
<style type="text/css">
<!--
.style5 {font-family: "Bookman Old Style"; font-weight: bold; font-size: 14px; }
.style6 {
    font-size: 14px;
    color: #CCCCCC;
}
.style10 {font-family: "Bookman Old Style"; font-size: 14; }
.style11 {font-size: 14}
.style13 {font-family: "Bookman Old Style"; font-weight: bold; font-size: 14px; color: #CCCCCC; }
-->
</style>
</head>
<body>
<%
String message=(String)request.getAttribute("gridmessage");
if(message==null)message="";
%>
<html:form action="/Grid" method="post">
<table width="100%" cellspacing="0" cellpadding="0">
  <tr>
    <td width="21%" class="style5">Name :<html:text property="name" /></td>
    <td width="25%" class="style5">Description :<html:text property="description" /></td>
    <td width="16%" class="style5">Age :<html:text property="age" /></td>
    <td width="38%"><html:button property="add" value="Add" onclick="adddata()" /></td>
  </tr>
  <tr>
    <td><%= message %></td>
    <td>&nbsp;</td>
    <td>&nbsp;</td>
    <td>&nbsp;</td>
  </tr>
</table>
<table id="myScrollTable" width="100%" cellspacing="0" cellpadding="0" border="1">
<thead>
  <tr bgcolor="#333333">
    <th width="14%"><span class="style13">Slno</span></th>
    <th width="31%"><span class="style13">Name</span></th>
    <th width="27%"><span class="style13">Description</span></th>
    <th width="12%"><span class="style13">Age</span></th>
    <th width="16%">&nbsp;</th>
  </tr>
  </thead>
  <tbody>
  <%
  int i=0;
  if((ArrayList<Grid_form>)session.getAttribute("gridlist")!=null)
  {
  %>
  <logic:iterate id="gridlist_id" name="gridlist">
  <tr>
    <td><span class="style10">&nbsp;<%= i+1 %>
    <a href="Grid.do?parameter=delete&listid=<%= i %>");return false;">Delete   </a>
    </span></td>
    <td><span class="style10">&nbsp;
      <bean:write name="gridlist_id" property="name" />
    </span></td>
    <td><span class="style10">&nbsp;
      <bean:write name="gridlist_id" property="description" />
    </span></td>
    <td><span class="style10">&nbsp;
      <bean:write name="gridlist_id" property="age" />
    </span></td>
    <td><span class="style11"></span></td>
  </tr>
  <% 
  i++; 

  %>
  </logic:iterate>
  <%
  }
  %>
  </tbody>
</table>
<script type="text/javascript">
    var t = new ScrollableTable(document.getElementById('myScrollTable'),200);
   </script>
</html:form>
</body>
</html:html>

Сервлет действия: Grid.java

package sme.struts.action;

import java.util.ArrayList;

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

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;

import sme.struts.actionform.Grid_form;
import sme.struts.actionform.test_form;

public class Grid extends DispatchAction {
    public ActionForward add(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        String message = "";

        Grid_form gf = (Grid_form) form;

        String name = gf.getName();
        String description = gf.getDescription();
        String age = gf.getAge();

        ArrayList<Grid_form> al = null;// new ArrayList<Grid_form>();

        HttpSession session = request.getSession();

        al = (ArrayList<Grid_form>) session.getAttribute("gridlist");

        Grid_form myform = new Grid_form();

        if (al == null) {
            al = new ArrayList<Grid_form>();
            myform.setName(name);
            myform.setDescription(description);
            myform.setAge(age);
            al.add(myform);
        } else {
            boolean flag = true;
            for (int i = 0; i < al.size(); i++) {
                if (al.get(i).getName().equals(name)) {
                    flag = false;
                    break;
                }
            }

            if (flag == false) {
                message = "Data already exists";
            } else {
                myform.setName(name);
                myform.setDescription(description);
                myform.setAge(age);
                al.add(myform);
            }
        }
        request.setAttribute("gridmessage", message);
        session.setAttribute("gridlist", al);
        System.out.println("Description is:::::" + gf.getDescription());
        return mapping.findForward("addsuccess");
    }

    public ActionForward delete(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        Grid_form gf = (Grid_form) form;

        ArrayList<Grid_form> al = null;// new ArrayList<Grid_form>();
        HttpSession session = request.getSession();
        al = (ArrayList<Grid_form>) session.getAttribute("gridlist");
        String listid = request.getParameter("listid");
        if (al != null) {
            al.remove(Integer.parseInt(listid));
        } else {

        }
        session.setAttribute("gridlist", al);
        return mapping.findForward("addsuccess");
    }
}

Форма действия: Grid_form.java

package sme.struts.actionform;

import javax.servlet.http.HttpServletRequest;

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

public class Grid_form extends ActionForm {
    private String name;
    private String description;
    private String age;

    /**
     * Method reset
     * 
     * @param mapping
     * @param request
     */
    public void reset(ActionMapping mapping, HttpServletRequest request) {
        // TODO Auto-generated method stub
    }

    public ActionErrors validate(ActionMapping mapping,
            HttpServletRequest request) {
        ActionErrors errors = new ActionErrors();
        System.out.println("1");
        // TODO Auto-generated method stub
        return errors;
    }

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

scrollabletable.js

/**
*
*  Scrollable HTML table
*  http://www.webtoolkit.info/
*
**/

function ScrollableTable (tableEl, tableHeight, tableWidth) {

    this.initIEengine = function () {

        this.containerEl.style.overflowY = 'auto';
        if (this.tableEl.parentElement.clientHeight - this.tableEl.offsetHeight < 0) {
            this.tableEl.style.width = this.newWidth - this.scrollWidth +'px';
        } else {
            this.containerEl.style.overflowY = 'hidden';
            this.tableEl.style.width = this.newWidth +'px';
        }

        if (this.thead) {
            var trs = this.thead.getElementsByTagName('tr');
            for (x=0; x<trs.length; x++) {
                trs[x].style.position ='relative';
                trs[x].style.setExpression("top",  "this.parentElement.parentElement.parentElement.scrollTop + 'px'");
            }
        }

        if (this.tfoot) {
            var trs = this.tfoot.getElementsByTagName('tr');
            for (x=0; x<trs.length; x++) {
                trs[x].style.position ='relative';
                trs[x].style.setExpression("bottom",  "(this.parentElement.parentElement.offsetHeight - this.parentElement.parentElement.parentElement.clientHeight - this.parentElement.parentElement.parentElement.scrollTop) + 'px'");
            }
        }

        eval("window.attachEvent('onresize', function () { document.getElementById('" + this.tableEl.id + "').style.visibility = 'hidden'; document.getElementById('" + this.tableEl.id + "').style.visibility = 'visible'; } )");
    };


    this.initFFengine = function () {
        this.containerEl.style.overflow = 'hidden';
        this.tableEl.style.width = this.newWidth + 'px';

        var headHeight = (this.thead) ? this.thead.clientHeight : 0;
        var footHeight = (this.tfoot) ? this.tfoot.clientHeight : 0;
        var bodyHeight = this.tbody.clientHeight;
        var trs = this.tbody.getElementsByTagName('tr');
        if (bodyHeight >= (this.newHeight - (headHeight + footHeight))) {
            this.tbody.style.overflow = '-moz-scrollbars-vertical';
            for (x=0; x<trs.length; x++) {
                var tds = trs[x].getElementsByTagName('td');
                tds[tds.length-1].style.paddingRight += this.scrollWidth + 'px';
            }
        } else {
            this.tbody.style.overflow = '-moz-scrollbars-none';
        }

        var cellSpacing = (this.tableEl.offsetHeight - (this.tbody.clientHeight + headHeight + footHeight)) / 4;
        this.tbody.style.height = (this.newHeight - (headHeight + cellSpacing * 2) - (footHeight + cellSpacing * 2)) + 'px';

    };

    this.tableEl = tableEl;
    this.scrollWidth = 16;

    this.originalHeight = this.tableEl.clientHeight;
    this.originalWidth = this.tableEl.clientWidth;

    this.newHeight = parseInt(tableHeight);
    this.newWidth = tableWidth ? parseInt(tableWidth) : this.originalWidth;

    this.tableEl.style.height = 'auto';
    this.tableEl.removeAttribute('height');

    this.containerEl = this.tableEl.parentNode.insertBefore(document.createElement('div'), this.tableEl);
    this.containerEl.appendChild(this.tableEl);
    this.containerEl.style.height = this.newHeight + 'px';
    this.containerEl.style.width = this.newWidth + 'px';


    var thead = this.tableEl.getElementsByTagName('thead');
    this.thead = (thead[0]) ? thead[0] : null;

    var tfoot = this.tableEl.getElementsByTagName('tfoot');
    this.tfoot = (tfoot[0]) ? tfoot[0] : null;

    var tbody = this.tableEl.getElementsByTagName('tbody');
    this.tbody = (tbody[0]) ? tbody[0] : null;

    if (!this.tbody) return;

    if (document.all && document.getElementById && !window.opera) this.initIEengine();
    if (!document.all && document.getElementById && !window.opera) this.initFFengine();


}

распорка-config.xml

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

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

<!--
     This is a blank Struts configuration file with an example
     welcome action/page and other commented sample elements.

     Tiles and the Struts Validator are configured using the factory defaults
     and are ready-to-use.

     NOTE: If you have a generator tool to create the corresponding Java classes
     for you, you could include the details in the "form-bean" declarations.
     Otherwise, you would only define the "form-bean" element itself, with the
     corresponding "name" and "type" attributes, as shown here.
-->
<struts-config>
<!-- ============================================ Data Source Configuration -->
<data-sources>
<data-source key="smeds" type="org.apache.commons.dbcp.BasicDataSource">
    <set-property
      property="driverClassName"
      value="oracle.jdbc.driver.OracleDriver" />
    <set-property
      property="url"
      value="jdbc:oracle:thin:@192.168.100.136:1521:ortelapp" />
    <set-property
      property="username"
      value="scott" />
    <set-property
      property="password"
      value="tigerscott" />
    <set-property
      property="maxActive"
      value="10" />
    <set-property
      property="maxWait"
      value="5000" />
    <set-property
      property="defaultAutoCommit"
      value="false" />
    <set-property
      property="defaultReadOnly"
      value="false" />

</data-source>
</data-sources>
<!-- ================================================ Form Bean Definitions -->

    <form-beans>


           <form-bean
            name="MyregForm"
            type="myregistration.MyregForm"/>
            <form-bean
            name="my_form"
            type="formbean.my_form"/> 

            <form-bean name="file_reg_v1_form" 
            type="sme.struts.actionform.file_reg_v1_form" />

            <form-bean name="test_form" 
            type="sme.struts.actionform.test_form" />

           <form-bean name="Grid_form" 
            type="sme.struts.actionform.Grid_form" />

                <!-- sample form bean descriptor for an ActionForm
        <form-bean
            name="inputForm"
            type="app.InputForm"/>
    end sample -->

    <!-- sample form bean descriptor for a DynaActionForm
        <form-bean
            name="logonForm"
            type="org.apache.struts.action.DynaActionForm">
            <form-property
                name="username"
                type="java.lang.String"/>
            <form-property
                name="password"
                type="java.lang.String"/>
       </form-bean>
    end sample -->
    </form-beans>


<!-- ========================================= Global Exception Definitions -->

    <global-exceptions>
        <!-- sample exception handler
        <exception
            key="expired.password"
            type="app.ExpiredPasswordException"
            path="/changePassword.jsp"/>
        end sample -->
    </global-exceptions>


<!-- =========================================== Global Forward Definitions -->

    <global-forwards>
        <!-- Default forward to "Welcome" action -->
        <!-- Demonstrates using index.jsp to forward -->
        <forward
            name="welcome"
            path="/Welcome.do"/>
            <forward
            name="sessionexpired"
            path="/ctss_logout.jsp"/>
    </global-forwards>


<!-- =========================================== Action Mapping Definitions -->

    <action-mappings>
            <!-- Default "Welcome" action -->
            <!-- Forwards to Welcome.jsp -->

        <action
      path="/DataSource"
      type="test.TestDataSource">
      <forward name="success" path="/pages/success.jsp"/>
      </action>    

        <action
            path="/Welcome"
            forward="/pages/Welcome.jsp"/>

        <action
            path="/TestAction"
            type="roseindia.net.TestAction">
            <forward name="testAction" path="/pages/TestAction.jsp"/>
        </action>

        <action
            path="/myaction"
            type="actionservlets.my_servlet"
            name="my_form"
            scope="request"
            validate="true"
            input="/u_login.jsp">           
             <forward name="myentrysuccess" path="/afterlogin.jsp" />
        </action>
        <!-- Bikram -->

        <action 
            path="/file_reg_v1"
            type="sme.struts.action.file_reg_v1"
            name="file_reg_v1_form"
            validate="true"
            scope="request"
            input="/file_reg_v1.jsp">
        <forward name="uploadsuccess" path="/file_reg_v1.jsp" />
        </action>

        <action 
        path="/test"
        type="sme.struts.action.test"
        name="test_form"
        validate="true"
        scope="request"
        input="/test.jsp"
        >
        <forward name="success" path="/test.jsp" />
        </action>


        <action 
        path="/Grid"
        type="sme.struts.action.Grid"
        name="Grid_form"
        validate="true"
        parameter="parameter"
        scope="request"
        input="/Grid.jsp"
        >
        <forward name="addsuccess" path="/Grid.jsp" />
        <forward name="addfailure" path="/Grid.jsp" />
        </action>
        <action
         path="/Tiles/Example"
         forward="Tiles.Example"/>

    <!-- sample input and input submit actions  

        <action
            path="/Input"
            type="org.apache.struts.actions.ForwardAction"
            parameter="/pages/Input.jsp"/>

        <action
            path="/InputSubmit"
            type="app.InputAction"
            name="inputForm"
            scope="request"
            validate="true"
            input="/pages/Input.jsp"/>

            <action
                path="/edit*"
                type="app.Edit{1}Action"
                name="inputForm"
                scope="request"
                validate="true"
                input="/pages/Edit{1}.jsp"/>

    end samples -->
    </action-mappings>


<!-- ============================================= Controller Configuration -->

    <controller
       processorClass="org.apache.struts.tiles.TilesRequestProcessor"/>


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

    <message-resources parameter="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.
  -->

    <plug-in className="org.apache.struts.tiles.TilesPlugin" >

      <!-- Path to XML definition file -->
      <set-property property="definitions-config"
                       value="/WEB-INF/tiles-defs.xml" />
      <!-- Set Module-awareness to true -->
      <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/validator-rules.xml,/WEB-INF/validation.xml"/>
  </plug-in>

</struts-config>
0 голосов
/ 04 августа 2010

Здесь есть учебник , в котором показано, как это сделать. Я сделал это некоторое время назад.

По сути, вам нужно создать DispatchAction или LookupDispatchAction, который возвращает результат null, чтобы Struts не обрабатывал ActionForward.

Вместо этого для ваших методов действий вам придется записывать свои ответы в виде текста в HttpServletResponse.

Другое решение: AjaxAnywhere или представление AjaxStruts

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...