Struts 简单总结 图书数据库添加图书

08/29/2010

Struts 学习已经告一个段落,现在我们运用之前学习的知识做一个小的总结,完成一个示例小程序:图书管理系统的图书添加操作!
(1)图书类型为下拉框,其中的数据来自“图书类别表”;
(2)图书封面可以上传一个图片文件;
(3)提交后将图书名称、图书单价、图书类型、图片名称 保存到数据库中,库结构自定义;
(4)将图书封面保存到网站中的一个文件夹中;
(5)参考界面如下,可以根据需要在表单中添加其它的图书信息:
addbook

(1)数据库结构

  • 图书类别TABLE
  • DROP TABLE IF EXISTS `type`;
    CREATE TABLE `type` (
      `typeId` int(11) NOT NULL auto_increment,
      `typeName` varchar(100) NOT NULL,
      PRIMARY KEY  (`typeId`)
    ) ENGINE=MyISAM
    INSERT INTO `type` VALUES (1,'数据库编程');
    INSERT INTO `type` VALUES (2,'JAVA编程');
    INSERT INTO `type` VALUES (3,'.NET编程');
  • 图书内容表
  • DROP TABLE IF EXISTS `book`;
    CREATE TABLE `book` (
      `bookId` int(11) NOT NULL auto_increment,
      `bookName` varchar(100) NOT NULL,
      `bookPrice` decimal(18,0) NOT NULL,
      `bookType` int(11) NOT NULL,
      `bookImage` varchar(100) NOT NULL default 'default.gif',
      PRIMARY KEY  (`bookId`),
      KEY `foreignkey_booktype_type` (`bookType`)
    ) ENGINE=MyISAM

(2)根据数据库建立相应的实体BEAN

  • BookType.java
  • package cn.net.royakon.entity;
    
    public class BookType {
    
    	private int typeId;
    	private String typeName;
    
    	public int getTypeId() {
    		return typeId;
    	}
    	public void setTypeId(int typeId) {
    		this.typeId = typeId;
    	}
    	public String getTypeName() {
    		return typeName;
    	}
    	public void setTypeName(String typeName) {
    		this.typeName = typeName;
    	}
    }
  • Book.java
  • package cn.net.royakon.entity;
    
    import org.apache.struts.upload.FormFile;
    
    public class Book {
    
    	private int bookId;
    	private String bookName;
    	private double bookPrice;
    	private int bookType;
    	private String bookImageName;
    	//FormFile 类型的属性为冗余的属性,为了上传图书保存图片文件信息建立
    	private FormFile bookImage;
    	public int getBookId() {
    		return bookId;
    	}
    	public void setBookId(int bookId) {
    		this.bookId = bookId;
    	}
    	public String getBookName() {
    		return bookName;
    	}
    	public void setBookName(String bookName) {
    		this.bookName = bookName;
    	}
    	public double getBookPrice() {
    		return bookPrice;
    	}
    	public void setBookPrice(double bookPrice) {
    		this.bookPrice = bookPrice;
    	}
    	public int getBookType() {
    		return bookType;
    	}
    	public void setBookType(int bookType) {
    		this.bookType = bookType;
    	}
    	public String getBookImageName() {
    		return bookImageName;
    	}
    	public void setBookImageName(String bookImageName) {
    		this.bookImageName = bookImageName;
    	}
    	public FormFile getBookImage() {
    		return bookImage;
    	}
    	public void setBookImage(FormFile bookImage) {
    		this.bookImage = bookImage;
    	}
    
    }

(3)数据库连接DAO利用 《优化的 JAVA 通用数据库dao》
(4)数据库操作Model

package cn.net.royakon.model;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.jsp.jstl.sql.Result;

import cn.net.royakon.dao.GenericDao;
import cn.net.royakon.entity.Book;
import cn.net.royakon.entity.BookType;

public class BookModel extends GenericDao{
	/**
	 * 添加图书到数据库
	 * @param book
	 * @return
	 */
	public int addBook(Book book) {
		//设定添加语句的SQL
		String sqlValue = "insert into books.book values( null, ? , ? , ? , ? )";
		super.setSqlValue(sqlValue);

		//设定商品信息的参数
		List values = new ArrayList();
		values.add(book.getBookName());
		values.add(book.getBookPrice());
		values.add(book.getBookType());
		values.add(book.getBookImageName());
		super.setValues(values);

		//添加商品
		int result = 0;
		try {
			result = super.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
		}

		//返回受影响的行数,0为添加失败
		return result;
	}

	/**
	 * 得到图书类型的集合
	 * @return
	 */
	public List getBookType() {
		List bookTypeList = new ArrayList();
		String sql = "select * from books.type";
		super.setSqlValue(sql);
		try {
			Result rs = super.executeQuery();
			for(int i=0;i<rs.getRowCount();i++) {
				Map record = rs.getRows()[i];
				BookType bookType = new BookType();
				bookType.setTypeId((Integer)record.get("typeId"));
				bookType.setTypeName((String)record.get("typeName"));
				bookTypeList.add(bookType);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return bookTypeList;
	}

}

(5)编写添加图书的VIEW层代码 addbook.jsp

<%@ page language="java" pageEncoding="GB18030"%>

<%@ 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" %>
<%@ taglib uri="http://struts.apache.org/tags-tiles" prefix="tiles" %>

<!--
	载入页面时判断 REQUEST 作用域是否存在 图书类别的集合
	如果不存在就调用 取得图书类型 的 ACTION
-->
<logic:notPresent scope="request" name="bookTypeList">
	<jsp:forward page="/getBookType.do"></jsp:forward>
</logic:notPresent>

<h2 align="center">添加图书</h2>
<!--
	如果表单需要上传 非文本信息需要:
	enctype="multipart/form-data"
 -->
<html:form action="addBook.do" method="post" enctype="multipart/form-data">
<table border="0" align="center">
	<tr>
		<th colspan="2">添加图书</th>
	</tr>
	<tr>
		<td>图书名称</td>
		<!-- 绑定 ActionForm 属性 -->
		<td><html:text property="book.bookName"></html:text></td>
	</tr>
	<tr>
		<td>图书单价</td>
		<!-- 绑定 ActionForm 属性 -->
		<td><html:text property="book.bookPrice"></html:text></td>
	</tr>
	<tr>
		<td>图书类型</td>
		<td>
			<!-- 绑定 ActionForm 属性 -->
			<html:select property="book.bookType" size="1">
				<!--
					optionsCollection 标签 列表 select 项
				 	name=列表集合
				 	value=Struts 将自动回溯 列表内 对象 的属性 图书类型ID  作为列表值
				 	label=Struts 将自动回溯 列表内 对象 的属性 图书类型名称 作为列表显示标签
				 -->
				<html:optionsCollection value="typeId" label="typeName" name="bookTypeList" />
			</html:select>
		</td>
	</tr>
	<tr>
		<td>图书封面</td>
		<!-- 绑定 ActionForm 属性 -->
		<td><html:file property="book.bookImage" /></td>
	</tr>
	<tr>
		<td><html:submit>确定</html:submit></td>
		<td><html:reset>重置</html:reset></td>
	</tr>
</table>
</html:form>

(6)取得图书类别集合的 ACTION

/**
 * Generated by MyEclipse Struts
 * Template path: templates/java/JavaClass.vtl
 */
package cn.net.royakon.action;

import java.util.List;

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;

import cn.net.royakon.model.BookModel;

public class GetBookTypeAction extends Action {
	/**
	 * 取得图书类别集合并存入 REQUEST 作用域的 ACTION
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return ActionForward
	 */
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		BookModel bookModel = new BookModel();
		List bookTypeList = bookModel.getBookType();
		//取得图书类型集合 并保存至 REQUEST 作用域
		request.setAttribute("bookTypeList", bookTypeList);
		//跳转回调用的页面
		return mapping.findForward("result");
	}
}

(7)提交添加图书页面的ActionForm

/**
 * Generated by MyEclipse Struts
 * Template path: templates/java/JavaClass.vtl
 */
package cn.net.royakon.form;

import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import cn.net.royakon.entity.Book;

/**
 * MyEclipse Struts
 * Creation date: 01-06-2009
 *
 * XDoclet definition:
 * @struts.form name="bookForm"
 */
public class BookForm extends ActionForm {
	/**
	 * Generated fields
	 */

	/** 对象作为 ActionForm 的属性 需要实例化*/
	private Book book = new Book();

	/**
	 * Generated Methods
	 */

	/**
	 * Method validate
	 * @param mapping
	 * @param request
	 * @return ActionErrors
	 */
	public ActionErrors validate(ActionMapping mapping,
			HttpServletRequest request) {
		// TODO Auto-generated method stub
		return null;
	}

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

	/**
	 * Returns the book.
	 * @return Book
	 */
	public Book getBook() {
		return book;
	}

	/**
	 * Set the book.
	 * @param book The book to set
	 */
	public void setBook(Book book) {
		this.book = book;
	}
}

(8)添加图书信息的Action

/**
 * Generated by MyEclipse Struts
 * Template path: templates/java/JavaClass.vtl
 */
package cn.net.royakon.action;

import java.io.File;
import java.io.FileOutputStream;

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;
import org.apache.struts.upload.FormFile;

import cn.net.royakon.entity.Book;
import cn.net.royakon.form.BookForm;
import cn.net.royakon.model.BookModel;

public class AddBookAction extends Action {
	/**
	 * 添加图书数据到数据库
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return ActionForward
	 */
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		BookForm bookForm = (BookForm) form;
		// TODO Auto-generated method stub
		int result = 0;
		Book book = new Book();
		book = bookForm.getBook();
		try {
			//为图书名称重新设置编码
			book.setBookName(new String(book.getBookName().getBytes("iso8859-1"),"gb2312"));
			//保存图书封面
			FormFile photo= book.getBookImage();
			//得到文件名
			book.setBookImageName(photo.getFileName());
			String path=this.servlet.getServletConfig().getServletContext().getRealPath("/photos");
			//生成文件输出流
			FileOutputStream file_out=new FileOutputStream(path + File.separator + book.getBookImageName());
			file_out.write(photo.getFileData());
			file_out.close();
			//销毁内存中的文件
			photo.destroy();
			//调用 Model 添加图书信息
			BookModel bookModel = new BookModel();
			result = bookModel.addBook(book);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (result==0) {
			return mapping.findForward("fail");
		}
		request.setAttribute("book", book);
		return mapping.findForward("ok");
	}
}

(9)添加成功后的跳转页面 result.jsp

<%@ page language="java" pageEncoding="GB18030"%>
<h2 align="center">添加图书成功!</h2>
<table border="0" align="center">
	<tr>
		<th colspan="2">添加图书成功</th>
	</tr>
	<tr>
		<td>图书名称</td>
		<td>${book.bookName}"</td>
	</tr>
	<tr>
		<td>图书单价</td>
		<td>${book.bookPrice}</td>
	</tr>
	<tr>
		<td>图书类型</td>
		<td>${book.bookType}</td>
	</tr>
	<tr>
		<td>图书封面</td>
		<td><img src="photos/${book.bookImageName}" /></td>
	</tr>
</table>