SSH框架下的增删改查_第1页
SSH框架下的增删改查_第2页
SSH框架下的增删改查_第3页
SSH框架下的增删改查_第4页
SSH框架下的增删改查_第5页
已阅读5页,还剩34页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

SSH实现的增删改查实例分类:ssh2010-10-0117:124591人阅读评论⑺收藏举报一•整合步骤通过MyEclipse向导,添加struts功能通过MyEclipse向导,添加Hibernate3功能:生成会话工厂的那个步骤中一定要将那个对号要去掉,不能由hibernate来生成,而是交给Spring来生成;还有就是导入jar包的时候选择复制到lib目录下这一项。通过MyEclipse向导,导入实现Spring功能,注意导入jar包的时候选择复制到lib目录下这一项。利用MyEclipse反向工程的方法,以Spring<dao>生成dao对象的方式创建HibernateDAO,相关POJO及其xxx.hbm.xml。DAO实现类加入@Transactional标记。修改即plicationContext.xml文件,增加Spring事务管理、DAO等bean的配置。编写action类。在applicationContext.xml文件中添加Action的代理bean。在struts的配置文件中,添加相应的Action,类名指向Spring中的代理bean,并加入〈controllerprocessorClass="org.springframework.web.struts.DelegatingRequestProcessor""“plug-inclassName="org.springframework.web.struts.ContextLoaderPlugln"><set-propertyproperty="contextConfigLocation"value="/WEB-INF/classes/applicationContext.xml"/></plug-in>。编写Jsp文件。发布web项目。启动web服务器,运行项目二.SSH实现关于书籍增删改查实例1.创建mysql数据库及其表createdatabasebook;createtablebook(idintnotnullprimarykeyauto_increment,booknamevarchar(30),bookauthorvarchar(30));2•表现层(1)index.jsp(首页)[java]viewplaincopyprint?<%@pagelanguage="java"pageEncoding="GBK"%><%@tagliburi="/tags-html"prefix="html"%><!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01Transitional//EN"><html:htmllang="true"><head><html:base/><title>欢迎</title></head><body><ahref="book.do?method=listbook"mce_href="book.do?method=listbook">查看书籍列表</a><br></body></html:html>〈%@pagelanguage="java"pageEncoding="GBK"%〉<%@tagliburi="/tags-html"〈!D0CTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01Transi<html:htmllang="true"><head>〈html:base/〉〈title〉欢迎〈/title〉</head>〈body〉<ahref="book.do?method=listbook"mce_href="book.do〈/body〉</html:html>(2)list.jsp(书籍列表页面)[c-sharp]viewplaincopyprint?<%@pagecontentType="text/html;charset=GBK"isELIgnored="false"%><%--我们使用JSTL来访问数据--%><%@tagliburi="/jsp/jstl/core"prefix="c"%><%Stringpath=request.getContextPath();StringbasePath=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01Transitional//EN"><html><head><basehref="<%=basePath%>"><title>书籍列表页面</title><metahttp-equiv="pragma"content="no-cache"><metahttp-equiv="cache-control"content="no-cache"><metahttp-equiv="expires"content="0"><mce:style><!--/*给链接加入鼠标移过变色和去除下划线功能*/a:hover{color:red;text-decoration:none}--></mce:stylexstylemce_bogus="1">/*给链接加入鼠标移过变色和去除下划线功能*/a:hover{color:red;text-decoration:none}</style></head><body><b>书籍列表页面</b>

4.<%--输出用户列表--%><br><c:choose><c:whentest="${notemptybooks}"〉<tablewidth="80%"border="1"cellpadding="0"style="border-collapse:collapse;"bordercolor="#000000"><tr><td><b>书籍ID</b></td><td><b>书籍名称</b></td><td><b>作者</b></td><td><b>价格</b></td><td><b>操作</b></td></tr><c:forEachitems="${books}"var="book"><tr><td>${book.id}</td><td>${book.bookname}</td><td>${book.bookauthor}</td><td>${book.bookprice}</td><td><ahref="<%=path%>/book.do?method=modifybook&id=${book.id}">修改</a><ahref="<%=path%>/book.do?method=deletebook&id=${book.id}">删除</a></td></tr>

