繁体中文
设为首页
加入收藏
当前位置:JSP技术首页 >> 资料/其它 >> 一个Struts实现分页,增删改查,Tiles,国际化的DEMO

一个Struts实现分页,增删改查,Tiles,国际化的DEMO

2005-02-15 08:00:00  作者:  来源:互联网  浏览次数:0  文字大小:【】【】【
简介:这个DEMO供大家一起探讨学习Struts,因为工作太累,没精力给大家解释实现原理。如果看不懂,没关系。只是说明JSP基础还没有到火候,不要心急,回去强化下JSP+Servlet,基础扎实了,自然能够看懂我写的代码。这个D...
关键字:Struts 一个 Tiles DEMO

这个DEMO供大家一起探讨学习Struts,因为工作太累,没精力给大家解释实现原理。如果看不懂,没关系。只是说明JSP基础还没有到火候,不要心急,回去强化下JSP+Servlet,基础扎实了,自然能够看懂我写的代码。这个DEMO借鉴了网上很多前人的经验,在此一并谢谢。

web.xml文件:

http://java.sun.com/dtd/web-app_2_3.dtd">

BookShopMod

action

org.apache.struts.action.ActionServlet

config

/WEB-INF/struts-config.xml

debug

2

application

ApplicationResources

2

action

*.do

index.jsp

index.htm

/WEB-INF/struts-bean.tld

/WEB-INF/struts-bean.tld

/WEB-INF/struts-html.tld

/WEB-INF/struts-html.tld

/WEB-INF/struts-logic.tld

/WEB-INF/struts-logic.tld

/WEB-INF/struts-template.tld

/WEB-INF/struts-template.tld

/WEB-INF/struts-tiles.tld

/WEB-INF/struts-tiles.tld

/WEB-INF/struts-nested.tld

/WEB-INF/struts-nested.tld

/WEB-INF/camel-define.tld

/WEB-INF/camel-define.tld

Struts-config.xml文件:

http://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd">

tiles-defs文件:

http://jakarta.apache.org/struts/dtds/tiles-config_1_1.dtd">

camel-define文件:

http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd">

1.0

1.1

camel

http://jakarta.apache.org/struts/tags-bean

isLastPage

com.bookshop.util.IsLastTag

JSP

page

true

true

上面几个文件和struts-bean.tld,struts-html.tld,struts-tiles.tld,struts-logic.tld都一起位于WEB-INF的根目录下面。

以下是三个Action文件:

/*FindRecordAction.java*/

package com.bookshop.action;

import org.apache.struts.action.ActionMapping;

import org.apache.struts.action.ActionForm;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForward;

import com.bookshop.form.FindRecordForm;

import org.apache.struts.action.Action;

import java.util.List;

import java.util.ArrayList;

import com.bookshop.model.Operator;

import com.bookshop.util.PageInfo;

import org.apache.struts.action.ActionErrors;

import org.apache.struts.action.ActionError;

public class FindRecordAction

extends Action {

public ActionForward execute(ActionMapping actionMapping,

ActionForm actionForm,

HttpServletRequest servletRequest,

HttpServletResponse servletResponse) {

FindRecordForm findRecordForm = (FindRecordForm) actionForm;

String key = findRecordForm.getFindByKey().trim();

String value = findRecordForm.getFindByValue().trim();

List list = new ArrayList();

list = Operator.getRecords(key, value, 0);

servletRequest.getSession().setAttribute("books", list);

if (!list.isEmpty()) {

servletRequest.getSession().setAttribute("pageinfo",

new PageInfo(Operator.

getRecordsNumber(), 1));

}

else {

ActionErrors messages = new ActionErrors();

messages.add(ActionErrors.GLOBAL_MESSAGE,

new ActionError("findrecord.jsp.notfound"));

servletRequest.getSession().setAttribute("pageinfo",

new PageInfo(0, 1));

}

return actionMapping.findForward("browser");

}

}

/*GenericAction.java*/

package com.bookshop.action;

import org.apache.struts.action.ActionMapping;

import org.apache.struts.action.ActionForm;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForward;

import org.apache.struts.actions.DispatchAction;

import org.apache.struts.action.ActionErrors;

import org.apache.struts.action.ActionError;

public class GenericAction

extends DispatchAction {

/*

public ActionForward execute(ActionMapping actionMapping,

ActionForm actionForm,

HttpServletRequest servletRequest,

HttpServletResponse servletResponse) {

throw new java.lang.UnsupportedOperationException(

"Method $execute() not yet implemented.");

}

*/

public void saveGlobalErrors(HttpServletRequest httpServletRequest,

String errorKey) {

ActionErrors errors = new ActionErrors();

errors.add(ActionErrors.GLOBAL_ERROR, new ActionError(errorKey));

if (errors != null) {

saveErrors(httpServletRequest, errors);

}

}

public ActionForward getIndexForward(ActionMapping actionMapping) {

return actionMapping.findForward("index");

}

public ActionForward getBrowserForward(ActionMapping actionMapping) {

return actionMapping.findForward("browser");

}

public ActionForward showDeleteForward(ActionMapping actionMapping) {

return actionMapping.findForward("showDelete");

}

public ActionForward getOperatorOkForward(ActionMapping actionMapping) {

return actionMapping.findForward("operatorok");

}

public ActionForward getErrorForward(ActionMapping actionMapping) {

return actionMapping.findForward("global_error");

}

public ActionForward getShowAddForward(ActionMapping actionMapping) {

return actionMapping.findForward("showAddRecord");

}

public ActionForward getShowModifyForward(ActionMapping actionMapping) {

return actionMapping.findForward("showModifyRecord");

}

public ActionForward getShowDeleteForward(ActionMapping actionMapping) {

return actionMapping.findForward("showDeleteRecord");

}

public ActionForward getShowFindForward(ActionMapping actionMapping) {

return actionMapping.findForward("showFindRecord");

}

}

/*OperatorAction.java*/

package com.bookshop.action;

import org.apache.struts.action.ActionMapping;

import org.apache.struts.action.ActionForm;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForward;

import com.bookshop.form.OperatorForm;

import org.apache.struts.action.Action;

import java.util.List;

import org.apache.struts.Globals;

import com.bookshop.util.DBUtil;

import com.bookshop.util.ApplicationUtil;

import com.bookshop.model.Operator;

import java.util.ArrayList;

import com.bookshop.util.PageInfo;

import org.apache.struts.actions.DispatchAction;

import java.util.Map;

import java.util.HashMap;

import com.bookshop.form.BookForm;

import java.util.Locale;

import org.apache.struts.action.ActionErrors;

import org.apache.struts.action.ActionError;

import com.bookshop.util.BookBean;

public class OperatorAction

extends GenericAction {

/*

public ActionForward execute(ActionMapping actionMapping,

ActionForm actionForm,

HttpServletRequest servletRequest,

HttpServletResponse servletResponse) {

throw new java.lang.UnsupportedOperationException(

"Method $execute() not yet implemented.");

}

*/

//转换为中文页面

public ActionForward ChangeCH(ActionMapping actionMapping,

ActionForm actionForm,

HttpServletRequest servletRequest,

HttpServletResponse servletResponse) {

servletRequest.getSession().setAttribute(Globals.LOCALE_KEY, Locale.CHINA);

return this.getIndexForward(actionMapping);

}

//转换为英文页面

public ActionForward ChangeEN(ActionMapping actionMapping,

ActionForm actionForm,

HttpServletRequest servletRequest,

HttpServletResponse servletResponse) {

servletRequest.getSession().setAttribute(Globals.LOCALE_KEY, Locale.ENGLISH);

return this.getIndexForward(actionMapping);

}

//链接到首页记录

public ActionForward showFirstPage(ActionMapping actionMapping,

ActionForm actionForm,

HttpServletRequest httpServletRequest,

HttpServletResponse httpServletResponse) {

List list = new ArrayList();

list = Operator.getRecords(0);

httpServletRequest.getSession().setAttribute("books", list);

httpServletRequest.getSession().setAttribute("pageinfo",

new PageInfo(Operator.

getRecordsNumber(), 1));

return this.getBrowserForward(actionMapping);

}

//链接到上一页记录

public ActionForward showPreviousPage(ActionMapping actionMapping,

ActionForm actionForm,

HttpServletRequest httpServletRequest,

HttpServletResponse httpServletResponse) {

List list = new ArrayList();

PageInfo pageInfo = (PageInfo) httpServletRequest.getSession().getAttribute(

"pageinfo");

list = Operator.getRecords( (pageInfo.getPreviousPageNumber() - 1) *

ApplicationUtil.recordPerPage);

httpServletRequest.getSession().setAttribute("books", list);

httpServletRequest.getSession().setAttribute("pageinfo",

new PageInfo(Operator.

getRecordsNumber(), pageInfo.getPreviousPageNumber()));

return this.getBrowserForward(actionMapping);

}

//链接到下一页记录

public ActionForward showNextPage(ActionMapping actionMapping,

ActionForm actionForm,

HttpServletRequest httpServletRequest,

HttpServletResponse httpServletResponse) {

List list = new ArrayList();

PageInfo pageInfo = (PageInfo) httpServletRequest.getSession().getAttribute(

"pageinfo");

list = Operator.getRecords(pageInfo.getCurrentlyPage() *

ApplicationUtil.recordPerPage);

httpServletRequest.getSession().setAttribute("books", list);

httpServletRequest.getSession().setAttribute("pageinfo",

new PageInfo(Operator.

getRecordsNumber(), pageInfo.getNextPageNumber()));

return this.getBrowserForward(actionMapping);

}

//链接到末页记录

public ActionForward showLastPage(ActionMapping actionMapping,

ActionForm actionForm,

HttpServletRequest httpServletRequest,

HttpServletResponse httpServletResponse) {

List list = new ArrayList();

PageInfo pageInfo = (PageInfo) httpServletRequest.getSession().getAttribute(

"pageinfo");

list = Operator.getRecords( (pageInfo.getPageCountNumber() - 1) *

ApplicationUtil.recordPerPage);

httpServletRequest.getSession().setAttribute("books", list);

httpServletRequest.getSession().setAttribute("pageinfo",

new PageInfo(Operator.

getRecordsNumber(), pageInfo.getLastPageNumber()));

return this.getBrowserForward(actionMapping);

}

//取消操作的转向

public ActionForward cancel(ActionMapping actionMapping,

ActionForm actionForm,

HttpServletRequest httpServletRequest,

HttpServletResponse httpServletResponse) {

if (isCancelled(httpServletRequest)) {

return this.getOperatorOkForward(actionMapping);

}

return null;

}

//查看所有记录

public ActionForward browser(ActionMapping actionMapping,

ActionForm actionForm,

HttpServletRequest httpServletRequest,

HttpServletResponse httpServletResponse) {

return this.showFirstPage(actionMapping, actionForm, httpServletRequest,

httpServletResponse);

}

//执行添加记录

public ActionForward addRecord(ActionMapping actionMapping,

ActionForm actionForm,

HttpServletRequest httpServletRequest,

HttpServletResponse httpServletResponse) {

BookForm bookForm = (BookForm) actionForm;

if (Operator.addRecord(bookForm.loadBook()) >= 1) {

return this.getOperatorOkForward(actionMapping);

}

else {

this.saveGlobalErrors(httpServletRequest, "editrecord.jsp.adderror");

return this.getErrorForward(actionMapping);

}

}

//提交更新操作

public ActionForward SubmitRecord(ActionMapping actionMapping,

ActionForm actionForm,

HttpServletRequest httpServletRequest,

HttpServletResponse httpServletResponse) {

String str = (String) httpServletRequest.getSession().getAttribute("method");

if (str.equals("addRecord")) {

return addRecord(actionMapping, actionForm, httpServletRequest,

httpServletResponse);

}

if (str.equals("modifyRecord")) {

return modifyRecord(actionMapping, actionForm, httpServletRequest,

httpServletResponse);

}

else {

this.saveGlobalErrors(httpServletRequest, "edit.body.error");

return this.getErrorForward(actionMapping);

}

}

//执行修改操作

public ActionForward modifyRecord(ActionMapping actionMapping,

ActionForm actionForm,

HttpServletRequest httpServletRequest,

HttpServletResponse httpServletResponse) {

BookForm bookForm = (BookForm) actionForm;

if (Operator.modifyRecord(bookForm.loadBook()) != -1) {

return this.getOperatorOkForward(actionMapping);

}

else {

this.saveGlobalErrors(httpServletRequest, "editrecord.jsp.modifyerror");

return this.getErrorForward(actionMapping);

}

}

//跳转到添加记录编辑页面

public ActionForward showAdd(ActionMapping actionMapping,

ActionForm actionForm,

HttpServletRequest httpServletRequest,

HttpServletResponse httpServletResponse) {

httpServletRequest.getSession().setAttribute("bookBean", new BookForm());

httpServletRequest.getSession().setAttribute("method",

new String("addRecord"));

return this.getShowAddForward(actionMapping);

}

//跳转到修改记录编辑页面

public ActionForward showModify(ActionMapping actionMapping,

ActionForm actionForm,

HttpServletRequest httpServletRequest,

HttpServletResponse httpServletResponse) {

BookBean book = new BookBean();

String str = httpServletRequest.getParameter("bookid").toString();

book = Operator.getRecord(str);

httpServletRequest.getSession().setAttribute("bookBean",

new BookForm(book.getBookId(),

book.getBookName(), book.getAuthor(), book.getPublish(), book.getPrice()));

httpServletRequest.getSession().setAttribute("method",

new String("modifyRecord"));

return this.getShowModifyForward(actionMapping);

}

//删除记录

public ActionForward showDelete(ActionMapping actionMapping,

ActionForm actionForm,

HttpServletRequest httpServletRequest,

HttpServletResponse httpServletResponse) {

String str = httpServletRequest.getParameter("bookid").toString();

if (Operator.deleteRecord(str) != -1) {

return this.getOperatorOkForward(actionMapping);

}

else {

this.saveGlobalErrors(httpServletRequest, "edit.body.error");

return this.getErrorForward(actionMapping);

}

}

public ActionForward showFind(ActionMapping actionMapping,

ActionForm actionForm,

HttpServletRequest httpServletRequest,

HttpServletResponse httpServletResponse) {

//传递参数

httpServletRequest.getSession().setAttribute("bookBean", new BookForm());

httpServletRequest.getSession().setAttribute("method",

new String("findRecord"));

return this.getShowFindForward(actionMapping);

}

}

以下是三个ActionForm文件:

package com.bookshop.form;

import org.apache.struts.action.ActionForm;

import org.apache.struts.action.ActionErrors;

import org.apache.struts.action.ActionError;

import org.apache.struts.action.ActionMapping;

import javax.servlet.http.HttpServletRequest;

import java.util.Map;

import java.util.HashMap;

public class BookForm

extends ActionForm {

private String author;

private String bookId;

private String bookName;

private String price;

private String publish;

private String beanId;

public BookForm() {

this.bookId = "";

this.bookName = "";

this.author = "";

this.publish = "";

this.price = "";

this.beanId = "";

}

public BookForm(String id, String name, String author, String publish,

String price) {

this.bookId = id;

this.bookName = name;

this.author = author;

this.publish = publish;

this.price = price;

this.beanId = id;

}

public String getAuthor() {

return author;

}

public void setAuthor(String author) {

this.author = author;

}

public void setPublish(String publish) {

this.publish = publish;

}

public void setPrice(String price) {

this.price = price;

}

public void setBookName(String bookName) {

this.bookName = bookName;

}

public void setBookId(String bookId) {

this.bookId = bookId;

}

public String getBookId() {

return bookId;

}

public String getBookName() {

return bookName;

}

public String getPrice() {

return price;

}

public String getPublish() {

return publish;

}

public String getBeanId() {

return this.beanId;

}

public void setBeanId(String beanId) {

this.beanId = beanId;

}

public Map loadBook() {

Map record = new HashMap();

record.put("column1", this.getBookId().trim());

record.put("column2", this.getBookName().trim());

record.put("column3", this.getAuthor().trim());

record.put("column4", this.getPublish().trim());

record.put("column5", this.getPrice().trim());

return record;

}

public ActionErrors validate(ActionMapping actionMapping,

HttpServletRequest httpServletRequest) {

ActionErrors errors = new ActionErrors();

if (this.bookId == null || this.bookId.equals("") ||

this.bookId.length() < 1) {

errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("book.bookid.error"));

}

if (this.bookName == null || this.bookName.equals("") ||

this.bookName.length() < 1) {

errors.add(ActionErrors.GLOBAL_ERROR,

new ActionError("book.bookname.error"));

}

if (this.author == null || this.author.equals("") ||

this.author.length() < 1) {

errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("book.author.error"));

}

