论坛首页 Java企业应用论坛

struts 2 中的doubleselect(jdbc实现)

浏览 6454 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2008-08-29  

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
   发表时间:2008-09-01  
用iBatis吧,数据访问会简单很多
0 请登录后投票
   发表时间: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>
  • 大小: 194.7 KB
0 请登录后投票
   发表时间: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有问题了
0 请登录后投票
论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics