这个DEMO供大家一起探讨学习Struts,因为工作太累,没精力给大家解释实现原理。如果看不懂,没关系。只是说明JSP基础还没有到火候,不要心急,回去强化下JSP+Servlet,基础扎实了,自然能够看懂我写的代码。这个DEMO借鉴了网上很多前人的经验,在此一并谢谢。
web.xml文件:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<display-name>BookShopMod</display-name>
<servlet>
<servlet-name>action</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml</param-value>
</init-param>
<init-param>
<param-name>debug</param-name>
<param-value>2</param-value>
</init-param>
<init-param>
<param-name>application</param-name>
<param-value>ApplicationResources</param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
<welcome-file>index.htm</welcome-file>
</welcome-file-list>
<taglib>
<taglib-uri>/WEB-INF/struts-bean.tld</taglib-uri>
<taglib-location>/WEB-INF/struts-bean.tld</taglib-location>
</taglib>
<taglib>
<taglib-uri>/WEB-INF/struts-html.tld</taglib-uri>
<taglib-location>/WEB-INF/struts-html.tld</taglib-location>
</taglib>
<taglib>
<taglib-uri>/WEB-INF/struts-logic.tld</taglib-uri>
<taglib-location>/WEB-INF/struts-logic.tld</taglib-location>
</taglib>
<taglib>
<taglib-uri>/WEB-INF/struts-template.tld</taglib-uri>
<taglib-location>/WEB-INF/struts-template.tld</taglib-location>
</taglib>
<taglib>
<taglib-uri>/WEB-INF/struts-tiles.tld</taglib-uri>
<taglib-location>/WEB-INF/struts-tiles.tld</taglib-location>
</taglib>
<taglib>
<taglib-uri>/WEB-INF/struts-nested.tld</taglib-uri>
<taglib-location>/WEB-INF/struts-nested.tld</taglib-location>
</taglib>
<taglib>
<taglib-uri>/WEB-INF/camel-define.tld</taglib-uri>
<taglib-location>/WEB-INF/camel-define.tld</taglib-location>
</taglib>
</web-app>
Struts-config.xml文件:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.1//EN" "http://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd">
<struts-config>
<form-beans>
<form-bean name="bookForm" type="com.bookshop.form.BookForm"/>
<form-bean name="operatorForm" type="com.bookshop.form.OperatorForm"/>
<form-bean name="findRecordForm" type="com.bookshop.form.FindRecordForm"/>
</form-beans>
<global-forwards>
<forward name="index" path="/index.jsp"/>
<forward name="browser" path="/show.jsp"/>
<forward name="global_error" path="/error.jsp"/>
</global-forwards>
<action-mappings>
<action input="/show.jsp" name="bookForm" parameter="operator" path="/operatorAction" scope="session" type="com.bookshop.action.OperatorAction" validate="false">
<forward name="operatorok" path="/success.jsp" redirect="true"/>
<forward name="showFirstPage" path="/operatorAction.do?operator=showFirstPage"/>
<forward name="showPreviousPage" path="/operatorAction.do?operator=showPreviousPage"/>
<forward name="showNextPage" path="/operatorAction.do?operator=showNextPage"/>
<forward name="showLastPage" path="/operatorAction.do?operator=showLastPage"/>
<forward name="showAddRecord" path="/editrecord.jsp?operator=addRecord" redirect="true"/>
<forward name="showModifyRecord" path="/editrecord.jsp?operator=modifyRecord"/>
<forward name="showFindRecord" path="/findrecord.jsp" redirect="true"/>
</action>
<action input="/findrecord.jsp" name="findRecordForm" path="/findRecordAction" scope="session" type="com.bookshop.action.FindRecordAction" validate="false"/>
</action-mappings>
<plug-in className="org.apache.struts.tiles.TilesPlugin">
<set-property property="definitions-config" value="/WEB-INF/tiles-defs.xml"/>
</plug-in>
</struts-config>
tiles-defs文件:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE tiles-definitions PUBLIC "-//Apache Software Foundation//DTD Tiles Configuration 1.1//EN" "http://jakarta.apache.org/struts/dtds/tiles-config_1_1.dtd">
<tiles-definitions>
<definition name="base-definition" path="layout.jsp">
<put name="head" value="head.jsp" />
<put name="left" value="left.jsp" />
<put name="body" />
<put name="foot" value="foot.jsp" />
</definition>
<definition extends="base-definition" name="index-definition">
<put name="body" value="index_body.jsp" />
</definition>
<definition extends="base-definition" name="show-definition">
<put name="body" value="show_body.jsp" />
</definition>
<definition extends="base-definition" name="edit-definition">
<put name="body" value="edit_body.jsp" />
</definition>
<definition extends="base-definition" name="find-definition">
<put name="body" value="find_body.jsp"/>
</definition>
<definition extends="base-definition" name="success-definition">
<put name="body" value="success_body.jsp" />
</definition>
<definition extends="base-definition" name="error-definition">
<put name="body" value="error_body.jsp"/>
</definition>
</tiles-definitions>
camel-define文件:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN" "http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd">
<taglib>
<tlibversion>1.0</tlibversion>
<jspversion>1.1</jspversion>
<shortname>camel</shortname>
<uri>http://jakarta.apache.org/struts/tags-bean</uri>
<tag>
<name>isLastPage</name>
<tagclass>com.bookshop.util.IsLastTag</tagclass>
<bodycontent>JSP</bodycontent>
<attribute>
<name>page</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
</taglib>
上面几个文件和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) || (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,
&
web.xml文件:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<display-name>BookShopMod</display-name>
<servlet>
<servlet-name>action</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml</param-value>
</init-param>
<init-param>
<param-name>debug</param-name>
<param-value>2</param-value>
</init-param>
<init-param>
<param-name>application</param-name>
<param-value>ApplicationResources</param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
<welcome-file>index.htm</welcome-file>
</welcome-file-list>
<taglib>
<taglib-uri>/WEB-INF/struts-bean.tld</taglib-uri>
<taglib-location>/WEB-INF/struts-bean.tld</taglib-location>
</taglib>
<taglib>
<taglib-uri>/WEB-INF/struts-html.tld</taglib-uri>
<taglib-location>/WEB-INF/struts-html.tld</taglib-location>
</taglib>
<taglib>
<taglib-uri>/WEB-INF/struts-logic.tld</taglib-uri>
<taglib-location>/WEB-INF/struts-logic.tld</taglib-location>
</taglib>
<taglib>
<taglib-uri>/WEB-INF/struts-template.tld</taglib-uri>
<taglib-location>/WEB-INF/struts-template.tld</taglib-location>
</taglib>
<taglib>
<taglib-uri>/WEB-INF/struts-tiles.tld</taglib-uri>
<taglib-location>/WEB-INF/struts-tiles.tld</taglib-location>
</taglib>
<taglib>
<taglib-uri>/WEB-INF/struts-nested.tld</taglib-uri>
<taglib-location>/WEB-INF/struts-nested.tld</taglib-location>
</taglib>
<taglib>
<taglib-uri>/WEB-INF/camel-define.tld</taglib-uri>
<taglib-location>/WEB-INF/camel-define.tld</taglib-location>
</taglib>
</web-app>
Struts-config.xml文件:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.1//EN" "http://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd">
<struts-config>
<form-beans>
<form-bean name="bookForm" type="com.bookshop.form.BookForm"/>
<form-bean name="operatorForm" type="com.bookshop.form.OperatorForm"/>
<form-bean name="findRecordForm" type="com.bookshop.form.FindRecordForm"/>
</form-beans>
<global-forwards>
<forward name="index" path="/index.jsp"/>
<forward name="browser" path="/show.jsp"/>
<forward name="global_error" path="/error.jsp"/>
</global-forwards>
<action-mappings>
<action input="/show.jsp" name="bookForm" parameter="operator" path="/operatorAction" scope="session" type="com.bookshop.action.OperatorAction" validate="false">
<forward name="operatorok" path="/success.jsp" redirect="true"/>
<forward name="showFirstPage" path="/operatorAction.do?operator=showFirstPage"/>
<forward name="showPreviousPage" path="/operatorAction.do?operator=showPreviousPage"/>
<forward name="showNextPage" path="/operatorAction.do?operator=showNextPage"/>
<forward name="showLastPage" path="/operatorAction.do?operator=showLastPage"/>
<forward name="showAddRecord" path="/editrecord.jsp?operator=addRecord" redirect="true"/>
<forward name="showModifyRecord" path="/editrecord.jsp?operator=modifyRecord"/>
<forward name="showFindRecord" path="/findrecord.jsp" redirect="true"/>
</action>
<action input="/findrecord.jsp" name="findRecordForm" path="/findRecordAction" scope="session" type="com.bookshop.action.FindRecordAction" validate="false"/>
</action-mappings>
<plug-in className="org.apache.struts.tiles.TilesPlugin">
<set-property property="definitions-config" value="/WEB-INF/tiles-defs.xml"/>
</plug-in>
</struts-config>
tiles-defs文件:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE tiles-definitions PUBLIC "-//Apache Software Foundation//DTD Tiles Configuration 1.1//EN" "http://jakarta.apache.org/struts/dtds/tiles-config_1_1.dtd">
<tiles-definitions>
<definition name="base-definition" path="layout.jsp">
<put name="head" value="head.jsp" />
<put name="left" value="left.jsp" />
<put name="body" />
<put name="foot" value="foot.jsp" />
</definition>
<definition extends="base-definition" name="index-definition">
<put name="body" value="index_body.jsp" />
</definition>
<definition extends="base-definition" name="show-definition">
<put name="body" value="show_body.jsp" />
</definition>
<definition extends="base-definition" name="edit-definition">
<put name="body" value="edit_body.jsp" />
</definition>
<definition extends="base-definition" name="find-definition">
<put name="body" value="find_body.jsp"/>
</definition>
<definition extends="base-definition" name="success-definition">
<put name="body" value="success_body.jsp" />
</definition>
<definition extends="base-definition" name="error-definition">
<put name="body" value="error_body.jsp"/>
</definition>
</tiles-definitions>
camel-define文件:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN" "http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd">
<taglib>
<tlibversion>1.0</tlibversion>
<jspversion>1.1</jspversion>
<shortname>camel</shortname>
<uri>http://jakarta.apache.org/struts/tags-bean</uri>
<tag>
<name>isLastPage</name>
<tagclass>com.bookshop.util.IsLastTag</tagclass>
<bodycontent>JSP</bodycontent>
<attribute>
<name>page</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
</taglib>
上面几个文件和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) || (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,
&
相关推荐
在这个"一个Struts实现分页,增删改查,Tiles,国际化的DEMO"中,我们将深入探讨几个关键知识点。 首先,**分页**是大型Web应用中必不可少的功能,它帮助用户浏览大量数据时避免一次性加载过多信息,提高页面加载速度...
综上所述,"struts2+hibernate增删改查+分页"是一个基础的Java Web开发示例,它涵盖了MVC架构下,如何利用Struts2处理用户请求,通过Hibernate进行数据库操作,以及实现简单的分页功能。这种组合在实际项目中非常...
在这个"Struts1做的增删改查"项目中,你将学习到如何使用Struts1来处理用户请求,并实现数据的CRUD(Create,Read,Update,Delete)操作。 1. **Struts1框架基础**: - **架构**:Struts1的核心组件包括...
在“struts版增删改查”这个主题中,我们主要探讨的是如何利用Struts框架来实现一个基本的CRUD(创建、读取、更新、删除)应用。这种应用模式在许多Web系统中都非常常见,特别是在处理数据库数据时。 **1. MVC模式*...
这个"Struts1.x写的增删改查实例"是面向初学者和开发者的一个实用教程,它演示了如何使用Struts1.x来实现基本的数据操作功能,包括添加(Add)、删除(Delete)、修改(Update)和查询(Query)。 首先,让我们深入...
在这个"struts2图书管理"项目中,我们看到它实现了基础的图书管理系统功能,包括图书的增删改查以及用户登录和注册的验证。 首先,让我们详细了解一下Struts2的核心概念和特性: 1. **Action和Action Mapping**:...
在本示例中,我们将探讨如何在Struts中实现基本的增删改查(CRUD)操作。 1. **MVC模式**: MVC(Model-View-Controller)模式是Struts的核心架构。Model代表业务逻辑,View负责显示数据,Controller处理用户请求...
这个"struts 增删改查完整实例"旨在提供一个完整的CRUD(Create, Read, Update, Delete)操作示例,帮助开发者理解如何在实际项目中使用Struts来处理常见的数据操作。 在Struts框架中,核心组件包括Action类、配置...
4. **事务管理**:使用 Struts2 的拦截器处理事务,确保增删改查操作的原子性。 5. **结果集转换**:将 Hibernate 查询的结果转化为 Struts2 的 ValueStack,传递到 JSP 页面显示。 6. **错误和异常处理**:配置 ...
Struts是一个经典的Java web开发框架,由Apache软件基金会维护,主要用于构建MVC(Model-View-Controller)架构的Web应用程序。在这个"Struts带分页有查询"的项目中,开发者利用Struts框架实现了带有分页功能的查询...
最后,在`struts.xml`中,我们定义了一个名为“XXAction”的动作,该动作的成功结果类型为tiles,并指向了“myHome”布局,实现了动态页面的渲染和展示。 ### 总结 通过以上分析,我们可以看到Struts2 tiles插件的...
【标题】"用hibernate+struts写的用户登录和新闻增删改查"是一个基于Java Web开发的经典案例,它涵盖了两个重要的技术框架——Hibernate和Struts。Hibernate是一个对象关系映射(ORM)框架,它简化了Java应用程序与...
4. **DAO层**:包含Hibernate的Session操作,如增删改查方法,这些方法通常被Struts2的Action类调用。 5. **Action类**:实现了业务逻辑,负责接收请求、处理数据并调用DAO进行数据库操作。 6. **视图(View)**:...
Struts2是一个强大的Java web应用程序框架,用于构建可维护、可扩展且结构良好的MVC(模型-视图-控制器)架构应用。在这个“Struts2 完美实现 标签分页”的项目中,我们主要关注如何在Struts2框架下实现高效的分页...
Struts2是一个强大的Java web应用程序框架,而Tiles是用于构建MVC(模型-视图-控制器)架构的一个视图组件库。将Tiles与Struts2结合使用,可以更有效地管理和组织网页布局,实现复杂的页面结构和重用内容。在本篇...
Struts2是一个基于MVC(Model-View-Controller)设计模式的Java Web框架,它为开发者提供了一种组织应用程序结构和管理业务逻辑的方式。Oracle则是一种强大的关系型数据库管理系统,广泛用于企业级应用中存储和处理...
在本示例中,我们将深入探讨如何在一个简单的应用中整合Struts与Tiles。 Struts是一个开源的MVC框架,它提供了一种规范化的处理HTTP请求、控制业务逻辑以及呈现视图的方式。而Tiles是Struts的一个扩展,主要负责...
总结来说,"struts+ajax分页程序"是一个结合了Struts框架和Ajax技术的Web应用程序,实现了用户交互过程中无需刷新整个页面的动态分页效果。通过Struts处理业务逻辑和数据查询,以及Ajax负责异步通信,提升了用户体验...