if (this.publish == null || this.publish.equals("") ||

this.publish.length() < 1) {

errors.add(ActionErrors.GLOBAL_ERROR,

new ActionError("book.publish.error"));

}

// if ( (Float.isNaN(this.price)) && (this.price < 0)) {

if ( (Float.isNaN(Float.parseFloat(this.price))) &&

(Float.parseFloat(this.price) < 0)) {

errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("book.price.error"));

}

return errors;

}

}

/**/

package com.bookshop.form;

import org.apache.struts.action.ActionForm;

import org.apache.struts.action.ActionErrors;

import org.apache.struts.action.ActionError;

import org.apache.struts.action.ActionMapping;

import javax.servlet.http.HttpServletRequest;

public class FindRecordForm

extends ActionForm {

private String findByKey;

private String findByValue;

public String getFindByKey() {

return findByKey;

}

public void setFindByKey(String findByKey) {

this.findByKey = findByKey;

}

public void setFindByValue(String findByValue) {

this.findByValue = findByValue;

}

public String getFindByValue() {

return findByValue;

}

public ActionErrors validate(ActionMapping actionMapping,

HttpServletRequest httpServletRequest) {

/** @todo: finish this method, this is just the skeleton.*/

ActionErrors errors = null;

if (this.findByKey.equals("") || this.findByValue.equals("")) {

errors = new ActionErrors();

errors.add(ActionErrors.GLOBAL_ERROR,

new ActionError("find.jsp.error"));

}

return errors;

}

public void reset(ActionMapping actionMapping,

HttpServletRequest servletRequest) {

}

}

/**/

package com.bookshop.form;

import org.apache.struts.action.ActionForm;

import org.apache.struts.action.ActionErrors;

import org.apache.struts.action.ActionMapping;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts.action.ActionError;

public class OperatorForm

extends ActionForm {

private String operator;

public String getOperator() {

return operator;

}

public void setOperator(String operator) {

this.operator = operator;

}

public ActionErrors validate(ActionMapping actionMapping,

HttpServletRequest httpServletRequest) {

ActionErrors errors = new ActionErrors();

if (httpServletRequest.getParameter("operator") != null) {

String lang = httpServletRequest.getParameter("operator");

/* if ( (lang.length() 6)) {

errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("index.jsp.operator.error"));

}

*/

}

else {

errors.add(ActionErrors.GLOBAL_ERROR,

new ActionError("index.jsp.operator.null"));

}

return errors;

}

public void reset(ActionMapping actionMapping,

HttpServletRequest servletRequest) {

}

}

以下是业务类和数据库访问类:

package com.bookshop.model;

import java.util.Map;

import java.util.List;

import com.bookshop.util.*;

