Struts原理与实践(7)

在上一篇文章中介绍校验时提到客户边的校验用到了JavaScript,实际上用Struts配合JavaScript还可以实现许多有用的功能,比如,级联下拉菜单的实现就是一个典型的例子:

本例假设要实现的是一个文章发布系统,我们要发布的文章分为新闻类和技术类,其中新闻类又分为时事新闻和行业动态;技术类又分为操作系统、数据库、和编程语言等,为了便于添加新的条目,所有这些都保存在数据库表中。

为此,我们建立一个名为articleClass的表和一个名为articleSubClass的表。

      articleClass表的结构如下:
articleClassID字段:char类型,长度为2,主键
articleClassName字段:varchar类型,长度为20
articleSubClass表的结构如下:
articleClassID字段:char类型,长度为2
articleSubClassID字段:char类型,长度为2与articleClassID一起构成主键
articleSubClassName字段:varchar类型,长度为20


表建好后,在articleClass表中录入如下数据:如,01、新闻类;02、技术类

在articleSubClass表中录入:01、01、时事新闻;01、02、行业动态;02、01、操作系统等记录。到这里,数据库方面的准备工作就已做好。

有了前面做登录例子的基础,理解下面要进行的工作就没有什么难点了,我们现在的工作也在原来mystruts项目中进行。首先,建立需要用到的formbean即ArticleClassForm,其代码如下:

      package entity;
import org.apache.struts.action.*;
import javax.servlet.http.*;
import java.util.Collection;

public class ArticleClassForm extends ActionForm {
  //为select的option做准备
  private Collection beanCollection;
  private String singleSelect = "";
  private String[] beanCollectionSelect = { "" };
  private String articleClassID;
  private String articleClassName;
  private String subI;//子类所在行数
  private String subJ;//子类所在列数
  private String articleSubClassID;
  private String articleSubClassName;

  public Collection getBeanCollection(){
    return beanCollection;
  }

  public void setBeanCollection(Collection beanCollection){
    this.beanCollection=beanCollection;
  }

  public String getSingleSelect() {
    return (this.singleSelect);
  }
  public void setSingleSelect(String singleSelect) {
    this.singleSelect = singleSelect;
  }
  public String[] getBeanCollectionSelect() {
    return (this.beanCollectionSelect);
  }
  public void setBeanCollectionSelect(String beanCollectionSelect[]) {
    this.beanCollectionSelect = beanCollectionSelect;
  }

  public String getArticleClassID() {
    return articleClassID;
  }
  public void setArticleClassID(String articleClassID) {
    this.articleClassID = articleClassID;
  }
  public String getArticleClassName() {
    return articleClassName;
  }
  public void setArticleClassName(String articleClassName) {
    this.articleClassName = articleClassName;
  }

  public String getSubI() {
    return subI;
  }
  public void setSubI(String subI) {
    this.subI = subI;
  }

  public String getSubJ() {
    return subJ;
  }
  public void setSubJ(String subJ) {
    this.subJ = subJ;
  }

  public String getArticleSubClassID() {
    return articleSubClassID;
  }
  public void setArticleSubClassID(String articleSubClassID) {
    this.articleSubClassID = articleSubClassID;
  }

  public String getArticleSubClassName() {
    return articleSubClassName;
  }
  public void setArticleSubClassName(String articleSubClassName) {
    this.articleSubClassName = articleSubClassName;
  }
}


将它放在包entity中。其次,我们的系统要访问数据库,因此也要建立相应的数据库访问对象ArticleClassDao,其代码如下:

      package db;

import entity.ArticleClassForm;
import db.*;
import java.sql.*;

import java.util.Collection;
import java.util.ArrayList;
import org.apache.struts.util.LabelValueBean;
public class ArticleClassDao {
  private Connection con;

  public ArticleClassDao(Connection con) {
    this.con=con;
  }
  public Collection findInUseForSelect(){
    PreparedStatement ps=null;
    ResultSet rs=null;
    ArrayList list=new ArrayList();
    String sql="select * from articleClass order by articleClassID";
    try{
      if(con.isClosed()){
        throw new IllegalStateException("error.unexpected");
      }
      ps=con.prepareStatement(sql);
      rs=ps.executeQuery();

      while(rs.next()){
        String value=rs.getString("articleClassID");
        String label=rs.getString("articleClassName");
        list.add(new LabelValueBean(label,value));
      }
      return list;
    }
    catch(SQLException e){
      e.printStackTrace();
      throw new RuntimeException("error.unexpected");
    }
    finally{
      try{
        if(ps!=null)
          ps.close();
        if(rs!=null)
          rs.close();

      }
      catch(SQLException e){
        e.printStackTrace();
        throw new RuntimeException("error.unexpected");
      }
    }
  }

  public Collection findInUseForSubSelect(){
    PreparedStatement ps=null;
    ResultSet rs=null;
    PreparedStatement psSub=null;
    ResultSet rsSub=null;
    int i=0;//大类记数器
    int j=0;//小类记数器
    String classID="";
    String subClassID="";
    String subClassName="";

    ArrayList list=new ArrayList();
    ArticleClassForm articleClassForm;


    String sql="select * from articleClass order by articleClassID";
    try{
      if(con.isClosed()){
        throw new IllegalStateException("error.unexpected");
      }
      ps=con.prepareStatement(sql);
      rs=ps.executeQuery();

      while(rs.next()){
        i++;
        classID=rs.getString("articleClassID");
        String sqlSub="select * from articleSubClass where articleClassID=? 
		order by articleSubClassID";
        psSub=con.prepareStatement(sqlSub);
        psSub.setString(1,classID);
        rsSub=psSub.executeQuery();

        articleClassForm=new ArticleClassForm();
        articleClassForm.setSubI(""+i);
        articleClassForm.setSubJ(""+j);
        articleClassForm.setArticleSubClassID("请输入一个小类");
        articleClassForm.setArticleSubClassName("请输入一个小类");
        list.add(articleClassForm);

        while(rsSub.next()){
          subClassID=rsSub.getString("articleSubClassID");
          subClassName=rsSub.getString("articleSubClassName");
          j++;
          //optionStr="articleSubClassGroup[" + i + "][" + j + "]=
new Option('"+ subClassName +"','"+ subClassID+ "')";
          articleClassForm=new ArticleClassForm();
          articleClassForm.setSubI(""+i);
          articleClassForm.setSubJ(""+j);
          articleClassForm.setArticleSubClassID(subClassID);
          articleClassForm.setArticleSubClassName(subClassName);
          list.add(articleClassForm);
        }

        j=0;
      }
      return list;
    }
    catch(SQLException e){
      e.printStackTrace();
      throw new RuntimeException("error.unexpected");
    }
    finally{
      try{
        if(ps!=null)
          ps.close();
        if(rs!=null)
          rs.close();

      }
      catch(SQLException e){
        e.printStackTrace();
        throw new RuntimeException("error.unexpected");
      }
    }
  }
}


将它保存在db目录中。它们的目的是将文章的类和子类信息从数据库表中读出,以一定的格式保存在集合对象中以供页面显示。

再次,我们要建立相应的jsp文件,文件名为selectArticleClass.jsp,代码如下:

      <%@ page contentType="text/html; charset=UTF-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>