</c:forEach>76.</table></c:when><c:otherwise>抱歉,没有找到相关的记录!</c:otherwise></c:choose><ahref="<%=path%>/new.jsp">添加书籍</a><formaction="<%=path%>/book.do?method=searchbook"method="post"onsubmit="returncheckSearchForm(this);"><fieldset><legend>查找书籍</legend>书籍名:<input name="bookname"><input type="submit"value="查找"〉</fieldset></form></body></html><%@pagecontentType="text/html;charset=GBK"isELIg〈%—我们使用J§TL来访问数据一%〉 ”〈%@tagliburi="/jsp/jstl/core"〈%Stringpath=request.getContextPath();StringbasePath=request.getScheme()+"://"+request.getServerName()+"%〉〈!D0CTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01Transi<html><head>〈title〉书籍列表页面〈title〉书籍列表页面〈/title〉<mce:style><!一一/*给链接加入鼠标移过变色和去除下划线功能*/<metahttp-equiv二"pragma"content二"<metahttp-equiv<mce:style><!一一/*给链接加入鼠标移过变色和去除下划线功能*/⑶new.jsp(新增书籍页面)[c-sharp]viewplaincopyprint?<%@pagelanguage="java"pageEncoding="GBK"%><%@tagliburi="/tags-bean"prefix="bean"%><%@tagliburi="/tags-html"prefix="html"%><!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01Transitional//EN"><html><head><title> 添加书籍</title><meta http-equiv="pragma"content="no-cache"><meta http-equiv="cache-control"content="no-cache">

2.<metahttp-equiv="expires"content="0"><mce:scripttype="text/javascript"src="js/form.js"mce_src="js/form.js"x/mce:script></head><body><h3>添加书籍</h3><formaction="<%=request.getContextPath()%>/book.do?method=addbook"onsubmit="returncheckForm(this);"method="post"><tablewidth="100%"border="0"><tbody><tr><td>书籍名:</td><td><inputname="bookname"/><br></td></tr><tr><td>作者:</td><td><inputname="bookauthor"/></td></tr><tr><td>价格:</td><td><inputname="bookprice"/></td></tr><tr><td><inputtype="submit"value="添加"name="button1"></td>

53.<td>54.55.<inputtype="Reset"value="重填"name="button2">56.</td>57.</tr>58.</tbody>59.</table>60.61.<inputtype="button"onclick="document.location='<%=request.getContextPath()%>/book.do?method=listbook';"62.value="63.返回列表"〉64.65.</body></html>〈html〉〈head〉<h3>53.<td>54.55.<inputtype="Reset"value="重填"name="button2">56.</td>57.</tr>58.</tbody>59.</table>60.61.<inputtype="button"onclick="document.location='<%=request.getContextPath()%>/book.do?method=listbook';"62.value="63.返回列表"〉64.65.</body></html>〈html〉〈head〉<h3>添加书籍⑷edit.jsp(书籍修改页面)</h3> ”〈formaction="〈%=request.getContext</head>〈body〉<%@pagelanguage="java"pageEncoding="GBK"%〉〈%@tagliburi="/tags-bean"<%@tagliburi="/tags-html"〈!D0CTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01Transi〈title〉添加书籍〈/title〉<metahttp-equiv="pragma"content="<metahttp-equiv="cache-control"co<metahttp-equiv="expires"content=〈mce:scripttype="text/javascript"[c-sharp]viewplaincopyprint?<%@pagelanguage="java"pageEncoding="GBK"isELIgnored="false"%><!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01Transitional//EN"><html><head><title>修改书籍</title><metahttp-equiv="pragma"content="no-cache"><metahttp-equiv="cache-control"content="no-cache"><metahttp-equiv="expires"content="0"><mce:scripttype="text/javascript"src="js/form.js"mce_src="js/form.js"x/mce:script></head><body><h3>修改书籍</h3>