public class Operator {

private static int recordPerPage = ApplicationUtil.recordPerPage;

//动态SQL

private static String sqlNumber = "";

//留出接口设置每页显示多少条记录

public static void setRecordPerPage(int number) {

recordPerPage = number;

}

public Operator() {

}

//获得所有记录集(只查询一页记录)

public static List getRecords(int startIndex) {

String sql = "select * from booktab limit ?,?";

sqlNumber = "select count(*) from booktab";

return DBUtil.executeQuery(sql, startIndex, recordPerPage);

}

//按条件查找记录集(只查询一页记录)

public static List getRecords(String key, String value, int startIndex) {

String sql = "select * from booktab where " + key + "='" + value +

"' limit ?,?";

sqlNumber = "select count(*) from booktab where " + key + "='" + value +

"'";

return DBUtil.executeQuery(sql, startIndex, recordPerPage);

}

//查询单条记录 用于修改

public static BookBean getRecord(String value) {

String sql = "select * from booktab where bookid='" + value + "'";

BookBean book = new BookBean();

book = DBUtil.execQuery(sql);

return book;

}

//添加一条新记录

public static int addRecord(Map newRecord) {

String sql =

"insert into booktab(bookname,author,publish,price,bookid)values(?,?,?,?,?)";

return DBUtil.execUpdate(sql, newRecord);

}

//修改指定的记录

public static int modifyRecord(Map newRecord) {

String sql =

"update booktab set bookname=?,author=?,publish=?,price=? where bookid=?";

return DBUtil.execUpdate(sql, newRecord);

}

//删除指定的记录

public static int deleteRecord(String value) {

String sql =

"delete from booktab where bookid='" + value + "'";

return DBUtil.execUpdate(sql);

}

//获得表中所有记录的条数

public static int getRecordsNumber() {

return DBUtil.executeQuery(sqlNumber);

}

/*

public static void main(String[] args) {

Operator operator = new Operator();

}

*/

}

/**/

package com.bookshop.util;

import javax.servlet.http.HttpServletRequest;

public class ApplicationUtil {

public ApplicationUtil() {

}

public static final String driver = "org.gjt.mm.mysql.Driver";

public static final String url ="jdbc:mysql://localhost/bookshop";

public static final String user = "root";

public static final String password = "";

public static final int recordPerPage = 5;

public static String toGBK(String s) {

try {

return new String(s.getBytes("ISO-8859-1"), "gb2312");

}

catch (Exception ex) {

return "";

}

}

public static String getSelfURL(HttpServletRequest req) {

String s1 = req.getRequestURI();

String s2 = req.getQueryString();

if (s2 != null) {

s1 = s1 + "?" + s2;

}

return s1;

}

public static void setParam(String param, String value, java.util.HashMap map) {

String[] p = param.split(";");

String[] v = value.split(";");

for (int i = 0; i < p.length; i++) {

map.put(p[i], v[i]);

}

}

}

/**/

package com.bookshop.util;

import javax.servlet.jsp.tagext.*;

import javax.servlet.jsp.JspException;

import javax.servlet.jsp.PageContext;

public class IsLastTag

extends TagSupport {

private String page = "";

public IsLastTag() {

}

public void setPage(String page) {

this.page = page;

}

public String getPage() {

return this.page;

}

public int doStartTag() throws JspException {

if (this.page != null) {

//从session里面取出来的是PageInfo对象的引用

PageInfo pageBean = new PageInfo();

pageBean = (PageInfo) (pageContext.getSession().getAttribute(this.

page));

//只要该PageInfo对象的总页数等于当前页数就不处理主体部分

if (pageBean.getPageCountNumber() <= pageBean.getCurrentlyPage()) {

return this.SKIP_BODY;

}

else {

return this.EVAL_PAGE;//否则继续处理主体部分

}

}

else {

return this.SKIP_BODY;

}

}

}

/**/

package com.bookshop.util;

import java.util.List;

import java.util.ArrayList;

import java.sql.DriverManager;

import java.sql.Connection;

import java.sql.Statement;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.util.HashMap;

import java.util.Map;

