`
taijh999
  • 浏览: 4943 次
  • 来自: ...
文章分类
社区版块
存档分类
最新评论

struts 2 中的doubleselect(jdbc实现)

阅读更多

struts 2中的doubleselect 实现了级联操作,本文通过一个简单的是实例,说明怎样对数据库中的表进行级联。

希望对初学者有点滴的帮助。

本文给出了完整的实现过程,并有源代码下载。

本文参考了http://opas.iteye.com/blog/183518 向作者表示谢意

 

注意:用IE来看本文,要不然贴图看不到

 

 

首先建立数据库

CREATE DATABASE JPETSTORE;
USE JPETSTORE;

create table category (
	catid varchar(10) not null,
	name varchar(80) null,
	descn varchar(255) null,
	constraint pk_category primary key (catid)
);

create table product (
    productid varchar(10) not null,
    category varchar(10) not null,
    name varchar(80) null,
    descn varchar(255) null,
    constraint pk_product primary key (productid),
        constraint fk_product_1 foreign key (category)
        references category (catid)
);

INSERT INTO category VALUES ('FISH','Fish','<image src="../images/fish_icon.gif"><font size="5" color="blue"> Fish</font>');
INSERT INTO category VALUES ('DOGS','Dogs','<image src="../images/dogs_icon.gif"><font size="5" color="blue"> Dogs</font>');
INSERT INTO category VALUES ('REPTILES','Reptiles','<image src="../images/reptiles_icon.gif"><font size="5" color="blue"> Reptiles</font>');
INSERT INTO category VALUES ('CATS','Cats','<image src="../images/cats_icon.gif"><font size="5" color="blue"> Cats</font>');
INSERT INTO category VALUES ('BIRDS','Birds','<image src="../images/birds_icon.gif"><font size="5" color="blue"> Birds</font>');

INSERT INTO product VALUES ('FI-SW-01','FISH','Angelfish','<image src="../images/fish1.gif">Salt Water fish from Australia');
INSERT INTO product VALUES ('FI-SW-02','FISH','Tiger Shark','<image src="../images/fish4.gif">Salt Water fish from Australia');
INSERT INTO product VALUES ('FI-FW-01','FISH', 'Koi','<image src="../images/fish3.gif">Fresh Water fish from Japan');
INSERT INTO product VALUES ('FI-FW-02','FISH', 'Goldfish','<image src="../images/fish2.gif">Fresh Water fish from China');
INSERT INTO product VALUES ('K9-BD-01','DOGS','Bulldog','<image src="../images/dog2.gif">Friendly dog from England');
INSERT INTO product VALUES ('K9-PO-02','DOGS','Poodle','<image src="../images/dog6.gif">Cute dog from France');
INSERT INTO product VALUES ('K9-DL-01','DOGS', 'Dalmation','<image src="../images/dog5.gif">Great dog for a Fire Station');
INSERT INTO product VALUES ('K9-RT-01','DOGS', 'Golden Retriever','<image src="../images/dog1.gif">Great family dog');
INSERT INTO product VALUES ('K9-RT-02','DOGS', 'Labrador Retriever','<image src="../images/dog5.gif">Great hunting dog');
INSERT INTO product VALUES ('K9-CW-01','DOGS', 'Chihuahua','<image src="../images/dog4.gif">Great companion dog');
INSERT INTO product VALUES ('RP-SN-01','REPTILES','Rattlesnake','<image src="../images/snake1.gif">Doubles as a watch dog');
INSERT INTO product VALUES ('RP-LI-02','REPTILES','Iguana','<image src="../images/lizard1.gif">Friendly green friend');
INSERT INTO product VALUES ('FL-DSH-01','CATS','Manx','<image src="../images/cat2.gif">Great for reducing mouse populations');
INSERT INTO product VALUES ('FL-DLH-02','CATS','Persian','<image src="../images/cat1.gif">Friendly house cat, doubles as a princess');
INSERT INTO product VALUES ('AV-CB-01','BIRDS','Amazon Parrot','<image src="../images/bird2.gif">Great companion for up to 75 years');
INSERT INTO product VALUES ('AV-SB-02','BIRDS','Finch','<image src="../images/bird1.gif">Great stress reliever');

项目贴图:

 

 

 

 

    数据库操作代码

package petstore.dbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DataBaseConnection {

    private String DBDRIVER = "com.mysql.jdbc.Driver";
    private String DBURL = "jdbc:mysql://localhost:3306/jpetstore?characterEncoding=gbk";
    private String DBUSER = "root";
    private String DBPASSWORD = "";
    private Connection conn = null;

    public DataBaseConnection() {
        try {
            Class.forName(DBDRIVER);
            this.conn = DriverManager.getConnection(DBURL, DBUSER, DBPASSWORD);
        } catch (ClassNotFoundException e) {
            System.out.println("驱动程序不存在或名字写错");
            System.out.println(e.getMessage());
        } catch (SQLException e) {
            System.out.println("数据库操作错误");
            System.out.println(e.getMessage());
        }
    }

    public Connection getConnection() {
        return this.conn;
    }

    public void close() {
        try {
            this.conn.close();
        } catch (Exception e) {
        }
    }
};

 用到的实体类

package petstore.model;

import java.io.Serializable;


public class Category implements Serializable {

  private String categoryId;
  private String name;
  private String description;

  public String getCategoryId() {
    return categoryId;
  }

  public void setCategoryId(String categoryId) {
    this.categoryId = categoryId.trim();
  }

  public String getName() {
    return name;
  }

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

  public String getDescription() {
    return description;
  }

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

  

}
 
package petstore.model;

import java.io.Serializable;


public class Product implements Serializable {

  private String productId;
  private String categoryId;
  private String name;
  private String description;

  public String getProductId() {
    return productId;
  }

  public void setProductId(String productId) {
    this.productId = productId.trim();
  }

  public String getCategoryId() {
    return categoryId;
  }

  public void setCategoryId(String categoryId) {
    this.categoryId = categoryId;
  }

  public String getName() {
    return name;
  }

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

  public String getDescription() {
    return description;
  }

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

  public String toString() {
    return getName();
  }

}

 dao类:

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package petstore.dao;


import petstore.dbc.DataBaseConnection;
import petstore.model.Category;


import java.sql.* ;
import java.util.* ;


public class CategoryDao 
{
	// 增加操作
	
	// 查询全部
	public List<Category> findAll() throws Exception
	{
		List <Category>all = new ArrayList<Category>() ;
		String sql = "SELECT CatId,name,descn FROM Category" ;
		PreparedStatement pstmt = null ;
		DataBaseConnection dbc = null ;
		dbc = new DataBaseConnection() ;
		try
		{
			pstmt = dbc.getConnection().prepareStatement(sql) ;
			ResultSet rs = pstmt.executeQuery() ;
			while(rs.next())
			{
				Category Category = new Category() ;
				Category.setCategoryId(rs.getString(1)) ;
				Category.setName(rs.getString(2)) ;
				Category.setDescription(rs.getString(3)) ;
				all.add(Category) ;
			}
			rs.close() ;
			pstmt.close() ;
		}
		catch (Exception e)
		{
			System.out.println(e) ;
			throw new Exception("操作中出现错误!!!") ;
		}
		finally
		{
			dbc.close() ;
		}
		return all ;
	}
	// 模糊查询
	
};
 
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package petstore.dao;


import petstore.dbc.DataBaseConnection;
import petstore.model.Product;


import java.sql.* ;
import java.util.* ;


public class ProductDao 
{
	// 增加操作
	
	// 查询全部
	public List findAll() throws Exception
	{
		List all = new ArrayList() ;
		String sql = "SELECT productId,categoryId,name,description FROM Product" ;
		PreparedStatement pstmt = null ;
		DataBaseConnection dbc = null ;
		dbc = new DataBaseConnection() ;
		try
		{
			pstmt = dbc.getConnection().prepareStatement(sql) ;
			ResultSet rs = pstmt.executeQuery() ;
			while(rs.next())
			{
				Product Product = new Product() ;
				Product.setProductId(rs.getString(1)) ;
				Product.setCategoryId(rs.getString(2)) ;
				Product.setName(rs.getString(3)) ;
				Product.setDescription(rs.getString(4)) ;
				all.add(Product) ;
			}
			rs.close() ;
			pstmt.close() ;
		}
		catch (Exception e)
		{
			System.out.println(e) ;
			throw new Exception("操作中出现错误!!!") ;
		}
		finally
		{
			dbc.close() ;
		}
		return all ;
	}
        public List findProductByCategoryId(String id) throws Exception
	{
		List all = new ArrayList() ;
		String sql = "SELECT productId,category,name,descn FROM Product where category=? " ;
		PreparedStatement pstmt = null ;
		DataBaseConnection dbc = null ;
		dbc = new DataBaseConnection() ;
		try
		{
			pstmt = dbc.getConnection().prepareStatement(sql) ;
                        pstmt.setString(1, id);
			ResultSet rs = pstmt.executeQuery() ;
			while(rs.next())
			{
				Product product = new Product() ;
				product.setProductId(rs.getString(1)) ;
				product.setCategoryId(rs.getString(2)) ;
				product.setName(rs.getString(3)) ;
				product.setDescription(rs.getString(4)) ;
				all.add(product);
                                
			}
			rs.close() ;
			pstmt.close() ;
		}
		catch (Exception e)
		{
			System.out.println(e) ;
			throw new Exception("操作中出现错误!!!") ;
		}
		finally
		{
			dbc.close() ;
		}
		return all;
	}

	// 模糊查询
	
};

Struts 2的action:

package petstore.action.redirect;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

import petstore.dao.CategoryDao;
import petstore.dao.ProductDao;
import petstore.model.Category;
import petstore.model.Product;

public class ItemAddRedirectAction extends ActionSupport {

    private static final long serialVersionUID = 1L;

    public static final String GLOBAL_CATEGORY = "global_category_list"; // 宠物大类列表
    public static final String GLOBAL_DOUBLE_LIST = "global_double_list"; // 宠物类列表

    private ProductDao productDao=new ProductDao();
    private CategoryDao categoryDao=new CategoryDao() ;

    private List<Category> categorys;

    @SuppressWarnings("unchecked")
    private Map doubleMap = new HashMap();

    public List<Category> getCategorys() {
	return categorys;
    }

    public void setCategorys(List<Category> categorys) {
	this.categorys = categorys;
    }

    @SuppressWarnings("unchecked")
    public Map getDoubleMap() {
	return doubleMap;
    }

    @SuppressWarnings("unchecked")
    public void setDoubleMap(Map doubleMap) {
	this.doubleMap = doubleMap;
    }

    public void setProductDao(ProductDao productDao) {
	this.productDao = productDao;
    }

    public void setCategoryDao(CategoryDao categoryDao) {
	this.categoryDao = categoryDao;
    }

    @SuppressWarnings("unchecked")
    @Override
    public String execute() throws Exception {
	
	//优化数据库性能
	categorys = (List) ActionContext.getContext().getSession().get(
		GLOBAL_CATEGORY);

	if (categorys == null) {
	    categorys = categoryDao.findAll();
	    ActionContext.getContext().getSession().put(GLOBAL_CATEGORY,
		    categorys);

	}

	for (int i = 0; i < categorys.size(); i++) {

	    List<Product> products = productDao
		    .findProductByCategoryId(categorys.get(i).getCategoryId());

	    List c = new LinkedList();
	    for (int j = 0; j < products.size(); j++) {

		c.add(products.get(j));
	    }
	    doubleMap.put(categorys.get(i), c);
	}
	return SUCCESS;
    }
}


itemAdd.jsp文件:

 

<%@ page language="java" contentType="text/html; charset=GB18030"
pageEncoding="GB18030"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<title><s:text name="additem_page" /></title>
</head>


<body>
<s:actionerror />
<p id="title">
增加宠物
</p>
<s:form action="itemAddAction" enctype="multipart/form-data" name="itemAdd" id="itemAdd">
<s:doubleselect name="category" list="categorys" doubleName="product"
doubleList="doubleMap.get(top)"></s:doubleselect>
<s:submit key="submit"></s:submit><s:reset key="reset"></s:reset>
</s:form>
</body>
</html> 

需要注意:

<s:doubleselect name="category" list="categorys" doubleName="product"
doubleList="doubleMap.get(top)"></s:doubleselect>

doubleselect中的list属性是一个Arraylist  doublelist属性是一个HashMap

和ItemAddRedirectAction类中的下列代码对应

private List<Category> categorys;

  private Map doubleMap = new HashMap();

 

 

 

struts.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
        "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
        "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
    <include file="struts-default.xml"/>
    <package name="struts2" extends="struts-default">
      
    <action name="directItemAdd" class="petstore.action.redirect.ItemAddRedirectAction">
<result>/itemAdd.jsp</result>
</action> 
        
    </package>
</struts>
 

 

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <filter>
        <filter-name>struts2</filter-name>    
        <filter-class>org.apache.struts2.dispatcher.FilterDispatcher
        </filter-class>
    </filter>
    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
        </welcome-file-list>
    </web-app>

  运行图片:用iE才能看到

 

  • doubleselect.zip (4.3 MB)
  • 描述: 使用netbeans做的,请多提宝贵意见
  • 下载次数: 293
分享到:
评论
5 楼 sealksk 2009-04-26  
itemAdd.jsp页面里,form action="itemAddAction",而struts.xml里,action name="directItemAdd",两个action名字不一样,不知道是不是楼主写错了?

另在itemAdd.jsp里,我试的时候,页面有错误:The attribute prefix COLOR does not correspond to any imported tag library。我把span都删除后,又报这个错:org.apache.jasper.JasperException: tag 'doubleselect', field 'list', name 'category': The requested list key 'categorys' could not be resolved as a collection/array/map/enumeration/iterator type

我用的是myeclipse做的。
BTW:用IE还是看不到图,不知道是不是自己RP有问题了
4 楼 zhang__lei 2009-04-25  
我做的怎么报错呢。是网页上有个错误
找不到哪的错。代码如下

items = this.getItemManager().queryAll();
for(int i=0; i<items.size(); i++){
item = items.get(i);
subitems = item.getSubitems();
List<Subitem> c = new LinkedList<Subitem>();
Iterator iter = subitems.iterator();
while(iter.hasNext()){
c.add((Subitem)iter.next());

}
doubleMap.put(items.get(i), c);
}
return SUCCESS;


<s:doubleselect doubleList="doubleMap.get(top)" doubleName="subitemname" doubleListValue="subitemname"
name="itemname" list="items" listValue="itemname" formName="form1"></s:doubleselect>
3 楼 bruno 2009-03-19  
lz你好,我按照你这个做了,可结果报错
tag 'doubleselect', field 'list', name 'province': The requested list key 'provinces' could not be resolved as a collection/array/map/enumeration/iterator type. Example: people or people.{name} - [unknown location]
org.apache.struts2.components.Component.fieldError(Component.java:230)
org.apache.struts2.components.Component.findValue(Component.java:351)
org.apache.struts2.components.ListUIBean.evaluateExtraParams(ListUIBean.java:80)
org.apache.struts2.components.DoubleListUIBean.evaluateExtraParams(DoubleListUIBean.java:96)
org.apache.struts2.components.DoubleSelect.evaluateExtraParams(DoubleSelect.java:61)
org.apache.struts2.components.UIBean.evaluateParams(UIBean.java:856)
org.apache.struts2.components.UIBean.end(UIBean.java:510)
org.apache.struts2.views.jsp.ComponentTagSupport.doEndTag(ComponentTagSupport.java:42)
org.apache.jsp.jsps.search3_jsp._jspx_meth_s_doubleselect_0(search3_jsp.java:269)
org.apache.jsp.jsps.search3_jsp._jspx_meth_s_form_0(search3_jsp.java:215)
org.apache.jsp.jsps.search3_jsp._jspService(search3_jsp.java:133)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:97)
javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:334)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:314)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:264)
javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
org.apache.struts2.dispatcher.FilterDispatcher.doFilter(FilterDispatcher.java:389)
com.carsearch.struts.filter.SetCharacterEncodingFilter.doFilter(SetCharacterEncodingFilter.java:122)

jsp里的 <s:form action="itemAddAction"
和struts2里的<action name="directItemAdd"   有什么关联吗  怎么访问到action呢?
2 楼 wanglihu 2008-11-05  
看你做struts2有经验了,能不能提供我关于<s:optiontransferselect>的具体示例啊?
十分感谢!
我的QQ:317666833
急待你的回复!
1 楼 王者之剑 2008-09-01  
用iBatis吧,数据访问会简单很多

相关推荐

    struts2中doubleselect标签的应用

    通过上述分析,我们可以看到Struts2中的`doubleselect`标签是一个非常有用的工具,它可以简化前端页面上多级选择框的设计与实现。同时,通过与Hibernate和Spring框架的整合,可以实现从前端到后端整个流程的自动化...

    struts2 标签 doubleselect动态 用法

    `doubleselect`标签是Struts2提供的一个特殊标签,用于创建具有两个级联选择框的用户界面,通常用于父类别与子类别之间的关联选择,如在上述例子中的部门与人员选择。 在`doubleselect`标签中,`list`属性用于指定...

    Struts2级联doubleselect

    在Struts2级联doubleselect的实现中,主要涉及以下几个关键知识点: 1. **Action类**:Action类是业务逻辑的载体,通常包含获取和设置属性的方法,用于处理请求和返回结果。在级联doubleselect中,Action类会处理两...

    struts2 doubleselect标签的用法例子

    在"struts2 doubleselect标签的用法例子"中,我们将探讨如何实现这个功能。首先,我们需要理解`doubleselect`标签的基本结构和属性。`doubleselect`标签通常包含两个部分:父级选择器和子级选择器,它们之间的关联...

    Struts2的doubleselect标签演示

    在Struts2框架中,`doubleselect`标签是用于创建一对多选择的HTML元素,通常表现为两个下拉列表,其中一个选项的选择会影响到另一个下拉列表的选项显示。这个标签使得用户在前端界面可以方便地进行关联数据的选择,...

    j2ee-struts2-Select_DoubleSelect.rar_struts2 doubleselect

    Struts2作为Java EE应用程序开发中的一个流行框架,极大地简化了MVC(模型-视图-控制器)架构的实现。在Struts2中,我们有许多内置的标签来帮助开发者更方便地处理表单元素,例如`&lt;s:select&gt;`和`&lt;s:doubleselect&gt;`...

    struts2中的doubleSelect标签的用法(从数据库中读取数据,HSS)

    综上所述,通过整合Hibernate、Struts2和Spring三个框架,我们可以实现从数据库中读取数据,并利用Struts2中的`doubleSelect`标签来展示数据的功能。这种技术不仅提高了开发效率,而且增强了用户体验。开发者可以...

    struts2 doubleselect 实例

    Struts2 Doubleselect标签是用于创建二级联动下拉列表的,这种控件在网页表单中常见于需要显示层次关系数据的场景,例如省份-城市的选择。Doubleselect标签结合了两个下拉列表,其中一个的选择会影响到另一个下拉...

    struts2地市、县区二级联动下拉菜单 doubleselect标签

    在Struts2中,`doubleselect`标签就是为了解决这类问题而设计的。 `doubleselect`标签是Struts2自定义标签库的一部分,它允许开发者创建两个相关的下拉列表,当用户在第一个下拉框选择一个选项时,第二个下拉框的...

    doubleselect实现

    doubleselect实现doubleselect实现doubleselect实现doubleselect实现doubleselect实现doubleselect实现doubleselect实现doubleselect实现doubleselect实现doubleselect实现doubleselect实现doubleselect实现...

    Struts2-Double-Select-Example

    "Struts2-Double-Select-Example"这个项目是Struts2框架的一个实例,用于演示如何在Web表单中实现双层选择框功能,这在处理复杂数据关联和用户选择时非常有用。 首先,我们需要了解Struts2框架的核心组件和工作原理...

    extjs+struts2省市区三级联动完整示例

    这个示例适用于需要在Web应用程序中实现地理区域选择功能的情况,例如用户地址输入。以下是对该技术栈及其实现方法的详细说明。 首先,ExtJS是一个强大的JavaScript库,用于构建富客户端应用程序。它提供了丰富的...

    struts2源代码分析

    Struts2的视图组件被封装在`org.apache.struts2.components`包中,包括了许多增强的组件,如updownselect、doubleselect、datetimepicker等,这些组件增强了用户界面的功能和交互性。此外,Struts2支持主题(Theme)...

    Struts2源码分析

    在视图层,Struts2提供了一系列增强的组件,位于`org.apache.struts2.components`包中,包括updownselect、doubleselect、datetimepicker、token、tree等,这些组件增强了用户体验,并且支持主题(theme)以自定义...

    struts2 Action 包 命名空间 servlet API

    1. `org.apache.struts2.components`:包含了视图组件,如UI标签,增强了Struts1.x的功能,新增了多种组件,如updownselect、doubleselect等,并支持主题(theme)以定制页面样式。 2. `org.apache.struts2.config`...

    doubleselect.doc

    ### Struts2中doubleselect标签实现省市联动案例详解 #### 一、背景介绍 在Web应用开发中,经常需要处理一些具有层级关系的数据选择问题,比如中国的省市县选择。为了提高用户体验并简化开发过程,Struts2框架提供...

    Struts2工作机制

    Struts2提供了丰富的视图组件,如`updownselect`、`doubleselect`、`datetimepicker`等,这些组件可以通过主题(theme)定制样式,使得视图的外观更加统一和美观。 总的来说,Struts2的工作流程大致为:请求到达-&gt;...

    Struts2的总结和Strut2集成Spring

    #### Struts2中实现动态Action 动态Action允许开发者根据传入的参数执行不同的方法,这提高了代码的灵活性和重用性。例如,可以设计一个`UserAction`类,通过传递参数`method`来调用不同的方法,如`list()`, `edit...

Global site tag (gtag.js) - Google Analytics