<head>
<title>
选择文件类别
</title>
</head>
<body bgcolor="#ffffff">
<h3>
选择文件所属类型
</h3>
<html:errors/>
<table width="500" border="0" cellspacing="0" cellpadding="0">
  <tr>
    <td><html:form name="articleClassForm" type="entity.ArticleClassForm"
	action="selectArticleClassAction.do">
        <table width="500" border="0" cellspacing="0" cellpadding="0">
          <tr>
            <td align="right">文章大类*</td>
            <td>
              <html:select property="articleClassID" styleClass="word"
			 onchange="articleClassFormredirect(this.options.selectedIndex)">
                <html:option value="">请选择一个大类</html:option>
                <html:optionsCollection name="articleClassForm" property="beanCollection" styleClass="word"/>
              </html:select>
            </td>
          </tr>
          <tr>
            <td align="right">文章小类*</td>
            <td>
              <select name="articleSubClassID" Class="word" >
                <option value="">请选择一个小类</option>
              </select>
              <SCRIPT language=JavaScript>
              <!--
              var articleSubClassGroups=document.articleClassForm.articleClassID.
			 options.length
              var articleSubClassGroup=new Array(articleSubClassGroups)
              for (i=0; i<articleSubClassGroups; i++)
              articleSubClassGroup[i]=new Array()
              <logic:iterate name="articleSubClassList" id="articleClassForm"
			  scope="request" type="entity.ArticleClassForm">
                articleSubClassGroup[<bean:write name="articleClassForm"
				property="subI"/>][<bean:write name="articleClassForm"
				property="subJ"/>]=new Option("<bean:write name="articleClassForm"
			property="articleSubClassName"/>","<bean:write name="articleClassForm"
			property="articleSubClassID"/>")
              </logic:iterate>
              var articleSubClassTemp=document.articleClassForm.articleSubClassID
              function articleClassFormredirect(x){
                for (m=articleSubClassTemp.options.length-1;m>0;m--)
                articleSubClassTemp.options[m]=null
                for (i=0;i<articleSubClassGroup[x].length;i++){
                  articleSubClassTemp.options[i]=new
		Option(articleSubClassGroup[x][i].text,
                   articleSubClassGroup[x][i].value)
                }
                articleSubClassTemp.options[0].selected=true
              }
             //-->
           </SCRIPT>
            </td>
          </tr>
        </table>
      </html:form>
    </td>
  </tr>
</table>
</body>
</html>


这里值得重点关注的是其中的JavaScript代码,有兴趣的可以仔细分析一下它们是怎样配合集合中的元素来实现级联选择的。

最后,为了例子的完整。我们将涉及到action代码和必要的配置代码在下面列出:其中,action的文件名为SelectArticleClassAction.java,代码如下:

      package action;
import entity.*;
import org.apache.struts.action.*;
import javax.servlet.http.*;
import javax.sql.DataSource;
import java.sql.Connection;
import db.ArticleClassDao;
import java.util.Collection;
import java.sql.SQLException;
public class SelectArticleClassAction extends Action {
  public ActionForward execute(ActionMapping actionMapping, ActionForm actionForm,
  HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
    /**@todo: complete the business logic here, this is just a skeleton.*/
    ArticleClassForm articleClassForm = (ArticleClassForm) actionForm;
    DataSource dataSource;
    Connection cnn=null;
    ActionErrors errors=new ActionErrors();
    try{
      dataSource = getDataSource(httpServletRequest,"A");
      cnn = dataSource.getConnection();
      ArticleClassDao articleClassDao=new ArticleClassDao(cnn);

      Collection col=articleClassDao.findInUseForSelect();
      articleClassForm.setBeanCollection(col);
      httpServletRequest.setAttribute("articleClassList",col);

      //处理子类选项
      Collection subCol=articleClassDao.findInUseForSubSelect();
      httpServletRequest.setAttribute("articleSubClassList",subCol);
      return actionMapping.findForward("success");
    }
    catch(Throwable e){
      e.printStackTrace();
      //throw new RuntimeException("未能与数据库连接");
      ActionError error=new ActionError(e.getMessage());
      errors.add(ActionErrors.GLOBAL_ERROR,error);
    }
    finally{
      try{
        if(cnn!=null)
          cnn.close();
      }
      catch(SQLException e){
        throw new RuntimeException(e.getMessage());
      }
    }
    saveErrors(httpServletRequest,errors);
    return actionMapping.findForward("fail");
  }
}


将其保存在action目录中。

在struts-config.xml文件中做如下配置:

      <form-beans>
中加入
      <form-bean name="articleClassForm" type="entity.ArticleClassForm" />


      ><action-mappings>
中加入:

      <action name="articleClassForm" path="/selectArticleClassAction" scope="session"
	type="action.SelectArticleClassAction" validate="false">
<forward name="success" path="/selectArticleClass.jsp" />
<forward name="fail" path="/genericError.jsp" />
</action>


为了对应配置中的
      <forward name="fail" path="/genericError.jsp" />
,我们还要提供一个显示错误信息的jsp页面,其代码如下:

      <%@ page contentType="text/html; charset=UTF-8" %>
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
<html>
<head>
<title>
genericError
</title>
<link href="css/mycss.css" rel="stylesheet" type="text/css">
</head>
<body bgcolor="#ffffff">
<html:errors/>
</body>
</html>


现在一切就绪,可以编译执行了。在浏览器中输入:http://127.0.0.1:8080/mystruts/selectArticleClassAction.do就可以看到该例子的运行结果了。(T111)  

你可能感兴趣的:(JavaScript,String,struts,null,action,import)