7.<formaction="<%=request.getContextPath()%>/book.do?method=updatebook"onsubmit="returncheckForm(this);"method="post"><inputtype="hidden"value="${book.id}"name="id"/><tablewidth="100%"border="0"><tbody><tr><td>书籍名:</td><td><inputname="bookname"value="${book.bookname}"/><br></td></tr><tr><td>作者:</td><td><inputname="bookauthor"value="${book.bookauthor}"/></td></tr><tr><td>价格:</td><td><inputname="bookprice"value="${book.bookprice}"/></td></tr><tr><td><inputtype="submit"value='提交"〉</td><td><inputtype="reset"value="重填"〉</td></tr></tbody>

</table></form><inputtype="button"onclick="document.location='book.do?method=listbook';"value="返回列表"〉</body></html>〈html〉〈head〉</head>〈body〉〈title〉修改书籍〈/title〉<metahttp-equiv二"pragma"content二"<metahttp-equiv二〈html〉〈head〉</head>〈body〉〈title〉修改书籍〈/title〉<metahttp-equiv二"pragma"content二"<metahttp-equiv二"cache-control"co<metahttp-equiv二"expires"content=〈mce:scripttype二"text/javascript"<h3>修改书籍</h3> ,,〈formaction二"〈%=request.getContext〈inputtype二"hidden"value="${b〈tablewidth二"100%"border二(5)error.jsp(错误公用页面)[c-sharp]viewplaincopyprint?<%@pagelanguage="java"pageEncoding="GBK"isELIgnored="false"%><%Stringpath=request.getContextPath();StringbasePath=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01Transitional//EN"><html><head><basehref="<%=basePath%>"><title>出错了!</title></head><body>出错了!<br/>详细信息是:<br/>${message}<br/xbr/><ahref="javascript:history.back();"mce_href="javascript:history.back();">返回</a></body></html>

〈%@pagelanguage="java"pageEncoding="GBK"isELIgn〈%Stringpath=request.getContextPath();StringbasePath=request.getScheme()+"://"+request.getServerName()+"%〉〈!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01Transi<html><head><basehref="〈%=basePath%〉"〉〈title〉出错了!〈/title〉</head>〈body〉出错了!〈br/〉详细信息是:〈br/〉${message}〈br/〉〈br/〉<ahref="javascript:history.back();"mce_href="java//bo(//bo(<1[c-sharp]viewplaincopyprint?//验证表单输入不为空的脚本代码functioncheckForm(form){if (form.bookname.value==""){alert("书名不能为空门;form.bookname.focus();returnfalse;}if (form.bookauthor.value==""){alert("作者不能为空门;form.bookauthor.focus();returnfalse;}if (form.bookprice.value==""){alert("价格不能为空门;form.bookprice.focus();returnfalse;}returntrue;}functioncheckSearchForm(form){if(form.bookname.value.match(/A/s*$/)){alert("查询条件不能为空!");form.bookname.focus();returnfalse;}returntrue;//验证表单输入不为空的脚本代码functioncheckForm(form){if}if(form.bookname.value=="""){alert("书名不能为空!");form.bookname.focus();returnfalse;}if(form.bookauthor.value=="""){alert("作者不能为空!");form.bookauthor.focus();returnfalse;(form.bookprice.value==""""){alert("价格不能为空!");form.bookprice.focus();returnfalse;公用类及其javabean⑴EncodingFilter.java(过滤器)[c-sharp]viewplaincopyprint?packagefilter;importjava.io.IOException;importjavax.servlet.Filter;importjavax.servlet.FilterChain;importjavax.servlet.FilterConfig;importjavax.servlet.ServletException;importjavax.servlet.ServletRequest;importjavax.servlet.ServletResponse;publicclassEncodingFilterimplementsFilter{protectedFilterConfigconfig;protectedStringEncoding=null;publicvoidinit(FilterConfigconfig)throwsServletException{this.config=config;this.Encoding=config.getlnitParameter("Encoding");}publicvoiddoFilter(ServletRequestrequest,ServletResponseresponse,FilterChainchain)throwsIOException,ServletException{if(request.getCharacterEncoding()==null){if(Encoding!=null){request.setCharacterEncoding(Encoding);response.setCharacterEncoding(Encoding);TOC\o"1-5"\h\z}}chain.doFilter(request,response);}publicvoiddestroy(){}packagefilter;importjava.io.IOException;importjavax.servlet.Filter;importjavax.servlet.FilterChain;importjavax.servlet.FilterConfig;importjavax.servlet.ServletException;importjavax.servlet.ServletRequest;importjavax.servlet.ServletResponse;publicclassEncodingFilterimplementsFilter{protectedFilterConfigconfig;protectedStringEncoding=null;}publicpublicvoidinit(FilterConfigconfig)throwthis.config=config;this.Encoding=config.getlnitParam}publicillvoiddoFilter(ServletRequestrequestFilterChainchain)throwsif(request.getCharacterEncoding()ill(2)book.java[c-sharp]viewplaincopyprint?.3.4.5./***Bookentity.@authorMyEclipsePersistenceTools*/publicclassBookimplementsjava.io.Serializable{//FieldsprivateIntegerid;privateStringbookname;privateStringbookauthor;privateFloatbookprice;//Constructors/**defaultconstructor*/publicBook(){}/**fullconstructor*/publicBook(Stringbookname,Stringbookauthor,Floatbookprice){this.bookname=bookname;this.bookauthor=bookauthor;this.bookprice=bookprice;TOC\o"1-5"\h\z}//PropertyaccessorspublicIntegergetId(){returnthis.id;}publicvoidsetld(lntegerid){this.id=id;}publicStringgetBookname(){returnthis.bookname;}publicvoidsetBookname(Stringbookname){this.bookname=bookname;TOC\o"1-5"\h\z}publicStringgetBookauthor(){returnthis.bookauthor;}publicvoidsetBookauthor(Stringbookauthor){this.bookauthor=bookauthor;}publicFloatgetBookprice(){returnthis.bookprice;}publicvoidsetBookprice(Floatbookprice){this.bookprice=bookprice;}}packagedao;/***Bookentity.@authorMyEclipsePersistenceTools*/publicclassBookimplementsjava.io.Serializable{//FieldsprivateIntegerid;privateStringbookname;privateStringbookauthor;privateFloatbookprice;//Constructors/**defaultconstructor*/publicBook(){/**fullconstructor*/publicBook(Stringbookname,Stringbookautthis.bookname=bookname;DAO层BookDAO.java[c-sharp]viewplaincopyprint?packagedao;importjava.util.List;importorg.hibernate.LockMode;importorg.hibernate.Query;importorg.slf4j.Logger;importorg.slf4j.LoggerFactory;importorg.springframework.context.ApplicationContext;importorg.springframework.context.support.ClassPathXmlApplicationContext;importorg.springframework.orm.hibernate3.support.HibernateDaoSupport;importorg.springframework.transaction.annotation.Transactional;/***Adataaccessobject(DAO)providingpersistenceandsearchsupportforBook

5.56.entities.Transactioncontrolofthesave(),update。anddelete。operationscandirectlysupportSpringcontainer-managedtransactionsortheycanbeaugmentedtohandleuser-managedSpringtransactions.Eachofthesemethodsprovidesadditionalinformationforhowtoconfigureitforthedesiredtypeoftransactioncontrol.*@seedao.Book@authorMyEclipsePersistenceTools*/@TransactionalpublicclassBookDAOextendsHibernateDaoSupport{privatestaticfinalLoggerlog=LoggerFactory.getLogger(BookDAO.class);//propertyconstantspublicstaticfinalStringBOOKNAME="bookname";publicstaticfinalStringBOOKAUTHOR="bookauthor";publicstaticfinalStringBOOKPRICE="bookprice";protectedvoidinitDao(){//donothing}publicvoidsave(Booktransientinstance){log.debug("savingBookinstance");try{getHibernateTemplate().save(transientlnstance);log.debug("savesuccessful");}catch(RuntimeExceptionre){log.error("savefailed",re);throwre;}}publicvoidupdate(Booktransientinstance){log.debug("savingBookinstance");try{getHibernateTemplate().update(transientinstance);log.debug("savesuccessful");}catch(RuntimeExceptionre){log.error("savefailed",re);throwre;}}publicvoiddelete(Bookpersistentinstance){log.debug("deletingBookinstance");try{getHibernateTemplate().delete(persistentinstance);log.debug("deletesuccessful");

00.log.error("deletefailed",re);throwre;}}publicBookfindByld(java.lang.1ntegerid){log.debug("gettingBookinstancewithid:"+id);try{Bookinstance=(Book)getHibernateTemplate().get("dao.Book",id);returninstance;}catch(RuntimeExceptionre){log.error("getfailed",re);throwre;}}publicListfindByExample(Bookinstance){log.debug("findingBookinstancebyexample");try{Listresults=getHibernateTemplate().findByExample(instance);log.debug("findbyexamplesuccessful,resultsize:"+results.size());returnresults;}catch(RuntimeExceptionre){log.error("findbyexamplefailed",re);throwre;}}publicListfindByProperty(StringpropertyName,Objectvalue){log.debug("findingBookinstancewithproperty:"+propertyName+",value:"+value);try{StringqueryString="fromBookasmodelwheremodel."+propertyName+"like=";returngetHibernateTemplate().find(queryString,value);}catch(RuntimeExceptionre){log.error("findbypropertynamefailed",re);throwre;}}publicListfindByBookname(Stringbookname){Stringsql="fromBookwherebooknamelike'%"+bookname+"%"‘;Queryquery=this.getSession().createQuery(sql);returnquery.list();}0043.144.publicListfindByBookauthor(Objectbookauthor){returnfindByProperty(BOOKAUTHOR,bookauthor);}publicListfindByBookprice(Objectbookprice){returnfindByProperty(BOOKPRICE,bookprice);}publicListfindAll(){log.debug("findingallBookinstances");try{StringqueryString="fromBook";returngetHibernateTemplate().find(queryString);}catch(RuntimeExceptionre){log.error("findallfailed",re);throwre;}}publicBookmerge(BookdetachedInstance){log.debug("mergingBookinstance");try{Bookresult=(Book)getHibernateTemplate().merge(detachedlnstance);log.debug("mergesuccessful");returnresult;}catch(RuntimeExceptionre){log.error("mergefailed",re);throwre;}}publicvoidattachDirty(Bookinstance){log.debug("attachingdirtyBookinstance");try{getHibernateTemplate().saveOrUpdate(instance);log.debug("attachsuccessful");}catch(RuntimeExceptionre){log.error("attachfailed",re);throwre;}}publicvoidattachClean(Bookinstance){log.debug("attachingcleanBookinstance");try{getHibernateTemplate().lock(instance,LockMode.NONE);log.debug("attachsuccessful");}catch(RuntimeExceptionre){log.error("attachfailed",re);packagedao;importimportimportimportimportimportimportimportimport/***packagedao;importimportimportimportimportimportimportimportimport/********145.throwre;146.}147.}148.publicstaticBookDAOgetFromApplicationContext(ApplicationContextctx){149.return(BookDAO)ctx.getBean("BookDAO");150.}151.publicstaticvoidmain(String[]args){152.Applicationcontextctx=153.new154.ClassPathXmlApplicationContext("applicationContext.xml");155.BookDAOdao=(BookDAO)ctx.getBean("BookDAO");156.157.Bookbook=newBook();book.setBookname("数学”);158.book.setBookauthor("张三”);159.book.setBookprice(12.0f);160.dao.save(book);161.162.}}java.util.List;org.hibernate.LockMode;org.hibernate.Query;org.slf4j.Logger;org.slf4j.LoggerFactory;org.springframework.context.ApplicationConteorg.springframework.context.support.ClassPatorg.springframework.orm.hibernate3.support.Horg.springframework.transaction.annotation.TAdataaccessobject(DAO)providingpersistenceentities.Transactioncontrolofthesave(),updcandirectlysupportSpringcontainer-managedtraugmentedtohandleuser-managedSpringtransactprovidesadditionalinformationforhowtoconfioftransactioncontrol.service层(1)IBookManager.java(接口)[c-sharp]viewplaincopyprint?packageservice;importjava.util.List;importdao.Book;publicinterfaceIBookManager{/**@paramBook*(2)BookManager.java(实现类@paramBook*(2)BookManager.java(实现类)[c-sharp]viewplaincopyprint?**@paramid* 用户编号*@return找到的用户对象,找不到时返回null

用户编号被更新的用户packageservice;importimportpublic用户编号被更新的用户packageservice;importimportpublic11.*/12.publicBookfindByld(intid);13.14./***更新用户对象。15.*16.17.@paramBook被更新的用户18.*@return更新成功与否19.*/20.publicbooleanupdate(BookBook);21.publicbooleansave(BookBook);22.23./***删除用户对象。24.*25.26.@paramBook被删除的用户27.*@return删除成功与否28.*/29.publicbooleandelete(BookBook);30.31./***根据用户名查找用户。32.*33.34.@paramusername用户名35.*@return包含此用户名的用户列表36.*/37.publicList<Book>findByBookname(Stringusername);38.39.publicListfindAll();}

packageservice;importjava.util.List;importorg.springframework.context.ApplicationContext;importorg.springframework.context.support.ClassPathXmlApplicationContext;importdao.Book;importdao.BookDAO;publicclassBookManagerimplementsIBookManager{privateBookDAObookdao;publicbooleandelete(Bookbook){try{bookdao.delete(book);returntrue;}catch(Exceptione){}returnfalse;}publicBookfindByld(intid){returnbookdao.findById(id);}publicListfindAll(){returnbookdao.findAll();}publicList<Book>findByBookname(Stringbookname){returnbookdao.findByBookname(bookname);}publicbooleanupdate(BookBook){try{bookdao.update(Book);returntrue;}catch(Exceptione){}returnfalse;}publicbooleansave(BookBook){try{bookdao.save(Book);returntrue;}catch(Exceptione){}returnfalse;}publicdao.BookDAOgetBookdao(){..2.43.44.returnbookdao;}publicvoidsetBookdao(dao.BookDAObookdao){this.bookdao=bookdao;}}packageservice;importimportimportimportimportpublicjava.util.List;org.springframework.context.ApplicationConteorg.springframework.context.support.ClassPatdao.Book;dao.BookDAO;classBookManagerimplementsIBookManager{privateBookDAObookdao;publicbooleandelete(Bookbook){try{}catch}returnfalse;bookdao.delete(book);returntrue;(Exceptione){6.Action处理⑴BookForm.java[c-sharp]viewplaincopyprint?packagecom.zxc.struts.form;importorg.apache.struts.action.ActionForm;publicclassBookFormextendsActionForm{private intid;private String bookname;private String bookauthor;private floatbookprice;publicint getId(){returnid;}publicvoid setId(intid){this.id=id;}publicStringgetBookname(){returnbookname;}publicvoidsetBookname(Stringbookname){this.bookname=bookname;}publicStringgetBookauthor(){returnbookauthor;}23.publicvoidsetBookauthor(Stringbookauthor){this.bookauthor=bookauthor;TOC\o"1-5"\h\z}publicfloatgetBookprice(){returnbookprice;}publicvoidsetBookprice(float bookprice){this.bookprice=bookprice;}}packagecom.zxc.struts.form;importorg.apache.struts.action.ActionForm;publicvoidsetBookname(Stringbookname){intgetld(){returnid;StringgetBookname(){returnbookname;}publicpublic}publicvoidsetId(intid){this.id=id;publicclassBookFormextendsActionForm{privateintid;publicvoidsetBookname(Stringbookname){intgetld(){returnid;StringgetBookname(){returnbookname;}publicpublic}publicvoidsetId(intid){this.id=id;privateStringbookname;privateStringbookauthor;privatefloatbookprice;BookAction.java[java]viewplaincopyprint?1./*2.*GeneratedbyMyEclipseStruts3.*Templatepath:templates/java/JavaClass.vtl4.*/5.packagecom.zxc.struts.action;6.importjava.util.List;7.importjavax.servlet.http.HttpServletRequest;8.importjavax.servlet.http.HttpServletResponse;9.importorg.apache.struts.action.ActionForm;10.importorg.apache.struts.action.ActionForward;11.importorg.apache.struts.action.ActionMapping;12.importorg.apache.struts.actions.DispatchAction;13.importservice.1BookManager;14.importcom.zxc.struts.form.BookForm;15.importdao.Book;16./**17.*MyEclipseStruts18.*Creationdate:10-01-201019.*20.*XDocletdefinition:*@struts.actionvalidate="true"*/publicclassBookActionextendsDispatchAction{privateIBookManagerbookManager;publicActionForwardaddbook(ActionMappingmapping,ActionFormform,HttpServletRequestrequest,HttpServletResponseresponse){//TODOAuto-generatedmethodstubBookFormbookForm=(BookForm)form;Bookbook=newBook();book.setBookname(bookForm.getBookname());book.setBookauthor(bookForm.getBookauthor());book.setBookprice(bookForm.getBookprice());bookManager.save(book);returnlistbook(mapping,form,request,response);}publicActionForwardupdatebook(ActionMappingmapping,ActionFormform,HttpServletRequestrequest,HttpServletResponseresponse){//TODOAuto-generatedmethodstubBookFormbookForm=(BookForm)form;Stringid=request.getParameter("id");Bookbook=bookManager.findByld(lnteger.parselnt(id));book.setBookname(bookForm.getBookname());book.setBookauthor(bookForm.getBookauthor());book.setBookprice(bookForm.getBookprice());if(bookManager.update(book)){returnlistbook(mapping,form,request,response);}else{Stringmessage="更新失败!";request.setAttribute("message",message);returnmapping.findForward("message");}}publicActionForwardmodifybook(ActionMappingmapping,ActionFormform,HttpServletRequestrequest,HttpServletResponseresponse){//TODOAuto-generatedmethodstubStringid=request.getParameter("id");Bookbook=bookManager.findByld(lnteger.parselnt(id));request.setAttribute("book",book);returnmapping.findForward("edit");}publicActionForwarddeletebook(ActionMappingmapping,ActionFormform,HttpServletRequestrequest,HttpServletResponseresponse){//TODOAuto-generatedmethodstubStringid=request.getParameter("id");

Bookbook=bookManager.findByld(lnteger.parselnt(id));if(bookManager.delete(book)){return listbook(mapping,form,request,response);}else{String message』删除失败!";request.setAttribute("message",message);return mapping.findForward("message");}}publicActionForwardlistbook(ActionMappingmapping,ActionFormform,HttpServletRequestrequest,HttpServletResponseresponse){//TODOAuto-generatedmethodstubListbooks=bookManager.findAll();request.setAttribute("books",books);returnmapping.findForward("list");}publicActionForwardsearchbook(ActionMappingmapping,ActionFormform,HttpServletRequestrequest,HttpServletResponseresponse){//TODOAuto-generatedmethodstubStringbookname=request.getParameter("bookname");Listbooks=bookManager.findByBookname(bookname);request.setAttribute("books",books);returnmapping.findForward("list");TOC\o"1-5"\h\z}publicvoidsetBookManager(IBookManagerbookManager){this.bookManager=bookManager;}publicIBookManagergetBookManager(){returnbookManager;}7■配置文件*MyEclipseStruts}7■配置文件*MyEclipseStruts⑴Iperties[c-sharp]viewplaincopyprint?Iog4j.rootLogger=WARN,stdoutlog4j.appender.stdout=org.apache.log4j.ConsoleAppenderlog4j.appender.stdout.layout=org.apache.log4j.PatternLayoutlog4j.appender.stdout.layout.ConversionPattern=%d%p[%c]-%m%n(2)hibernate.cfg.xml[c-sharp]viewplaincopyprint?<?xmlversion='1.0'encoding='UTF-8'?><!DOCTYPEhibernate-configurationPUBLIC"-//Hibernate/HibernateConfigurationDTD3.0//EN""/hibernate-configuration-3.0.dtd"><!--GeneratedbyMyEclipseHibernateTools. --><hibernate-configuration><session-factory><propertyname="dialect">org.hibernate.dialect.MySQLDialect</property><propertyname="connection.url">jdbc:mysql://localhost:3306/book</property><propertyname="connection.username">root</property><propertyname="connection.password">123</property><propertyname="connection.driver_class">com.mysql.jdbc.Driver</property><propertyname="file">mysql5</property><mappingresource="dao/Book.hbm.xml"/></session-factory></hibernate-configuration>

〈?xmlversion='1.0'encoding='UTF-8'?〉〈!DOCTYPEhibernate-configurationPUBLIC"-//Hibernate/HibernateConfigurationDTD""/hiberna<!一GeneratedbyMyEclipseHibernateTools.<hibernate-configuration>(session-factory〉(propertyname="dialect">org.hibernate.dialect.MySQL〈/property〉(propertyname="connection.url">jdbc:mysql://localhost:3306</property>(propertyname="connection.username(propertyname="connection.password(propertyname="connection.driver_ccom.mysql.jdbc.Driverbook.hbm.xml[c-sharp]viewplaincopyprint?<?xmlversion="1.0"encoding="utf-8"?><!DOCTYPEhibernate-mappingPUBLIC"-//Hibernate/HibernateMappingDTD3.0//EN""/hibernate-mapping-3-0.dtd"><!--MappingfileautogeneratedbyMyEclipsePersistenceTools--><hibernate-mapping><classname="dao.Book"table="book"catalog="book"><idname="id"type="java.lang.1nteger"><columnname="id"/><generatorclass="increment"/></id><propertyname="bookname"type="java.lang.String"><columnname="bookname"length="30"/></property><propertyname="bookauthor"type="java.lang.String"><column name="bookauthor"length="30"/></property><propertyname="bookprice"type="java.lang.Float"><column name="bookprice" precision="12"scale="0"/></property></class></hibernate-mapping>

〈?xmlversion="1.0"encoding="utf-8"?〉〈!DOCTYPEhibernate-mappingPUBLIC"-//Hibernate/Hi"/hibernate-mapping<!--MappingfileautogeneratedbyMyEclipsePersist—>〈hibernate-mapping〉</id> ” ” ”</id> ” ” ”(propertyname="bookname"type="java.lang.S(columnname="bookname"length="30"/>(/property〉(propertyname="bookauthor"type="java.lang〈columnname="bookauthor"length="30"/struts-config.xml[c-sharp]viewplaincopyprint?<?xmlversion="1.0"encoding="UTF-8"?><!DO

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论