public class DBUtil {

public DBUtil() {

}

private static String driver = ApplicationUtil.driver;

private static String url = ApplicationUtil.url;

private static String user = ApplicationUtil.user;

private static String password = ApplicationUtil.password;

private static List list = null;

private static Connection con = null;

private static Statement sta = null;

private static PreparedStatement psta = null;

private static ResultSet res = null;

//获得满足查询条件的记录行数

public static int executeQuery(String sql) {

int countNum = 0;

try {

execute(sql);

while (res.next()) {

countNum = res.getInt(1);

}

}

catch (Exception e) {

e.printStackTrace();

}

finally {

close();

return countNum;

}

}

//删除记录

public static int execUpdate(String sql) {

int i = -1;

try {

getStatement();

i = sta.executeUpdate(sql);

}

catch (Exception e) {

e.printStackTrace();

}

finally {

close();

return i;

}

}

//添加新记录

public static int execUpdate(String sql, Map newRecord) {

int i = -1;

try {

getPreparedStatement(sql);

if (newRecord != null && !newRecord.isEmpty()) {

psta.setString(1, (String) newRecord.get("column2"));

psta.setString(2, (String) newRecord.get("column3"));

psta.setString(3, (String) newRecord.get("column4"));

psta.setString(4, (String) newRecord.get("column5"));

psta.setString(5, (String) newRecord.get("column1"));

}

i = psta.executeUpdate();

}

catch (Exception e) {

e.printStackTrace();

}

finally {

close();

return i;

}

}

//查询单个记录(用于修改)

public static BookBean execQuery(String sql) {

BookBean book = null;

try {

execute(sql);

while (res.next()) {

book = new BookBean(ApplicationUtil.toGBK(res.getString(1)),

ApplicationUtil.toGBK(res.getString(2)),

ApplicationUtil.toGBK(res.getString(3)),

ApplicationUtil.toGBK(res.getString(4)),

ApplicationUtil.toGBK(res.getString(5))

);

}

}

catch (Exception e) {

e.printStackTrace();

}

finally {

close();

return book;

}

}

//查询记录(只查询指定页要显示的记录)

public static List executeQuery(String sql, int startIndex, int count) {

try {

list = new ArrayList();

getResultSet(sql, startIndex, count);

while (res.next()) {

list.add(new BookBean(ApplicationUtil.toGBK(res.getString(1)),

ApplicationUtil.toGBK(res.getString(2)),

ApplicationUtil.toGBK(res.getString(3)),

ApplicationUtil.toGBK(res.getString(4)),

ApplicationUtil.toGBK(res.getString(5))

));

}

}

catch (Exception e) {

e.printStackTrace();

}

finally {

close();

return list;

}

}

private static void getConnection() throws Exception {

Class.forName(driver);

con = DriverManager.getConnection(url, user, password);

//con.setAutoCommit(false);

}

private static void getPreparedStatement(String sql) throws Exception {

getConnection();

psta = con.prepareStatement(sql);

}

private static void execute(String sql) throws Exception {

getStatement();

res = sta.executeQuery(sql);

}

private static void getStatement() throws Exception {

getConnection();

sta = con.createStatement();

}

private static void getResultSet(String sql, int startIndex, int count) throws

Exception {

getPreparedStatement(sql);

psta.setInt(1, startIndex);

psta.setInt(2, count);

res = psta.executeQuery();

}

//释放资源

private static void close() {

try {

/*

if(con!=null){

con.commit();

}

*/

if (res != null) {

res.close();

}

if (psta != null) {

psta.close();

}

if (sta != null) {

sta.close();

}

if (con != null) {

con.close();

}

}

catch (SQLException e) {

e.printStackTrace();

}

}

}

/**/

package com.bookshop.util;

import java.io.Serializable;

public class BookBean

implements Serializable {

private String author = "";

private String bookId = "";

private String bookName = "";

private String price = "";

private String publish = "";

public BookBean() {

this.bookId = "";

this.bookName = "";

this.author = "";

this.publish = "";

this.price = "";

}

public BookBean(String bookId, String bookName, String author, String publish,

&

责任编辑:admin
相关文章