• 1.25 MB
  • 2022-04-22 11:32:28 发布

《JSP实用教程》第二版 (耿祥义 著)课后习题答案 清华大学出版社

  • 197页
  • 当前文档由用户上传发布,收益归属用户
  1. 1、本文档共5页,可阅读全部内容。
  2. 2、本文档内容版权归属内容提供方,所产生的收益全部归内容提供方所有。如果您对本文有版权争议,可选择认领,认领后既往收益都归您。
  3. 3、本文档由用户上传,本站不保证质量和数量令人满意,可能有诸多瑕疵,付费之前,请仔细先通过免费阅读内容等途径辨别内容交易风险。如存在严重挂羊头卖狗肉之情形,可联系本站下载客服投诉处理。
  4. 文档侵权举报电话:19940600175。
'欢迎光临阳光大学生网,提供最全面的大学生课后习题答案和复习试题免费下载,http://www.sundxs.com/阳光大学生网我们希望呵护您的眼睛,关注您的成长,给您一片绿色的环境,欢迎加入我们,一起分享大学里的学习和生活感悟,免费提供:大学生课后答案,大学考试题及答案,大学生励志书籍。 (第二版)清华大学出版社(耿祥义张跃平编著)程序源代码I 摘要JSP是一种动态网页技术标准,利用这一技术可以建立安全、跨平台的先进动态网站。本书是一本实用教程,配备了大量的例题,叙述详细,通俗易懂,便于自学,特别注重结合实例讲解一些难点和关键技术。全书共分10章,内容包括JSP简介、JSP语法、内置对象、JSP与Javabean、文件操作、数据库操作、JavaServlet、MVC设计模式、JSP中使用XML等重要内容。本书所有知识都结合具体实例进行介绍.力求详略得当,突出JSP在开发Web动态网站方面的强大功能,使读者快速掌握和运用JSP的编程技巧。本书不仅可以作为大学计算机及相关专业的选修课教材,也适合自学者及网站开发人员参考使用。课后答案网II 课后答案网:www.hackshp.cn前言本书是《JSP实用教程》的第二版,继续保留原教材的特点——注重教材的可读性和实用性,许多例题都经过精心的考虑,即能帮助理解知识,同时又具有启发性。在第二版中增加了XML和MVC模式在Web设计中的应用,对全书章节的先后顺序和部分例题的内容做了调整。第1章介绍JSP重要性,对Tomcat服务器的安装与配置给予了详细介绍。第2章讲解JSP页面的基本构成、常用的JSP标记。第3章讲解内置对象,特别强调了这些内置对象在JSP应用开发中的重要性,结合实例使读者掌握内置对象的用法。第4章是JSP技术中很重要的内容,即怎样使用Javabean分离数据的显示和处理,这一章讲解了许多有一定应用价值的例子。第5章主要讲解怎样使用Java中的输入输出流实现文件的读写操作,在实例上特别强调怎样使用Javabean实现文件的读写操作。第6章涉及的内容是数据库,也是Web应用开发的非常重要的一部分内容,特别介绍了各种数据库的连接方式。第7章讲解JavaServlet,对servlet对象的运行原理给予了细致的讲解,许多例子都是大多数Web开发中经常使用的模块。在第8章对JavaServlet在MVC开发模式中的地位给予了重点介绍,并按着MVC模式给出了易于理解MVC设计模式的例子。第9章介绍了XML语言以及在JSP中怎样有效地使用XML文件。第10章是一个完整的网站,完全按着MVC模式开发设计,其目的是掌握一般Web应用中常用基本模块的开发方法。作者简介耿祥义,1995年中国科学技术大学博士毕业,获理学博士学位。1997年从中山大学博士后流动站出站。现任大连交通大学教授。已编写出版《Java2实用教程》、《Java课程设计》、《JSP实用教程》、《JSP基础教程》、《XML基础教程》等10余部教材。张跃平,现任大连交通大学讲师。已编写和参编出版《课后答案网VisualFoxPro课程设计》、《Java2实用教程》、《JSP实用教程》3部教材。希望本教材能对读者学习JSP有所帮助,并请读者批评指正(xygeng0629@sina.com)。编者2007年05月www.hackshp.cnIII若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn第1章JSP简介........................................................................................................................................................................................................................................................11例子11................................................................................................................................................................................................................................................................................................................................................................................................................................................11第2章JSP语法..........................................................................................................................................................................................................................................................22例子1..............................................................................................................................................................................................................................................................................................22<%@pagecontentType="text/html;charset=GB2312"%>..............................22<%date=newDate();//java程序片..................................................................................22<%=start%>......................................................22例子2..............................................................................................................................................................................................................................................................................................22例子33................................................................................................................................................................................................................................................................................................................................................................................................................................................33例子44................................................................................................................................................................................................................................................................................................................................................................................................................................................33例子55................................................................................................................................................................................................................................................................................................................................................................................................................................................44例子66................................................................................................................................................................................................................................................................................................................................................................................................................................................44例子77................................................................................................................................................................................................................................................................................................................................................................................................................................................55例子88................................................................................................................................................................................................................................................................................................................................................................................................................................................55例子99................................................................................................................................................................................................................................................................................................................................................................................................................................................66例子1010.............................................................................................................................................................................................................................................................................................................................................................................................................................................77例子11..............................................................................................................................................................................................................................................................................................7课后答案网7例子1212.............................................................................................................................................................................................................................................................................................................................................................................................................................................88例子1313.............................................................................................................................................................................................................................................................................................................................................................................................................................................99第3章JSP内置对象....................................................................................................................................................................................................................................10www.hackshp.cn10例子11.............................................................................................................................................................................................................................................................................................................................................................................................................................................1010例子22.............................................................................................................................................................................................................................................................................................................................................................................................................................................1010例子33..............................................................................................................................................................................................................................................................................................11例子44.............................................................................................................................................................................................................................................................................................................................................................................................................................................1212例子55.............................................................................................................................................................................................................................................................................................................................................................................................................................................1414例子66.............................................................................................................................................................................................................................................................................................................................................................................................................................................1515例子77.............................................................................................................................................................................................................................................................................................................................................................................................................................................1616I若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn例子88.............................................................................................................................................................................................................................................................................................................................................................................................................................................1717例子9............................................................................................................................................................................................................................................................................................1717例子10..........................................................................................................................................................................................................................................................................................1818例子11..........................................................................................................................................................................................................................................................................................1818例子12..........................................................................................................................................................................................................................................................................................1919例子13..........................................................................................................................................................................................................................................................................................2020例子1414.......................................................................................................................................................................................................................................................................................................................................................................................................................................2121例子15..........................................................................................................................................................................................................................................................................................2222例子1616.......................................................................................................................................................................................................................................................................................................................................................................................................................................2424例子1717.......................................................................................................................................................................................................................................................................................................................................................................................................................................2525例子18..........................................................................................................................................................................................................................................................................................2727例子19..........................................................................................................................................................................................................................................................................................2929第4章JSP与JavaBean............................................................................................................................................................................................................................3131Circle.javaCircle.java.....................................................................................................................................................................................................................................................................................................................................................................................................................3131例子1............................................................................................................................................................................................................................................................................................3131例子22.............................................................................................................................................................................................................................................................................................................................................................................................................................................3232例子33.............................................................................................................................................................................................................................................................................................................................................................................................................................................32课后答案网32NewCircle.javaNewCircle.java.............................................................................................................................................................................................................................................................................................................................................................................................3232例子44.............................................................................................................................................................................................................................................................................................................................................................................................................................................3333Student.javaStudent.java............................................................................................................................................................................................................................................................................................................................................................................................................3333例子55.............................................................................................................................................................................................................................................................................................................................................................................................................................................34www.hackshp.cn34Goods.javaGoods.java..................................................................................................................................................................................................................................................................................................................................................................................................................3434例子6............................................................................................................................................................................................................................................................................................3535ListFile.javaListFile.java............................................................................................................................................................................................................................................................................................................................................................................................................3636例子77.............................................................................................................................................................................................................................................................................................................................................................................................................................................3636三角形bean..........................................................................................................................................................................................................................................................................3737Triangle.javaTriangle.java........................................................................................................................................................................................................................................................................................................................................................................................................................3737四则运算bean..................................................................................................................................................................................................................................................................3838II若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnComputerBean.java......................................................................................................................38computer.jsp.................................................................................................................................40计数器bean..........................................................................................................................................................................................................................................................................4040CounterCount.java.......................................................................................................................40comeOne.jsp.................................................................................................................................42comeTwo.jsp................................................................................................................................42浏览图像bean................................................................................................................................................................................................................................................................4242Play.java.......................................................................................................................................42play.jsp.........................................................................................................................................43成绩单bean........................................................................................................................................................................................................................................................................4444ScoreList.java...............................................................................................................................44studentScore.jsp...........................................................................................................................45日历bean..................................................................................................................................................................................................................................................................................4646CalendarBean.java.......................................................................................................................46showCalendar.jsp.........................................................................................................................48第5章JSP中的文件操作......................................................................................................................................................................................................................4949例子11.............................................................................................................................................................................................................................................................................................................................................................................................................................................4949FileDir.java...................................................................................................................................49fileAndDir.jsp...............................................................................................................................50例子22.............................................................................................................................................................................................................................................................................................................................................................................................................................................5050ReadFile.java...............................................................................................................................50课后答案网selectDir.jsp..................................................................................................................................52listfile.jsp......................................................................................................................................52例子33.............................................................................................................................................................................................................................................................................................................................................................................................................................................5353WriterFile.java.............................................................................................................................53www.hackshp.cnwritefile.jsp..................................................................................................................................54例子44.............................................................................................................................................................................................................................................................................................................................................................................................................................................5555UpFile.java................................................................................................................................55upfile.jsp.......................................................................................................................................58show.jsp......................................................................................................................................58例子55.............................................................................................................................................................................................................................................................................................................................................................................................................................................5858DownLoadFile.java......................................................................................................................58downfile.jsp..................................................................................................................................59例子66.............................................................................................................................................................................................................................................................................................................................................................................................................................................6060III若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnReadByRow.java..........................................................................................................................60selectfile.jsp.................................................................................................................................61readByRow.jsp.............................................................................................................................62例子77.............................................................................................................................................................................................................................................................................................................................................................................................................................................6262Test.java....................................................................................................................................62test.jsp..........................................................................................................................................65第6章JSP中使用数据库......................................................................................................................................................................................................................6767例子11.............................................................................................................................................................................................................................................................................................................................................................................................................................................6767showByJdbcOdbc.jsp...................................................................................................................67例子2............................................................................................................................................................................................................................................................................................6868showBySQLDriver.jsp................................................................................................................68例子3............................................................................................................................................................................................................................................................................................6969QueryBean.java..........................................................................................................................69inquire.jsp.....................................................................................................................................71例子4............................................................................................................................................................................................................................................................................................7272RandomQueryBean.java..............................................................................................................72random.jsp..................................................................................................................................74例子5............................................................................................................................................................................................................................................................................................7575ConditionQuery.java................................................................................................................75condition.jsp............................................................................................................................77课后答案网例子6............................................................................................................................................................................................................................................................................................7878OrderQuery.java...........................................................................................................................78sort.jsp..........................................................................................................................................79例子7............................................................................................................................................................................................................................................................................................8080KeyWordQuery.java....................................................................................................................80www.hackshp.cnkeyWord.jsp................................................................................................................................82例子8............................................................................................................................................................................................................................................................................................8282AddBean.java..............................................................................................................................82add.jsp........................................................................................................................................84例子9............................................................................................................................................................................................................................................................................................8585ShowRecordByPage.java............................................................................................................85showByPage.jsp..........................................................................................................................88例子10..........................................................................................................................................................................................................................................................................................8989linkOracle.jsp..........................................................................................................................89IV若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn例子11..........................................................................................................................................................................................................................................................................................9090linkMySql.jsp............................................................................................................................90例子12..........................................................................................................................................................................................................................................................................................9191MySqlBean.java..........................................................................................................................91mysql.jsp....................................................................................................................................93例子13..........................................................................................................................................................................................................................................................................................9494inquireExcel.jsp............................................................................................................................94例子14..........................................................................................................................................................................................................................................................................................9595ApplicationCon.java................................................................................................................95UseConBean.java.........................................................................................................................96chaxun.jsp....................................................................................................................................97例子15..........................................................................................................................................................................................................................................................................................9898PreparedQueryBean.java..........................................................................................................98pre.jsp......................................................................................................................................100例子16......................................................................................................................................................................................................................................................................................100100AddRecordBean.java.................................................................................................................100addRecord.jsp..........................................................................................................................102第7章JavaServlet基础............................................................................................................................................................................................................................104104HelloBeijing.java:........................................................................................................................................................................................................................................104104web.xmlweb.xml...........................................................................................................................................................................................................................................................................................................................................................................................................................104课后答案网104例子1..........................................................................................................................................................................................................................................................................................105105giveRadius.jsp........................................................................................................................105Computer.java............................................................................................................................105例子2..........................................................................................................................................................................................................................................................................................106www.hackshp.cn106showLetter.jsp............................................................................................................................106ShowLetter.java......................................................................................................................106例子3..........................................................................................................................................................................................................................................................................................107107showPI.jsp................................................................................................................................107ComputerPI.java......................................................................................................................107例子4..........................................................................................................................................................................................................................................................................................108108method.jsp................................................................................................................................108GetSqare.java..........................................................................................................................108GetSquareOrCubic.java..........................................................................................................109V若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn例子5.............................................................................................................................................111input.jsp..................................................................................................................................111Verify.java..............................................................................................................................111ShowMessage.java.....................................................................................................................112例子6..........................................................................................................................................................................................................................................................................................113113Boy.java....................................................................................................................................113Look.java..................................................................................................................................114例子7..........................................................................................................................................................................................................................................................................................115115getLetter.jsp................................................................................................................................115inputLetter.jsp.............................................................................................................................115HandleGuess.java.......................................................................................................................116第8章基于Servlet的MVC模式....................................................................................................................................................................................................118118web.xml....................................................................................................................................................................................................................................................................................118118sun.yourservlet.HandleSumsun.yourservlet.HandleSum....................................................................................................................................................................................118118Series.java....................................................................................................................................................................................................................................................................118118inputMess.jspinputMess.jsp................................................................................................................................................................................................................................................................................................................................................................................................119119showResult.jsp........................................................................................................................................................................................................................................................120120HandleSum.java........................................................................................................................................................................................................................................................120120计算一元二次方程的根................................................................................................................................................................................................................................122课后答案网122Equation.java..............................................................................................................................122input.jsp......................................................................................................................................123show.jsp......................................................................................................................................123HandleData.java.........................................................................................................................124简单的计算器................................................................................................................................................................................................................................................................125www.hackshp.cn125ComputerBean.java....................................................................................................................125inputNumber.jsp.........................................................................................................................126showResult.jsp...........................................................................................................................126HandleComputer.java.................................................................................................................127读取文件................................................................................................................................................................................................................................................................................129129FileMessage.java........................................................................................................................129choiceFile.jsp.............................................................................................................................129showFile.jsp...............................................................................................................................130HandleFile.java..........................................................................................................................130VI若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn查询数据库........................................................................................................................................................................................................................................................................131131ShowRecordByPage.java...........................................................................................................131choiceDatabase.jsp.....................................................................................................................133showRecord.jsp..........................................................................................................................133HandleDatabase.java..................................................................................................................134第9章JSP中使用XML........................................................................................................................................................................................................................................139139例子11.......................................................................................................................................................................................................................................................................................................................................................................................................................................139139Score.xml..................................................................................................................................139input.jsp......................................................................................................................................140Number.java..............................................................................................................................140例子22.......................................................................................................................................................................................................................................................................................................................................................................................................................................142142trainList.xml...............................................................................................................................142train.jsp.......................................................................................................................................143SAXBean.java............................................................................................................................144例子33.......................................................................................................................................................................................................................................................................................................................................................................................................................................147147type.jsp....................................................................................................................................147formula.xml................................................................................................................................147show.css....................................................................................................................................148第10章基于会员制的网络广告系统........................................................................................................................................................................................150150head.txt................................................................................................................................................................................................................................................................................150150index.jsp............................................................................................................................................................................................................................................................................150课后答案网150web.xmlweb.xml...........................................................................................................................................................................................................................................................................................................................................................................................................................150150Register.javaRegister.java...................................................................................................................................................................................................................................................................................................................................................................................................152152register.jspregister.jsp...............................................................................................................................................................................................................................................................................................................................................................................................................153www.hackshp.cn153showRegisterMess.jspshowRegisterMess.jsp......................................................................................................................................................................................................................................................................................................................................................154154HandleRegister.javaHandleRegister.java...............................................................................................................................................................................................................................................................................................................................................................155155RequestDispatcherdispatcher=....................................................................................................................................................................................................157157Login.java........................................................................................................................................................................................................................................................................157157login.jsplogin.jsp...........................................................................................................................................................................................................................................................................................................................................................................................................................158158showLoginMess.jspshowLoginMess.jsp..................................................................................................................................................................................................................................................................................................................................................................158158HandleLogin.javaHandleLogin.java...........................................................................................................................................................................................................................................................................................................................................................................159159UploadFile.javaUploadFile.java....................................................................................................................................................................................................................................................................................................................................................................................161161VII若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnupload.jspupload.jsp..................................................................................................................................................................................................................................................................................................................................................................................................................162162showUploadMess.jsp........................................................................................................................................................................................................................................162162HandleUpload.java............................................................................................................................................................................................................................................163163MemberInform.java............................................................................................................................................................................................................................................167167ShowByPage.javaShowByPage.java...........................................................................................................................................................................................................................................................................................................................................................................168168choiceLookType.jsp........................................................................................................................................................................................................................................169169
分页显示全体会员........................................................................................................................................................................................................................................169169showAllMember.jsp............................................................................................................................................................................................................................................169169showLookedMember.jsp................................................................................................................................................................................................................................170170HandleDatabase.java....................................................................................................................................................................................................................................171171Password.java............................................................................................................................................................................................................................................................175175modifyPassword.jspmodifyPassword.jsp...............................................................................................................................................................................................................................................................................................................................................................175175showNewPasswor.jsp........................................................................................................................................................................................................................................176176HandlePassword.javaHandlePassword.java......................................................................................................................................................................................................................................................................................................................................................176176RequestDispatcherdispatcher=....................................................................................................................................................................................................177177ModifyMessage.javaModifyMessage.java............................................................................................................................................................................................................................................................................................................................................................178178choiceModifyMess.jspchoiceModifyMess.jsp......................................................................................................................................................................................................................................................................................................................................................179课后答案网179inputModifyMess.jspinputModifyMess.jsp.........................................................................................................................................................................................................................................................................................................................................................179179GetOldMess.javaGetOldMess.java..............................................................................................................................................................................................................................................................................................................................................................................180180RequestDispatcherdispatcher=....................................................................................................................................................................................................182182HandleModifyMess.javaHandleModifyMess.java..........................................................................................................................................................................................................................................................................................................................................182www.hackshp.cn182RequestDispatcherdispatcher=....................................................................................................................................................................................................184184HandleExit.javaHandleExit.java....................................................................................................................................................................................................................................................................................................................................................................................184184VIII若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn第1章JSP简介例子1eexample1_1.jspxample1_1.jsp<%@pagecontentType="text/html;charset=GB2312"%>

这是一个简单的JSP页面

<%inti,sum=0;for(i=1;i<=100;i++){sum=sum+i;}%>
1到100的连续和是:<%=sum%>
课后答案网www.hackshp.cn1若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn第2章JSP语法例子1example2_1.jsp<%@pagecontentType="text/html;charset=GB2312"%><%@pageimport="java.util.Date"%><%!Datedate;//数据声明intstart,end,sum;publicintcontinueSum(intstart,intend)//方法声明{for(inti=start;i<=end;i++)sum=sum+i;returnsum;}%>

程序片创建Date对象:<%date=newDate();//java程序片out.println("
"+date);start=1;end=100;sum=continueSum(start,end);%>课后答案网
从<%=start%>至<%=end%>的连续和是www.hackshp.cn<%=sum%>例子2eexample2_2.jspxample2_2.jsp:<%@pagecontentType="text/html;charset=GB2312"%><%!inti=0;%><%i++;%>2若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn

您是第<%=i%>个访问本站的客户。例子3eexample2_xample2_xample2_333.jsp.jsp:<%@pagecontentType="text/html;charset=GB2312"%><%!doublex,y;doublemulti(doublex,doubley){returnx*y;}doublediv(doublex,doubley){returnx/y;}%><%x=127;y=18;out.println("调用multi方法计算"+x+"与"+y+"之积:");doublea=multi(x,y);out.println(a);x=a;out.println("
调用div方法计算"+x+"除以"+y+"的商:");课后答案网doubleb=div(x,y);out.println(b);%>例子4www.hackshp.cneexample2_xample2_xample2_444.jsp.jsp<%@pagecontentType="text/html;Charset=GB2312"%><%!intcount=0;//被客户共享的countsynchronizedvoidsetCount()//synchronized修饰的方法{count++;}%><%setCount();out.println("您是第"+count+"个访问本站的客户");%>3若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn例子5eexample2_xample2_xample2_5.jsp5.jsp<%@pagecontentType="text/html;Charset=GB2312"%>

输出英文字母.<%charstart="A",end="M",c;intsize=2;%>
用<%=size%>磅字号输出><%for(c=start;c<=end;c++){%><%=c%>,<%}%><%size=4;start=(char)(end+1);end="Z";%>
用<%=size%>磅字号输出课后答案网><%for(c=start;c<=end;c++){%><%=c%>,<%}www.hackshp.cn%>例子6eexample2_xample2_xample2_666.jsp.jsp:<%@pagecontentType="text/html;charset=GB2312"%><%doublea=12.89;intx=12,y=10;%>计算表达式a+x*y-100/x+x%5的值:4若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn<%=a+x*y-100/x+x%5%>
计算表达式x>y&&a>0的值:<%=x>y&&a>0%>
计算表达式sin(x)+cos(y):<%=Math.sin(x)+Math.cos(y)%>
求8的平方根:<%=Math.sqrt(8)%>例子7eexample2_xample2_xample2_777.jsp.jsp:<%@pagecontentType="text/html;charset=GB2312"%>抽取字符串"C:myfilejspfileexample.jsp"中的"example.jsp"<%--下面是成员变量的声明--%><%!Strings="C:\myfile\jspfile\example.jsp";%><%--下面是Java程序片--%><%intindex=s.lastIndexOf("\");Stringstr=s.substring(index+1);%>
<%--下面是Java表达式--%>课后答案网<%=str%>例子8firstfirst.jsp.jsp<%@pagecontentType="text/html;Charset=GB2312"%>www.hackshp.cn

使用html处理所接受到的信息.secondsecond.jsp.jsp<%@pagecontentType="application/vnd.ms-powerpoint"%>

启动powerpoint应用程序处理所接受到的信息.5若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnthirdthird.jsp.jsp<%@pagecontentType="image/x-xbitmap"%><%@pageimport="java.awt.*"%><%@pageimport="java.io.*"%><%@pageimport="java.awt.image.*"%><%@pageimport="java.awt.geom.*"%><%@pageimport="com.sun.image.codec.jpeg.*"%><%intwidth=260,height=260;BufferedImageimage=newBufferedImage(width,height,BufferedImage.TYPE_INT_RGB);Graphicsg=image.getGraphics();g.setColor(Color.white);g.fillRect(0,0,width,height);Graphics2Dg_2d=(Graphics2D)g;Ellipse2Dellipse=newEllipse2D.Double(40,50,100,40);g_2d.setColor(Color.blue);g_2d.draw(ellipse);Polygonpolygon=newPolygon();polygon.addPoint(12,34);polygon.addPoint(51,134);polygon.addPoint(102,34);g_2d.drawPolygon(polygon);g_2d.dispose();课后答案网OutputStreamoutClient=response.getOutputStream();//获取指向客户端的输出流JPEGImageEncoderencoder=JPEGCodec.createJPEGEncoder(outClient);encoder.encode(image);%>例子9www.hackshp.cneexample2_xample2_xample2_9.9.9.jspjsp<%@pagecontentType="text/html;charset=GB2312"%><%@pageinfo="清华大学"%><%Strings=getServletInfo();%><%=s%>
<%=s%>出版社是中国著名出版社
<%=s%>是全国著名的高等学府6若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn例子10firstEfirstExample2_xample2_xample2_101010.jsp.jsp<%@pagecontentType="text/html;charset=GB2312"%><%@includefile="myfile/ok.txt"%>

我是firstExample.jsp页面secondEsecondExample2_xample2_xample2_101010.jsp.jsp(效果如图2.9(b)所示)<%@pagecontentType="text/html;charset=GB2312"%><%@includefile="myfile/ok.txt"%>

我是secondExample.jsp页面上述firstExample2_10.jsp等价于下面的JSP文件same.jsp:samesame.jsp.jsp<%@pagecontentType="text/html;Charset=GB2312"%>欢迎去firstExample2_10.jsp页面
欢迎去secondExample2_10.jsp页面

我是firstExample.jsp页面课后答案网例子11example2_11example2_11.jsp.jsp<%@pagecontentType="text/html;charset=GB2312"%><%doublea=3,b=4,c=5;%>www.hackshp.cn
加载trangle.jsp计算三边为<%=a%>,<%=b%>,<%=c%>的三角形面积:"/>"/>"/>trangletrangle.jsp.jsp<%@pagecontentType="text/html;charset=GB2312"%>7若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn<%!publicStringgetArea(doublea,doubleb,doublec){if(a+b>c&&a+c>b&&c+b>a){doublep=(a+b+c)/2.0;doublearea=Math.sqrt(p*(p-a)*(p-b)*(p-c));return""+area;}else{return(""+a+","+b+","+c+"不能构成一个三角形,无法计算面积");}}%><%StringsideA=request.getParameter("sideA");StringsideB=request.getParameter("sideB");StringsideC=request.getParameter("sideC");doublea=Double.parseDouble(sideA);doubleb=Double.parseDouble(sideB);doublec=Double.parseDouble(sideC);%>

我是被加载的文件,负责计算三角形的面积
给我传递的三边是:<%=sideA%>,<%=sideB%>,<%=sideC%>
三角形的面积:<%=getArea(a,b,c)%>课后答案网例子12eexample2_1xample2_1xample2_1222.jsp.jsp<%@pagecontentType="text/html;charset=GB2312"%><%doublei=Math.random();www.hackshp.cnif(i>0.5){%>"/><%}else{%>"/>8若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn<%}%>ffrontrontrontSSSide.jspide.jsp<%@pagecontentType="text/html;charset=GB2312"%><%Strings=request.getParameter("number");out.println("
传递过来的值是"+s);%>
钱币图像reverseSide.jsp<%@pagecontentType="text/html;charset=GB2312"%><%Strings=request.getParameter("number");out.println("传递过来的值是"+s);%>
钱币图像例子13eexample2_xample2_xample2_131313.jsp.jsp:课后答案网<%@pagecontentType="text/html;charset=GB2312"%>PlugintagOBJECTorEMBEDnotsupportedbybrowser.www.hackshp.cn9若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn第3章JSP内置对象例子1eexample3_1.jspxample3_1.jsp<%@pagecontentType="text/html;charset=GB2312"%>computercomputer.jsp.jsp<%@pagecontentType="text/html;charset=GB2312"%><%StringsideA=request.getParameter("sizeA");StringsideB=request.getParameter("sizeB");StringsideC=request.getParameter("sizeC");try{doublea=Double.parseDouble(sideA);doubleb=Double.parseDouble(sideB);课后答案网doublec=Double.parseDouble(sideC);doublep=(a+b+c)/2,area=0;area=Math.sqrt(p*(p-a)*(p-b)*(p-c));out.println("
三角形面积"+area);}www.hackshp.cncatch(NumberFormatExceptionee){out.println("
请输入数字字符");}%>例子2eexample3_2.jspxample3_2.jsp(如图3.2所示)<%@pagecontentType="text/html;charset=GB2312"%>10若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn<%StringtextContent=request.getParameter("girl");doublenumber=0,r=0;if(textContent==null){textContent="0";}try{number=Double.parseDouble(textContent);if(number>=0){r=Math.sqrt(number);out.print(String.valueOf(number)+"的平方根:");out.print("
"+String.valueOf(r));}else{out.print("
"+"请输入一个正数");}}catch(NumberFormatExceptione){out.print("
"+"请输入数字字符");}%>课后答案网例子3example3_3example3_3.jsp.jsp<%@pagecontentType="text/html;Charset=GB2312"%>www.hackshp.cn11若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnshowMessage1showMessage1.jsp.jsp<%@pagecontentType="text/html;Charset=GB2312"%>

获取文本框提交的信息:<%StringtextContent=request.getParameter("boy");%>
<%=textContent%>

获取按钮的名字:<%StringbuttonName=request.getParameter("submit");%>
<%=buttonName%>showMessage2showMessage2.jsp.jsp<%@pagecontentType="text/html;charset=GB2312"%>

获取文本框提交的信息:<%StringtextContent=request.getParameter("boy");byteb[]=textContent.getBytes("ISO-8859-1");textContent=newString(b);%>
<%=textContent%>课后答案网

获取按钮的名字:<%StringbuttonName=request.getParameter("submit");bytec[]=buttonName.getBytes("ISO-8859-1");buttonName=newString(c);%>www.hackshp.cn
<%=buttonName%>例子4eexample3_4.jspxample3_4.jsp<%@pagecontentType="text/html;Charset=GB2312"%><%@pageimport="java.util.*"%><%Stringprotocol=request.getProtocol();//协议Stringpath=request.getServletPath();//请求的页面12若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnStringmethod=request.getMethod();//提交信息的方式StringuserAgentHeader=request.getHeader("User-Agent");//User-Agent头的值StringacceptHeader=request.getHeader("accept");//accept头的值StringhostHeader=request.getHeader("Host");//Host头的值StringacceptEncodingHeader=request.getHeader("accept-encoding");//accept-encoding头的值StringclientIP=request.getRemoteAddr();//客户的IP地址StringserverName=request.getServerName();//服务器的名称intserverPort=request.getServerPort();//服务器的端口号%>
客户使用的协议是:<%=protocol%>
客户请求的页面:<%=path%>
客户提交信息的方式:<%=method%>
头文件中User-Agent头的值:<%=userAgentHeader%>
accept头的值:<%=acceptHeader%>
Host头的值:<%=hostHeader%>
accept-encoding头的值:<%=acceptEncodingHeader%>
客户的IP地址:<%=clientIP%>
服务器的端口号:<%=serverPort%>
获取客户端提交的所有参数的名字:<%EnumerationenumOne=request.getParameterNames();while(enumOne.hasMoreElements()){Strings=(String)enumOne.nextElement();课后答案网out.println(s);}%>
获取头名字的一个枚举:<%Enumerationenum_headed=request.getHeaderNames();www.hackshp.cnwhile(enum_headed.hasMoreElements()){Strings=(String)enum_headed.nextElement();out.println(s);}%>
获取头文件中指定头名字cookie的全部值的一个枚举:<%Enumerationenum_headedValues=request.getHeaders("cookie");while(enum_headedValues.hasMoreElements()){Strings=(String)enum_headedValues.nextElement();out.println(s);}13若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn%>例子5example3_5example3_5.jsp.jsp<%@pagecontentType="text/html;Charset=GB2312"%>
输入您的姓名:

选择性别:

选择您喜欢的球队:国际米兰队AC米兰队罗马队慕尼黑队
receivereceive.jsp.jsp课后答案网<%@pagecontentType="text/html;Charset=GB2312"%><%StringyourName=request.getParameter("name");//获取text提交的值StringyourSex=request.getParameter("R");//获取radio提交的值StringsecretMess=request.getParameter("secret");www.hackshp.cn//获取hidden提交的值StringitemName[]=request.getParameterValues("item");//获取checkbox提交的值out.println("

您的姓名:"+yourName+"

");out.println("

您的性别:"+yourSex+"

");out.println("

您喜欢的球队:");if(itemName==null){out.print("一个都不喜欢");}else{for(intk=0;k你提交的隐藏信息:"+secretMess);%>例子6select.jsp<%@pagecontentType="text/html;charset=GB2312"%>

选择计算和的方式:
计算1到n的连续和计算1到n的平方和计算1到n的立方和
选择n的值:
n=20n=40n=50n=100
课后答案网
sum.jsp<%@pagecontentType="text/html;charset=GB2312"%>
www.hackshp.cn<%longsum=0;Strings1=request.getParameter("sum");Strings2=request.getParameter("n");if(s1.equals("1")){intn=Integer.parseInt(s2);for(inti=1;i<=n;i++){sum=sum+i;}}elseif(s1.equals("2")){intn=Integer.parseInt(s2);15若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnfor(inti=1;i<=n;i++){sum=sum+i*i;}}elseif(s1.equals("3")){intn=Integer.parseInt(s2);for(inti=1;i<=n;i++){sum=sum+i*i*i;}}%>

您的求和结果:<%=sum%>

例子7example3_7example3_7.jsp.jsp<%@pagecontentType="text/html;Charset=GB2312"%>输入您的姓名:课后答案网选择性别:女www.hackshp.cn选择您喜欢的球队:国际米兰队AC米兰队罗马队慕尼黑队16若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn例子8example3_8example3_8.jsp.jsp<%@pagecontentType="text/html;charset=GB2312"%>
选择一副图像:人物动物
选择视频或音乐:祝你快乐弯弯的月亮
课后答案网showshow.jsp.jsp<%@pagecontentType="text/html;charset=GB2312"%>www.hackshp.cn<%Strings1=request.getParameter("image");Strings2=request.getParameter("video");%>"width=200height=160>图像"width=300height=180>视频例子9eexample3_xample3_xample3_999.jsp.jsp<%@pagecontentType="text/html;charset=GB2312"%>17若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn

我正在学习response对象的
setContentType方法

将当前页面保存为word文档吗?<%Stringstr=request.getParameter("submit");if(str==null){str="";}if(str.equals("yes")){response.setContentType("application/msword;charset=GB2312");}%>例子10eexample3_xample3_xample3_101010.jsp.jsp<%@pagecontentType="text/html;charset=GB2312"%><%@pageimport="java.util.*"%>

现在的时间是:
<%out.println(""+newDate());课后答案网response.setHeader("Refresh","5");%>例子11eexample3_xample3_11.jspwww.hackshp.cn<%@pagecontentType="text/html;charset=GB2312"%>

填写姓名:
formform.jsp.jsp18若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn<%@pagecontentType="text/html;Charset=GB2312"%><%Stringstr=request.getParameter("boy");if(str.length()==0){response.sendRedirect("example3_11.jsp");}else{out.print("欢迎您来到本网页!");out.print(str);}%>例子12eexample3_1xample3_1xample3_1222.jsp.jsp<%@pagecontentType="text/html;charset=GB2312"%>

点击下面的超链接:
bird1:欢迎你吗?
bird2:欢迎你吗?
bird3:欢迎你吗?bird1.jsp课后答案网<%response.setStatus(408);out.print("不显示了");%>www.hackshp.cnbird2.jsp<%@pagecontentType="text/html;charset=GB2312"%><%response.setStatus(200);out.println("ok");%>bird3.jsp<%@pagecontentType="text/html;charset=GB2312"%><%response.setStatus(500);19若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn%>例子13firstfirst.jsp.jsp<%@pagecontentType="text/html;charset=GB2312"%>我是first.jsp页面,输入你的姓名连接到second.jsp<%Stringid=session.getId();out.println("您的session对象的ID是:
"+id);%>secondsecond.jsp.jsp<%@pagecontentType="text/html;Charset=GB2312"%>我是second.jsp页面课后答案网<%Stringid=session.getId();out.println("您的session对象的ID是:
"+id);%>
点击超链接,连接到third.jsp的页面。欢迎去third.jsp页面!www.hackshp.cnthirdthird.jsp.jsp<%@pagecontentType="text/html;charset=GB2312"%>我是third.jsp页面<%Stringid=session.getId();out.println("您的session对象的ID是:
"+id);%>
点击超链接,连接到first.jsp的页面。欢迎去first.jsp!20若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn例子14main.jsp<%@pagecontentType="text/html;Charset=GB2312"%>

欢迎来到本页面,请输入您的姓名<%Stringname=request.getParameter("name");if(name==null){name="";}else{session.setAttribute("customerName",name);}%><%if(name.length()>0){%>

点击超链接,连接到book.jsp的页面,去选择书籍。课后答案网欢迎去选择书籍!<%}%>book.jsp<%@pagecontentType="text/html;charset=GB2312"%>www.hackshp.cn

点击超链接,连接到main.jsp的页面,去修改姓名。欢迎去main.jsp!

请选择您要购买的书籍:Java教程数据库原理操作系统C语言教程
21若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn<%StringbookName[]=request.getParameterValues("choice");if(bookName!=null){for(intk=0;k去结帐:欢迎去count.jsp!count.jsp<%@pagecontentType="text/html;Charset=GB2312"%><%@pageimport="java.util.*"%>这里是结帐处,您的姓名以及选择的书籍:<%StringpersonName=(String)session.getAttribute("customerName");out.println("
您的姓名:"+personName);EnumerationenumGoods=session.getAttributeNames();out.println("
购物车中的商品:
");while(enumGoods.hasMoreElements()){Stringkey=(String)enumGoods.nextElement();课后答案网Stringgoods=(String)session.getAttribute(key);if(!(goods.equals(personName)))out.println(goods+"
");}%>www.hackshp.cn连接到book.jsp的页面,继续购买书籍:欢迎去book.jsp!
连接到main.jsp的页面,去修改姓名:欢迎去main.jsp!
例子15getNumbergetNumber.jsp.jsp<%@pagecontentType="text/html;charset=GB2312"%>

随机分给了你一个1到100之间的数,请猜!<%intnumber=(int)(Math.random()*100)+1;22若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnsession.setAttribute("count",newInteger(0));session.setAttribute("save",newInteger(number));%>

输入你的所猜的数:result.jsp<%Stringstr=request.getParameter("boy");if(str.length()==0){response.sendRedirect("getNumber.jsp");}else{intguessNumber=Integer.parseInt(str);Integerinteger=(Integer)session.getAttribute("save");intrealnumber=integer.intValue();if(guessNumber==realnumber){intn=((Integer)session.getAttribute("count")).intValue();n=n+1;session.setAttribute("count",newInteger(n));课后答案网response.sendRedirect("success.jsp");}elseif(guessNumber>realnumber){intn=((Integer)session.getAttribute("count")).intValue();n=n+1;www.hackshp.cnsession.setAttribute("count",newInteger(n));response.sendRedirect("large.jsp");}elseif(guessNumber23若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnlarge.jsp<%@pagecontentType="text/html;charset=GB2312"%>

所猜的数比实际的数大,请再猜:small.jsp<%@pagecontentType="text/html;charset=GB2312"%>

所猜的数比实际的数小,请再猜:success.jsp<%@pagecontentType="text/html;charset=GB2312"%><%intcount=((Integer)session.getAttribute("count")).intValue();intnum=((Integer)session.getAttribute("save")).intValue();课后答案网%>

恭喜你,猜对了

您共猜了<%=count%>次

这个数字就是<%=num%>www.hackshp.cn例子16example3_16example3_16.jsp.jsp<%@pagecontentType="text/html;Charset=GB2312"%><%@pageimport="java.util.*"%><%session.setMaxInactiveInterval(15);booleanboo=session.isNew();out.println("
如果你第一次访问当前web服务目录,您的会话是新的");out.println("
如果你不是首次访问当前web服务目录,您的会话不是新的");24若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnout.println("
会话是新的吗?:"+boo);out.println("
欢迎来到本页面,您的session允许的最长发呆时间为"+session.getMaxInactiveInterval()+"秒");out.println("
您的session的创建时间是"+newDate(session.getCreationTime()));out.println("
您的session的Id是"+session.getId());LonglastTime=(Long)session.getAttribute("lastTime");if(lastTime==null){longn=session.getLastAccessedTime();session.setAttribute("lastTime",newLong(n));}else{longm=session.getLastAccessedTime();longn=((Long)session.getAttribute("lastTime")).longValue();out.println("
您的发呆时间大约是"+(m-n)+"毫秒,大约"+(m-n)/1000+"秒");session.setAttribute("lastTime",newLong(m));}%>例子17comeOnecomeOne.jsp.jsp<%@pagecontentType="text/html;Charset=GB2312"%>课后答案网<%@taglibprefix="person"tagdir="/WEB-INF/tags"%>

Welcome欢迎您访问本站,这是本网站的comeTwo.jsp页面
您是第www.hackshp.cn<%=(String)session.getAttribute("count")%>个访问本网站的客户。欢迎去comeTwo.jsp参观comeTwocomeTwo.jsp.jsp<%@pagecontentType="text/html;Charset=GB2312"%><%@taglibprefix="person"tagdir="/WEB-INF/tags"%>25若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn

欢迎您访问本站,这是本网站的comeOne.jsp页面
您是第<%=(String)session.getAttribute("count")%>个访问本网站的客户。欢迎去comeOne.jsp参观countcount...jspjsp<%@pagecontentType="text/html;charset=GB2312"%><%@pageimport="java.io.*"%><%!intnumber=0;Filefile=newFile("countNumber.txt");synchronizedvoidcountPeople()//计算访问次数的同步方法{if(!file.exists()){number++;try{file.createNewFile();FileOutputStreamout=newFileOutputStream(file);DataOutputStreamdataOut=newDataOutputStream(out);dataOut.writeInt(number);out.close();dataOut.close();}catch(IOExceptionee){}课后答案网}else{try{FileInputStreamin=newFileInputStream(file);DataInputStreamdataIn=newDataInputStream(in);number=dataIn.readInt();number++;www.hackshp.cnin.close();dataIn.close();FileOutputStreamout=newFileOutputStream(file);DataOutputStreamdataOut=newDataOutputStream(out);dataOut.writeInt(number);out.close();dataOut.close();}catch(IOExceptionee){}}26若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn}%><%Stringstr=(String)session.getAttribute("count");if(session.isNew()){out.println("请首先访问其它网页");}else{if(str==null){countPeople();StringpersonCount=String.valueOf(number);session.setAttribute("count",personCount);}}%>例子18submit.jsp<%@pagecontentType="text/html;charset=GB2312"%>输入您的名字:

输入您的留言标题:

输入您的留言:

www.hackshp.cnmessagePane.jsp<%@pagecontentType="text/html;Charset=GB2312"%><%@pageimport="java.util.*"%><%!Vectorv=newVector();inti=0;ServletContextapplication;synchronizedvoidsendMessage(Strings){application=getServletContext();;i++;27若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnv.add("No."+i+","+s);application.setAttribute("Mess",v);}%><%Stringname=request.getParameter("peopleName");Stringtitle=request.getParameter("Title");Stringmessages=request.getParameter("messages");if(name==null){name="guest"+(int)(Math.random()*10000);}if(title==null){title="无标题";}if(messages==null){messages="无信息";}Strings="姓名:"+name+"#"+"标题:"+title+"#"+"内容:"+"
"+messages;sendMessage(s);out.print("您的信息已经提交!");%>返回showMessage.jsp课后答案网<%@pagecontentType="text/html;charset=GB2312"%><%@pageimport="java.util.*"%><%Vectorv=(Vector)application.getAttribute("Mess");for(inti=0;i"+str);}}%>28若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn例子19example3_19example3_19.jsp.jsp<%@pagecontentType="text/html;charset=GB2312"%><%@pageimport="java.util.*"%><%!publicStringgetDayWeek(intn){Stringweek[]={"星期日","星期一","星期二","星期三","星期四","星期五","星期六"};returnweek[n];}%><%Calendarcalendar=Calendar.getInstance();//创建一个日历对象。calendar.setTime(newDate());//用当前时间初始化日历时间。String年=String.valueOf(calendar.get(Calendar.YEAR)),月=String.valueOf(calendar.get(Calendar.MONTH)+1),日=String.valueOf(calendar.get(Calendar.DAY_OF_MONTH)),星期=getDayWeek(calendar.get(Calendar.DAY_OF_WEEK)-1);inthour=calendar.get(Calendar.HOUR_OF_DAY),minute=calendar.get(Calendar.MINUTE),second=calendar.get(Calendar.SECOND);out.println("");out.println("");out.println("现在的时间:");课后答案网out.println(""+年+"年");out.println(""+月+"月");out.println(""+日+"日");out.println(""+星期+"");out.println(""+hour+"点");www.hackshp.cnout.println(""+minute+"分");out.println(""+second+"秒");out.println("");out.println("");if(日.equals("26")){out.print("

今天是病毒容易发作的日子!

");}else{out.print("

注意防范病毒!

");}29若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn%>
课后答案网www.hackshp.cn30若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn第4章JSP与JavaBeanCircle.javapackagetom.jiafeiimportjava.io.*;publicclassCircle{intradius;publicCircle(){radius=1;}publicintgetRadius(){returnradius;}publicvoidsetRadius(intnewRadius){radius=newRadius;}publicdoublecircleArea(){returnMath.PI*radius*radius;}publicdoublecirclLength(){return2.0*Math.PI*radius;}课后答案网}例子1useBean.jspwww.hackshp.cn<%@pagecontentType="text/html;charset=GB2312"%><%@pageimport="tom.jiafei.Circle"%><%--通过上述JSP标记,客户获得了一个作用域是page,名字是circle的bean--%><%circle.setRadius(888);%>

圆的半径是:<%=circle.getRadius()%>31若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn

圆的周长是:<%=circle.circlLength()%>

圆的面积是:<%=circle.circleArea()%>例子2bean1.jsp<%@pagecontentType="text/html;charset=GB2312"%><%@pageimport="tom.jiafei.Circle"%>

圆的半径是:<%=girl.getRadius()%>
bean2.jspbean2.jsp<%@pagecontentType="text/html;charset=GB2312"%><%@pageimport="tom.jiafei.Circle"%>

圆的半径是:<%=girl.getRadius()%><%girl.setRadius(400);%>

修改后的圆的半径是:<%=girl.getRadius()%>
bean1.jsp课后答案网例子3appbean.jsp<%@pagecontentType="text/html;charset=GB2312"%><%@pageimport="tom.jiafei.*"%>www.hackshp.cn

圆的初始半径是:<%=girl.getRadius()%><%girl.setRadius(1000);%>

修改后的圆的半径是:<%=girl.getRadius()%>NewNewCircle.javaCircle.javapackagetom.jiafei;importjava.io.*;32若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnpublicclassNewCircle{doubleradius=1,circleArea,circleLength;publicdoublegetRadius(){returnradius;}publicvoidsetRadius(doublenewRadius){radius=newRadius;}publicdoublegetCircleArea(){circleArea=Math.PI*radius*radius;returncircleArea;}publicdoublegetCircleLength(){circleLength=2.0*Math.PI*radius;returncircleLength;}}例子4beanGetbeanGetPPProperty.jsproperty.jsp<%@pagecontentType="text/html;charset=GB2312"%><%@pageimport="tom.jiafei.NewCircle"%>课后答案网<%apple.setRadius(100);%>圆的半径是:
圆的面积是:
圆的周长是:www.hackshp.cnStudent.javapublicclassStudent{Stringname=null;longnumber;doubleheight,weight;publicStringgetName(){returnname;}publicvoidsetName(StringnewName){name=newName;33若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn}publiclonggetNumber(){returnnumber;}publicvoidsetNumber(longnewNumber){number=newNumber;}publicdoublegetHeight(){returnheight;}publicvoidsetHeight(doublenewHeight){height=newHeight;}publicdoublegetWeight(){returnweight;}publicvoidsetWeight(doublenewWeight){weight=newWeight;}}例子5student.jsp<%@pagecontentType="text/html;charset=GB2312"%>课后答案网<%@pageimport="tom.jiafei.Student"%>名字是:www.hackshp.cn
学号是:"/>
身高是:
体重是:公斤Goods.javapackagetom.jiafei;34若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnpublicclassGoods{Stringname,goodsNumber;doubleprice;publicStringgetName(){returnname;}publicvoidsetName(StringnewName){name=newName;}publicStringgetGoodsNumber(){returngoodsNumber;}publicvoidsetGoodsNumber(Strings){goodsNumber=s;}publicdoublegetPrice(){returnprice;}publicvoidsetPrice(doublenewPrice){price=newPrice;}}课后答案网例子6goodsgoods.jsp.jsp<%@pagecontentType="text/html;Charset=GB2312"%>www.hackshp.cn<%@pageimport="tom.jiafei.*"%>输入商品的名称:
输入商品的代号:
输入商品的价格:

提交表单才能设置商品的信息35若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn
商品的名称:
商品的代号:
商品的价格:ListFile.javapackagetom.jiafei;importjava.io.*;classFileNameimplementsFilenameFilter{Stringstr=null;FileName(Strings){str="."+s;}publicbooleanaccept(Filedir,Stringname){returnname.endsWith(str);}}publicclassListFile{StringextendsName=null;StringBufferallFileName;publicvoidsetExtendsName(Strings){extendsName=s;}publicStringgetExtendsName()课后答案网{returnextendsName;}publicStringBuffergetFileName(){Filedir=newFile("d:/2000");FileNamehelp=newFileName(extendsName);www.hackshp.cnStringfile_name[]=dir.list(help);for(inti=0;i36若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn<%@pageimport="tom.jiafei.*"%>输入文件的扩展名:

扩展名是的文件有:
三角形beanTriangle.javapackagered.star;publicclassTriangle{doublesideA=-1,sideB=-1,sideC=-1,area=-1;booleantriangle;publicvoidsetSideA(doublea){sideA=a;}publicdoublegetSideA(){returnsideA;课后答案网}publicvoidsetSideB(doubleb){sideB=b;}publicdoublegetSideB()www.hackshp.cn{returnsideB;}publicvoidsetSideC(doublec){sideC=c;}publicdoublegetSideC(){returnsideC;}publicdoublegetArea(){doublep=(sideA+sideB+sideC)/2.0;if(triangle)37若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnarea=Math.sqrt(p*(p-sideA)*(p-sideB)*(p-sideC));returnarea;}publicbooleanisTriangle(){if(sideA<%@pageimport="red.star.Triangle"%>输入三角形三边:边A:边B:边C:课后答案网三角形的三边是:边A:,边B:,边C:.
这三个边能构成一个三角形吗?www.hackshp.cn
面积是:四则运算beanComputerBeanComputerBean.java.javapackagered.star;publicclassComputerBean{doublenumberOne,numberTwo,result;38若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnStringoperator="+";publicvoidsetNumberOne(doublen){numberOne=n;}publicdoublegetNumberOne(){returnnumberOne;}publicvoidsetNumberTwo(doublen){numberTwo=n;}publicdoublegetNumberTwo(){returnnumberTwo;}publicvoidsetOperator(Strings){operator=s.trim();;}publicStringgetOperator(){returnoperator;}publicdoublegetResult(){if(operator.equals("+")){result=numberOne+numberTwo;}课后答案网elseif(operator.equals("-")){result=numberOne-numberTwo;}elseif(operator.equals("*")){result=numberOne*numberTwo;www.hackshp.cn}elseif(operator.equals("/")){result=numberOne/numberTwo;}returnresult;}}39若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cncomputercomputer.jsp.jsp<%@pagecontentType="text/html;Charset=GB2312"%><%@pageimport="red.star.*"%>size=6>+-*/size=6>=
课后答案网计数器beanCounterCounterCountCountCount.java.javawww.hackshp.cnpackagered.star;importjava.io.*;publicclassComputerCount{intnumber=0;booleanisCome=false;Filefile=newFile("count.dat");40若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnprivatevoidcountPeople(){if(!file.exists()){number++;try{file.createNewFile();FileOutputStreamout=newFileOutputStream(file);DataOutputStreamdataOut=newDataOutputStream(out);dataOut.writeInt(number);out.close();dataOut.close();}catch(IOExceptionee){}}else{try{FileInputStreamin=newFileInputStream(file);DataInputStreamdataIn=newDataInputStream(in);number=dataIn.readInt();number++;in.close();dataIn.close();FileOutputStreamout=newFileOutputStream(file);DataOutputStreamdataOut=newDataOutputStream(out);dataOut.writeInt(number);out.close();课后答案网dataOut.close();}catch(IOExceptionee){}}isCome=true;www.hackshp.cn}publicintgetNumber(){if(isCome==false)countPeople();returnnumber;}}41若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cncomeOnecomeOne.jsp.jsp<%@pagecontentType="text/html;Charset=GB2312"%><%@pageimport="red.star.*"%>

Welcome欢迎您访问本站,这是本网站的comeOne.jsp页面
您是第个访问本网站的客户。欢迎去comeTwo.jsp参观comeTwocomeTwo.jsp.jsp<%@pagecontentType="text/html;Charset=GB2312"%><%@pageimport="red.star.*"%>

Welcome欢迎您访问本站,这是本网站的comeTwo.jsp页面
您是第课后答案网个访问本网站的客户。欢迎去comeOne.jsp参观浏览图像beanwww.hackshp.cnPlayPlay.java.javapackagered.star;importjava.io.*;classFileNameimplementsFilenameFilter{publicbooleanaccept(Filedir,Stringname){booleanboo=false;42若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnif(name.endsWith(".jpg")||name.endsWith(".JPG"))boo=true;returnboo;}}publicclassPlay{intimageNumber=0,max;StringpictureName[],playImage;publicPlay(){Filedir=newFile("D:/apache-tomcat-5.5.20/webapps/ch4/image");pictureName=dir.list(newFileName());max=pictureName.length;}publicvoidsetImageNumber(intn){if(n<0)n=max-1;if(n==max)n=0;imageNumber=n;}publicintgetImageNumber(){returnimageNumber;}课后答案网publicStringgetPlayImage(){playImage=newString("");returnplayImage;}www.hackshp.cn}playplay.jsp.jsp<%@pagecontentType="text/html;Charset=GB2312"%><%@pageimport="red.star.*"%>单击"上一张"或"下一张"按钮浏览图像43若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn

">">
成绩单beanScoreListScoreList.java.javapackagered.star;publicclassScoreList{StringstudentName,courseName="",score="";StringBufferscoreWatch=newStringBuffer();publicvoidsetScore(Stringn)课后答案网{score=n;}publicvoidsetStudentName(Strings){studentName=s;}www.hackshp.cnpublicvoidsetCourseName(Strings){courseName=s;}publicStringgetCourseName(){returncourseName;}publicStringBuffergetScoreWatch(){if(studentName!=null&&studentName.length()>0&&score.length()>0){scoreWatch.append("");scoreWatch.append("");44若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnscoreWatch.append(studentName);scoreWatch.append("");scoreWatch.append("");scoreWatch.append(""+score);scoreWatch.append("");scoreWatch.append("");studentName="";score="";}returnscoreWatch;}}studentScorestudentScore.jsp.jsp<%@pagecontentType="text/html;Charset=GB2312"%><%@pageimport="red.star.*"%>课后答案网课程名称:>
学生姓名:
学生成绩:www.hackshp.cn

45若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn日历beanCalendarBeanCalendarBean.java.javapackagered.star;importjava.util.*;publicclassCalendarBean{Stringcalendar=null;intyear=-1,month=-1;publicvoidsetYear(intyear){this.year=year;}publicintgetYear(){returnyear;}publicvoidsetMonth(intmonth){this.month=month;}publicintgetMonth(){returnmonth;}publicStringgetCalendar()课后答案网{StringBufferbuffer=newStringBuffer();Calendarrili=Calendar.getInstance();rili.set(year,month-1,1);//将日历翻到year年month月1日,注意0表示一月,//依次类推,11表示12月。//获取1日是星期几(get方法返回的值是1表示星期日,返回的值是7表示星期六):www.hackshp.cnint星期几=rili.get(Calendar.DAY_OF_WEEK)-1;intday=0;if(month==1||month==3||month==5||month==7||month==8||month==10||month==12){day=31;}if(month==4||month==6||month==9||month==11){day=30;}if(month==2){if(((year%4==0)&&(year%100!=0))||(year%400==0))46若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn{day=29;}else{day=28;}}Stringa[]=newString[42];for(inti=0;i<星期几;i++){a[i]="**";}for(inti=星期几,n=1;i<星期几+day;i++){a[i]=String.valueOf(n);n++;}for(inti=星期几+day,n=1;i<42;i++){a[i]="**";}//用表格显示数组:buffer.append("");buffer.append("");Stringweekday[]={"星期日","星期一","星期二","星期三","星期四","星期五","星期六"};for(intk=0;k<7;k++){buffer.append(""+weekday[k]+"");课后答案网}buffer.append("");for(intk=0;k<42;k=k+7){buffer.append("");for(intj=k;j"+a[j]+"");}buffer.append("");}buffer.append("<%@pageimport="red.star.CalendarBean"%>输入日历的年份:选择日历的月份:1月2月3月4月5月6月7月8月9月10月11月12月
月的日历:www.hackshp.cn48若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn第5章JSP中的文件操作例子1FileDirFileDir.java.javapackageuser.file;importjava.io.*;publicclassFileDir{StringnewWebDirName,oldWebDirName;StringBufferallFiles;publicFileDir(){allFiles=newStringBuffer();}publicvoidsetNewWebDirName(Strings){newWebDirName=s;if(newWebDirName!=null){Filedir=newFile("d:\apache-tomcat-5.5.20\webApps",newWebDirName);dir.mkdir();}}课后答案网publicStringgetNewWebDirName(){returnnewWebDirName;}publicvoidsetOldWebDirName(Strings){oldWebDirName=s;www.hackshp.cn}publicStringgetOldWebDirName(){returnoldWebDirName;}publicStringBuffergetAllFiles(){if(oldWebDirName!=null){Filedir=newFile("d:\apache-tomcat-5.5.20\webApps",oldWebDirName);Filea[]=dir.listFiles();for(intk=0;k子目录:"+a[k].getName());}for(intk=0;k文件:"+a[k].getName());}}returnallFiles;}}fileAndDirfileAndDir.jsp.jsp<%@pagecontentType="text/html;charset=GB2312"%><%@pageimport="user.file.FileDir"%>输入新的Web服务目录的名字课后答案网:
输入已有的Web服务目录的名字:新创建的Web服务目录:
已有的Web服务目录www.hackshp.cn下的子目录和文件:例子2ReadFileReadFile.java.javapackageuser.file;importjava.io.*;50若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnpublicclassReadFile{StringfileDir="c:/",fileName="";StringlistFile,readContent;publicvoidsetFileDir(Strings){fileDir=s;}publicStringgetFileDir(){returnfileDir;}publicvoidsetFileName(Strings){fileName=s;}publicStringgetFileName(){returnfileName;}publicStringgetListFile(){Filedir=newFile(fileDir);Filefile_name[]=dir.listFiles();StringBufferlist=newStringBuffer();for(inti=0;i"+temp+"";}catch(IOExceptione){readContent="";}returnreadContent;}}selectDir.jsp<%@pagecontentType="text/html;charset=GB2312"%>

请选择一个目录:D:/2000Web服务目录ch2Web课后答案网服务目录ch5www.hackshp.cnlistfilelistfile.jsp.jsp<%@pagecontentType="text/html;charset=GB2312"%><%@pageimport="user.file.ReadFile"%>

该目录有如下文件:
52若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn输入一个文件名字:文件:内容如下:

重新选择目录例子3WriterFile.javapackageuser.file;importjava.io.*;publicclassWriterFile{StringfilePath=null,fileName=null,fileContent=null;课后答案网booleansuccess;publicvoidsetFilePath(Strings){filePath=s;try{Filepath=newFile(filePath);path.mkdir();www.hackshp.cn}catch(Exceptione){}}publicStringgetFilePath(){returnfilePath;}publicvoidsetFileName(Strings){fileName=s;}publicStringgetFileName()53若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn{returnfileName;}publicvoidsetFileContent(Strings){fileContent=s;bytecontent[]=fileContent.getBytes();try{Filefile=newFile(filePath,fileName);FileOutputStreamin=newFileOutputStream(file);in.write(content,0,content.length);in.close();success=true;}catch(Exceptione){success=false;}}publicbooleanisSuccess(){returnsuccess;}}writefilewritefile.jsp.jsp<%@pagecontentType="text/html;Charset=GB2312"%>课后答案网<%@pageimport="user.file.WriterFile"%>www.hackshp.cn请选择一个目录:C:/hello88D:/ok88F:/myjspbookE:/javabook
输入保存文件的名字:
输入文件的内容:
54若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn
<%if(ok.isSuccess()==true){%>你写文件成功,文件所在目录:
文件名字:<%}%>例子4UpFile.javapackageuser.file;importjava.io.*;importjavax.servlet.http.*;publicclassUpFile{HttpServletRequestrequest;课后答案网HttpSessionsession;StringupFileMessage="";publicvoidsetRequest(HttpServletRequestrequest){this.request=request;}www.hackshp.cnpublicvoidsetSession(HttpSessionsession){this.session=session;}publicStringgetUpFileMessage(){StringfileName=null;try{StringtempFileName=(String)session.getId();//客户的session的idFilef1=newFile("D:/apache-tomcat-5.5.20/webapps/ch5",tempFileName);FileOutputStreamo=newFileOutputStream(f1);InputStreamin=request.getInputStream();byteb[]=newbyte[10000];55若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnintn;while((n=in.read(b))!=-1)//将客户上传的全部信息存入f1{o.write(b,0,n);}o.close();in.close();RandomAccessFilerandom=newRandomAccessFile(f1,"r");intsecond=1;//读出f1的第2行,析取出上传文件的名字:StringsecondLine=null;while(second<=2){secondLine=random.readLine();second++;}//获取第2行中目录符号""最后出现的位置intposition=secondLine.lastIndexOf("\");//客户上传的文件的名字是:fileName=secondLine.substring(position+1,secondLine.length()-1);bytecc[]=fileName.getBytes("ISO-8859-1");fileName=newString(cc);session.setAttribute("Name",fileName);//供show.jsp页面使用random.seek(0);//再定位到文件f1的开头。//获取第4行回车符号的位置:longforthEndPosition=0;课后答案网intforth=1;while((n=random.readByte())!=-1&&(forth<=4)){if(n=="n"){forthEndPosition=random.getFilePointer();forth++;www.hackshp.cn}}//根据客户上传文件的名字,将该文件存入磁盘:Filef2=newFile("D:/apache-tomcat-5.5.20/webapps/ch5",fileName);RandomAccessFilerandom2=newRandomAccessFile(f2,"rw");//确定出文件f1中包含客户上传的文件的内容的最后位置,即倒数第6行。random.seek(random.length());longendPosition=random.getFilePointer();longmark=endPosition;intj=1;while((mark>=0)&&(j<=6))56若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn{mark--;random.seek(mark);n=random.readByte();if(n=="n"){endPosition=random.getFilePointer();j++;}}//将random流指向文件f1的第4行结束的位置:random.seek(forthEndPosition);longstartPoint=random.getFilePointer();//从f1读出客户上传的文件存入f2(读取第4行结束位置至倒数第6行之间的内容)while(startPoint<%@pageimport="user.file.UpFile"%>

选择要上传的文件:

<%upFile.setRequest(request);upFile.setSession(session);%>

如果上传的是图像文件,可单击超链接查看图像:
查看图像show.jsp<%@pagecontentType="text/html;Charset=GB2312"%>课后答案网<%Stringpic=(String)session.getAttribute("Name");out.print(pic);out.print("");%>www.hackshp.cn例子5DownLoadFileDownLoadFile.java.javapackageuser.file;importjava.io.*;importjavax.servlet.http.*;publicclassDownLoadFile{HttpServletResponseresponse;58若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnStringfileName;publicvoidsetResponse(HttpServletResponseresponse){this.response=response;}publicStringgetFileName(){returnfileName;}publicvoidsetFileName(Strings){fileName=s;FilefileLoad=newFile("f:/2000",fileName);//客户使用下载文件的对话框:response.setHeader("Content-disposition","attachment;filename="+fileName);}}downfiledownfile.jsp.jsp<%@pagecontentType="text/html;charset=GB2312"%><%@pageimport="user.file.DownLoadFile"%><%@pageimport="java.io.*"%>

选择要下载的文件:课后答案网book.zipA.javaB.jspwww.hackshp.cn<%downFile.setResponse(response);%>59若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn例子6ReadByRow.javapackageuser.file;importjava.io.*;publicclassReadByRow{FileReaderinOne;BufferedReaderinTwo;StringfileName;StringBufferreadMessage;introws=0;publicReadByRow(){readMessage=newStringBuffer();}publicvoidsetFileName(Strings){fileName=s;readMessage=newStringBuffer();rows=0;Filef=newFile("D:/2000",fileName);try{inOne=newFileReader(f);inTwo=newBufferedReader(inOne);课后答案网}catch(IOExceptionexp){}}publicStringgetFileName(){returnfileName;www.hackshp.cn}publicvoidsetRows(intn){rows=n;}publicintgetRows(){returnrows;}publicStringBuffergetReadMessage(){inti=1;try{while(i<=rows)60若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn{Stringstr=inTwo.readLine();if(str==null){inOne.close();inTwo.close();readMessage.append("文件读取完毕");break;}else{readMessage.append("n"+str);}i++;}}catch(Exceptionexp){}returnreadMessage;}}selectfileselectfile.jsp.jsp<%@pagecontentType="text/html;charset=GB2312"%><%@pageimport="user.file.*"%>课后答案网选择一个文件:A.javawww.hackshp.cnExa.javaB.jsp
输入每次读取的行数:
61若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnreadByRowreadByRow.jsp.jsp<%@pagecontentType="text/html;charset=GB2312"%><%@pageimport="user.file.ReadByRow"%>正在读取的文件的名字:重新选择文件例子7Test.javapackageuser.file;课后答案网importjava.io.*;publicclassTest{StringfileName="",//存放考题文件名字的字符串correctAnswer="",//存放正确答案的字符串testContent="",www.hackshp.cn//存放试题的字符串selection="";//客户提交的答案的字符串intscore=0;//考试者的得分intgiveAnswerCount=0;//记录考试者提交答案的次数Stringname="",number="";//考试者姓名、学号publicvoidsetFileName(Stringname){fileName=name;selection="";score=0;giveAnswerCount=0;}62若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnpublicStringgetFileName(){returnfileName;}publicvoidsetGiveAnswerCount(intnumber){giveAnswerCount=number;}publicintgetGiveAnswerCount(){returngiveAnswerCount;}publicvoidsetName(Strings){name=s;}publicvoidsetNumber(Stringnum){number=num;}publicStringgetCorrectAnswer()//读取试题文件的第一行:标准答案{try{Filef=newFile("D:/2000",fileName);FileReaderin=newFileReader(f);BufferedReaderbuffer=newBufferedReader(in);correctAnswer=(buffer.readLine()).trim();//读取一行,去掉前后空格buffer.close();in.close();}课后答案网catch(Exceptione){}if(giveAnswerCount==1){returncorrectAnswer;}elsewww.hackshp.cnreturn"你只有一次提交答案的机会,不允许2次提交答案";}publicStringgetTestContent()//获取试题的内容{StringBuffertemp=newStringBuffer();try{if(fileName.length()>0){Filef=newFile("D:/2000",fileName);FileReaderin=newFileReader(f);BufferedReaderbuffer=newBufferedReader(in);Stringstr=buffer.readLine();//该行不显示给用户while((str=buffer.readLine())!=null)//读出全部题目{temp.append("n"+str);63若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn}buffer.close();in.close();}}catch(Exceptione){}returnnewString(temp);}publicvoidsetSelection(Strings){selection=s.trim();}publicStringgetSelection(){returnselection;}publicintgetScore(){score=0;if(giveAnswerCount==1){intlength1=selection.length();intlength2=correctAnswer.length();intmin=(int)(Math.min(length1,length2));inti=0;while(i<%@pageimport="user.file.Test"%>输入姓名:课后答案网输入学号:请选择试题:A.txtB.txtC.txtwww.hackshp.cn在文本框输入全部题目的答案,答案之间不允许有空格:
65若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn">
试题的正确答案:
您提交的答案:
您的分数课后答案网www.hackshp.cn66若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn第6章JSP中使用数据库例子1showByJdbcOdbc.jsp<%@pagecontentType="text/html;charset=GB2312"%><%@pageimport="java.sql.*"%><%Connectioncon;Statementsql;ResultSetrs;try{Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");}catch(ClassNotFoundExceptione){out.print(e);}try{con=DriverManager.getConnection("jdbc:odbc:mymoon","sa","sa");sql=con.createStatement();rs=sql.executeQuery("SELECT*FROMemployeeWHEREsalary>3000");课后答案网out.print("");out.print("");out.print(""+"雇员号");out.print(""+"姓名");out.print(""+"出生日期");www.hackshp.cnout.print(""+"薪水");out.print("");while(rs.next()){out.print("");out.print(""+rs.getString(1)+"");out.print(""+rs.getString(2)+"");out.print(""+rs.getDate("birthday")+"");out.print(""+rs.getFloat("salary")+"");out.print("");67若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn}out.print("");con.close();}catch(SQLExceptione){out.print(e);}%>例子2showBySQLDriver.jsp<%@pagecontentType="text/html;charset=GB2312"%><%@pageimport="java.sql.*"%><%Connectioncon;Statementsql;ResultSetrs;try{Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");}catch(Exceptione)课后答案网{out.print(e);}try{Stringuri="jdbc:sqlserver://127.0.0.1:1433;DatabaseName=factory";Stringuser="sa";Stringpassword="sa";www.hackshp.cncon=DriverManager.getConnection(uri,user,password);sql=con.createStatement();rs=sql.executeQuery("SELECT*FROMemployeeWHEREsalary>3000");out.print("");out.print("");out.print(""+"雇员号");out.print(""+"姓名");out.print(""+"出生日期");out.print(""+"薪水");out.print("");68若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnwhile(rs.next()){out.print("");out.print(""+rs.getString(1)+"");out.print(""+rs.getString(2)+"");out.print(""+rs.getDate("birthday")+"");out.print(""+rs.getFloat("salary")+"");out.print("");}out.print("");con.close();}catch(SQLExceptione){out.print(e);}%>例子3QueryBean.javapackagedatabase.operation;课后答案网importjava.sql.*;publicclassQueryBean{StringdatabaseName="";//数据库名StringtableName="";//表名Stringuser=""www.hackshp.cn;//用户Stringsecret="";//密码StringBufferqueryResult;//查询结果publicQueryBean(){queryResult=newStringBuffer();try{Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");}catch(Exceptione){}}publicvoidsetDatabaseName(Strings){databaseName=s.trim();queryResult=newStringBuffer();69若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn}publicStringgetDatabaseName(){returndatabaseName;}publicvoidsetTableName(Strings){tableName=s.trim();queryResult=newStringBuffer();}publicStringgetTableName(){returntableName;}publicvoidsetSecret(Strings){secret=s.trim();queryResult=newStringBuffer();}publicStringgetSecret(){returnsecret;}publicvoidsetUser(Strings){user=s.trim();queryResult=newStringBuffer();}publicStringgetUser()课后答案网{returnuser;}publicStringBuffergetQueryResult(){Connectioncon;Statementsql;www.hackshp.cnResultSetrs;try{queryResult.append("");Stringuri="jdbc:sqlserver://127.0.0.1:1433;DatabaseName="+databaseName;Stringid=user;Stringpassword=secret;con=DriverManager.getConnection(uri,id,password);DatabaseMetaDatametadata=con.getMetaData();ResultSetrs1=metadata.getColumns(null,null,tableName,null);int字段个数=0;queryResult.append("");while(rs1.next())70若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn{字段个数++;StringclumnName=rs1.getString(4);queryResult.append(""+clumnName+"");}queryResult.append("");sql=con.createStatement();rs=sql.executeQuery("SELECT*FROM"+tableName);while(rs.next()){queryResult.append("");for(intk=1;k<=字段个数;k++){queryResult.append(""+rs.getString(k)+"");}queryResult.append("");}queryResult.append("");con.close();}catch(SQLExceptione){queryResult.append("请输入正确的用户名和密码");}returnqueryResult;}}课后答案网inquireinquire.jsp.jsp<%@pagecontentType="text/html;charset=GB2312"%><%@pageimport="database.operation.QueryBean"%>www.hackshp.cn输入数据库名:输入表的名字:
输入用户名:输入密码:表查询到记录:71若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn
例子4RandomQueryBean.javapackagedatabase.operation;importjava.sql.*;importjava.util.*;publicclassRandomQueryBean{StringdatabaseName="";//数据库名称StringtableName="";//表的名字intcount;//记录总数intrandomNumber;//随机输出的记录数StringBufferrandomQueryResult;//查询结果Connectioncon;Statementsql;ResultSetrs;publicRandomQueryBean(){randomQueryResult=newStringBuffer();try{Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");}课后答案网catch(Exceptione){}}publicvoidsetDatabaseName(Strings){databaseName=s.trim();randomQueryResult=newStringBuffer();www.hackshp.cn}publicStringgetDatabaseName(){returndatabaseName;}publicvoidsetTableName(Strings){tableName=s.trim();randomQueryResult=newStringBuffer();}publicStringgetTableName(){returntableName;72若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn}publicvoidsetRandomNumber(intn){randomNumber=n;randomQueryResult=newStringBuffer();}publicintgetRandomNumber(){returnrandomNumber;}publicintgetCount(){try{Stringuri="jdbc:sqlserver://127.0.0.1:1433;DatabaseName="+databaseName;con=DriverManager.getConnection(uri,"sa","sa");sql=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);rs=sql.executeQuery("SELECT*FROM"+tableName);rs.last();count=rs.getRow();con.close();}catch(SQLExceptionexp){count=-1;}returncount;}课后答案网publicStringBuffergetRandomQueryResult(){randomQueryResult=newStringBuffer();try{randomQueryResult.append("");Stringuri="jdbc:sqlserver://127.0.0.1:1433;DatabaseName="+databaseName;con=DriverManager.getConnection(uri,"sa","sa");www.hackshp.cnDatabaseMetaDatametadata=con.getMetaData();ResultSetrs1=metadata.getColumns(null,null,tableName,null);int字段个数=0;randomQueryResult.append("");while(rs1.next()){字段个数++;StringclumnName=rs1.getString(4);randomQueryResult.append(""+clumnName+"");}randomQueryResult.append("");sql=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,73若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnResultSet.CONCUR_READ_ONLY);rs=sql.executeQuery("SELECT*FROM"+tableName);rs.last();count=rs.getRow();Vectorvector=newVector();for(inti=1;i<=count;i++){vector.add(newInteger(i));}int抽取数目=Math.min(randomNumber,count);while(抽取数目>0){inti=(int)(Math.random()*vector.size());intindex=(vector.elementAt(i)).intValue();//vector中随机抽取一个元素rs.absolute(index);//游标移到这一行randomQueryResult.append("");for(intk=1;k<=字段个数;k++){randomQueryResult.append(""+rs.getString(k)+"");}randomQueryResult.append("");抽取数目--;vector.removeElementAt(i);//将抽取过的元素从vector中删除}randomQueryResult.append("");con.close();课后答案网}catch(SQLExceptione){}randomNumber=0;returnrandomQueryResult;}www.hackshp.cn}random.jsp<%@pagecontentType="text/html;charset=GB2312"%><%@pageimport="database.operation.*"%>

随机查询数据库表中的记录:
74若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn输入数据库的名字:输入表的名字:
输入要随机查询的记录数:表中共有条记录.
随机输出条记录:
例子5ConditionQuery.javapackagedatabase.operation;importjava.sql.*;publicclassConditionQuery{Stringnumber;//雇员号floatsalaryMax,salaryMin;//薪水范围StringBufferqueryResultByNumber,queryResultBySalary;publicConditionQuery()课后答案网{queryResultByNumber=newStringBuffer();queryResultBySalary=newStringBuffer();try{Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");}catch(Exceptione){}www.hackshp.cn}publicvoidsetNumber(Strings){number=s.trim();queryResultByNumber=newStringBuffer();queryResultBySalary=newStringBuffer();}publicStringgetNumber(){returnnumber;}publicvoidsetSalaryMax(floatn)75若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn{salaryMax=n;queryResultByNumber=newStringBuffer();queryResultBySalary=newStringBuffer();}publicfloatgetSalaryMax(){returnsalaryMax;}publicvoidsetSalaryMin(floatn){salaryMin=n;queryResultByNumber=newStringBuffer();queryResultBySalary=newStringBuffer();}publicfloatgetSalaryMin(){returnsalaryMin;}publicStringBuffergetQueryResultByNumber(){Stringcondition="SELECT*FROMemployeeWherenumber=""+number+""";queryResultByNumber=f(condition);returnqueryResultByNumber;}publicStringBuffergetQueryResultBySalary(){Stringcondition="SELECT*FROMemployeeWheresalary<="+salaryMax+"AND"+"salary>="+salaryMin;课后答案网queryResultBySalary=f(condition);returnqueryResultBySalary;}privateStringBufferf(Stringcondition){StringBufferstr=newStringBuffer();www.hackshp.cnConnectioncon;Statementsql;ResultSetrs;try{Stringuri="jdbc:sqlserver://127.0.0.1:1433;DatabaseName=factory";con=DriverManager.getConnection(uri,"sa","sa");sql=con.createStatement();rs=sql.executeQuery(condition);str.append("");str.append(""+"number");str.append(""+"name");str.append(""+"birthday");76若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnstr.append(""+"salary");while(rs.next()){str.append("");str.append(""+rs.getString(1)+"");str.append(""+rs.getString(2)+"");str.append(""+rs.getDate(3)+"");str.append(""+rs.getFloat(4)+"");str.append("");}str.append("");con.close();}catch(SQLExceptione){System.out.println(e);}returnstr;}}condition.jsp课后答案网<%@pagecontentType="text/html;charset=GB2312"%><%@pageimport="database.operation.*"%>www.hackshp.cn雇员查询(根据雇员号查询)
输入雇员号:雇员查询(根据薪水查询)
薪水在之间77若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn根据雇员号查询到的记录:
薪水在之间的记录:
例子6OrderOrderQuery.javaQuery.javapackagedatabase.operation;importjava.sql.*;publicclassOrderQuery{StringorderType;//排序方式StringBufferorderResult;//排序结果publicOrderQuery(){orderResult=newStringBuffer();try{Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");}catch(Exceptione){}}课后答案网publicvoidsetOrderType(Strings){orderType=s.trim();try{bytebb[]=orderType.getBytes("ISO-8859-1");orderType=newString(bb,"gb2312");}catch(Exceptione){}www.hackshp.cn}publicStringgetOrderType(){returnorderType;}publicStringBuffergetOrderResult(){StringorderCondition="SELECT*FROMemployeeORDERBY"+orderType;Connectioncon;Statementsql;ResultSetrs;try{Stringuri="jdbc:sqlserver://127.0.0.1:1433;DatabaseName=factory";78若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cncon=DriverManager.getConnection(uri,"sa","sa");sql=con.createStatement();rs=sql.executeQuery(orderCondition);orderResult.append("");orderResult.append(""+"number");orderResult.append(""+"name");orderResult.append(""+"birthday");orderResult.append(""+"salary");while(rs.next()){orderResult.append("");orderResult.append(""+rs.getString(1)+"");orderResult.append(""+rs.getString(2)+"");orderResult.append(""+rs.getDate(3)+"");orderResult.append(""+rs.getFloat(4)+"");orderResult.append("");}orderResult.append("");con.close();}catch(SQLExceptione){System.out.println(e);}returnorderResult;课后答案网}}sortsort.jsp.jsp<%@pagecontentType="text/html;charset=GB2312"%>www.hackshp.cn<%@pageimport="database.operation.*"%>排序记录:按姓氏排序按薪水排序根据排序方式:,排序的记录79若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn
例子7KeyWordQuery.javapackagedatabase.operation;importjava.sql.*;publicclassKeyWordQuery{Stringziduan="",//字段keyWord="";//关键字StringBufferqueryResult;publicKeyWordQuery(){queryResult=newStringBuffer();try{Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");}catch(Exceptione){}}publicvoidsetKeyWord(Strings){keyWord=s.trim();try{bytebb[]=keyWord.getBytes("ISO-8859-1");keyWord=newString(bb,"gb2312");课后答案网}catch(Exceptione){}}publicStringgetKeyWord(){returnkeyWord;www.hackshp.cn}publicvoidsetZiduan(Strings){ziduan=s.trim();try{bytebb[]=ziduan.getBytes("ISO-8859-1");ziduan=newString(bb,"gb2312");}catch(Exceptione){}}publicStringgetZiduan(){returnziduan;80若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn}publicStringBuffergetQueryResult(){Stringcondition="SELECT*FROMemployeeWhere"+ziduan+"Like"%"+keyWord+"%"";StringBufferstr=f(condition);returnstr;}publicStringBufferf(Stringcondition){StringBufferstr=newStringBuffer();Connectioncon;Statementsql;ResultSetrs;try{Stringuri="jdbc:sqlserver://127.0.0.1:1433;DatabaseName=factory";con=DriverManager.getConnection(uri,"sa","sa");sql=con.createStatement();rs=sql.executeQuery(condition);str.append("");str.append(""+"雇员号");str.append(""+"姓名");str.append(""+"出生日期");str.append(""+"薪水");while(rs.next()){str.append("");str.append(""+rs.getString(1)+"");课后答案网str.append(""+rs.getString(2)+"");str.append(""+rs.getDate(3)+"");str.append(""+rs.getString(4)+"");str.append("");}www.hackshp.cnstr.append("");con.close();}catch(SQLExceptione){System.out.println(e);}returnstr;}}81若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnkeyWord.jsp<%@pagecontentType="text/html;charset=GB2312"%><%@pageimport="database.operation.*"%>选择:姓名雇员号含有:含有关键字的记录:
例子8课后答案网AddBean.javapackagedatabase.operation;importjava.sql.*;www.hackshp.cnpublicclassAddBean{Stringnumber="",//雇员号name="",//姓名birthday="";//出生日期floatsalary;//薪水StringaddMessage="";publicAddBean(){try{Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");}catch(Exceptione){}82若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn}publicvoidsetNumber(Strings){number=s.trim();}publicvoidsetName(Strings){name=s.trim();try{bytebb[]=name.getBytes("ISO-8859-1");name=newString(bb,"gb2312");}catch(Exceptione){}}publicvoidsetBirthday(Strings){birthday=s.trim();}publicvoidsetSalary(floatn){salary=n;}publicStringgetAddMessage(){StringinsertCondition="INSERTemployeeVALUES(""+number+"",""+name+"",""+birthday+"","+salary+")";Stringstr="";Connectioncon;Statementsql;课后答案网try{Stringuri="jdbc:sqlserver://127.0.0.1:1433;DatabaseName=factory";con=DriverManager.getConnection(uri,"sa","sa");sql=con.createStatement();if(number.length()>0){intm=sql.executeUpdate(insertCondition);www.hackshp.cnif(m!=0){str="对表中添加"+m+"条记录成功";}else{str="添加记录失败";}}else{str="必须要有雇员号";}con.close();83若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn}catch(SQLExceptione){str="输入的雇员不允许重复"+e;}returnstr;}}add.jsp<%@pagecontentType="text/html;charset=GB2312"%><%@pageimport="java.sql.*"%><%@pageimport="database.operation.*"%>雇员号是主键,不可重复,请输入新记录的相应字段的值:课后答案网输入雇员号:输姓名:
输入出生日期(****-**-**):输入薪水:

你添加记录操作的结果:

数据库当前的数据记录是:84若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn例子9ShowRecordByPage.javapackagedatabase.operation;importjava.sql.*;importcom.sun.rowset.*;publicclassShowRecordByPage{intpageSize=10;//每页显示的记录数intpageAllCount=0;//分页后的总页数intshowPage=1;//当前显示页StringBufferpresentPageResult;//显示当前页内容CachedRowSetImplrowSet;//用于存储ResultSet对象StringdatabaseName="";//数据库名称StringtableName="";//表的名字Stringuser="";//用户Stringpassword="";//密码String字段[]=newString[100];int字段个数=0;publicShowRecordByPage(){presentPageResult=newStringBuffer();try{Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();课后答案网}catch(Exceptione){}}publicvoidsetPageSize(intsize){pageSize=size;www.hackshp.cn字段个数=0;Stringuri="jdbc:sqlserver://127.0.0.1:1433;DatabaseName="+databaseName;try{Connectioncon=DriverManager.getConnection(uri,user,password);DatabaseMetaDatametadata=con.getMetaData();ResultSetrs1=metadata.getColumns(null,null,tableName,null);intk=0;while(rs1.next()){字段个数++;字段[k]=rs1.getString(4);//获取字段的名字k++;85若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn}Statementsql=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);ResultSetrs=sql.executeQuery("SELECT*FROM"+tableName);rowSet=newCachedRowSetImpl();//创建行集对象rowSet.populate(rs);con.close();//关闭连接rowSet.last();intm=rowSet.getRow();//总行数intn=pageSize;pageAllCount=((m%n)==0)?(m/n):(m/n+1);}catch(Exceptionexp){}}publicintgetPageSize(){returnpageSize;}publicintgetPageAllCount(){returnpageAllCount;}publicvoidsetShowPage(intn){showPage=n;}课后答案网publicintgetShowPage(){returnshowPage;}publicStringBuffergetPresentPageResult(){if(showPage>pageAllCount)www.hackshp.cnshowPage=1;if(showPage<=0)showPage=pageAllCount;presentPageResult=show(showPage);returnpresentPageResult;}publicStringBuffershow(intpage){StringBufferstr=newStringBuffer();str.append("");str.append("");for(inti=0;i<字段个数;i++)86若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn{str.append(""+字段[i]+"");}str.append("");try{rowSet.absolute((page-1)*pageSize+1);for(inti=1;i<=pageSize;i++){str.append("");for(intk=1;k<=字段个数;k++){str.append(""+rowSet.getString(k)+"");}str.append("");rowSet.next();}}catch(SQLExceptionexp){}str.append("");returnstr;}publicvoidsetDatabaseName(Strings){databaseName=s.trim();}publicStringgetDatabaseName(){returndatabaseName;}课后答案网publicvoidsetTableName(Strings){tableName=s.trim();}publicStringgetTableName(){returntableName;www.hackshp.cn}publicvoidsetPassword(Strings){password=s.trim();;}publicvoidsetUser(Strings){user=s.trim();}publicStringgetUser(){returnuser;}}87若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnshowByPage.jsp<%@pagecontentType="text/html;charset=GB2312"%><%@pageimport="java.sql.*"%><%@pageimport="database.operation.*"%>数据库表的记录将被分页显示。
共有页.
每页最多显示条记录。
当前显示第页,
单击“前一页”或“下一页”按纽查看记录

88若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn
课后答案网">www.hackshp.cn">输入页码:
例子10linkOracle.jsp<%@pagecontentType="text/html;charset=GB2312"%><%@pageimport="java.sql.*"%><%Connectioncon=null;Statementsql=null;ResultSetrs=null;try{Class.forName("oracle.jdbc.driver.OracleDriver");}catch(ClassNotFoundExceptione){}try{con=DriverManager.getConnection("jdbc:oracle:thin:@192.168.0.35:1521:Lea","scott","tiger");sql=con.createStatement();rs=sql.executeQuery("select*fromemp");out.print("");课后答案网out.print("");out.print(""+"EMPNO");out.print(""+"Ename");out.print("");while(rs.next())www.hackshp.cn{out.print("");intn=rs.getInt(1);out.print(""+n+"");Stringe=rs.getString(2);out.print(""+e+"");out.print("");}out.print("");con.close();}89若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cncatch(SQLExceptione1){out.print(""+e1);}%>例子11linkMySql.jsp<%@pagecontentType="text/html;charset=GB2312"%><%@pageimport="java.sql.*"%><%Connectioncon;Statementsql;ResultSetrs;try{Class.forName("com.mysql.jdbc.Driver");}catch(Exceptione){out.print(e);}try{Stringuri="jdbc:mysql://localhost/factory";课后答案网con=DriverManager.getConnection(uri,"root","123");sql=con.createStatement();rs=sql.executeQuery("SELECT*FROMemployee");out.print("");while(rs.next())www.hackshp.cn{out.print("");out.print(""+rs.getString(1)+"");out.print(""+rs.getString(2)+"");out.print(""+rs.getDate(3)+"");out.print(""+rs.getFloat(4)+"");out.print("");}out.print("");con.close();}90若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cncatch(SQLExceptione1){out.print(e1);}%>例子12MySqlBean.javapackagedatabase.operation;importjava.sql.*;publicclassMySqlBean{StringdatabaseName="";//数据库名StringtableName="";//表名Stringuser="";//用户Stringsecret="";//密码StringBufferqueryResult;//查询结果publicMySqlBean(){queryResult=newStringBuffer();try{Class.forName("com.mysql.jdbc.Driver");}catch(Exceptione){}课后答案网}publicvoidsetDatabaseName(Strings){databaseName=s.trim();queryResult=newStringBuffer();}www.hackshp.cnpublicStringgetDatabaseName(){returndatabaseName;}publicvoidsetTableName(Strings){tableName=s.trim();queryResult=newStringBuffer();}publicStringgetTableName(){returntableName;}91若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnpublicvoidsetSecret(Strings){secret=s.trim();queryResult=newStringBuffer();}publicStringgetSecret(){returnsecret;}publicvoidsetUser(Strings){user=s.trim();queryResult=newStringBuffer();}publicStringgetUser(){returnuser;}publicStringBuffergetQueryResult(){Connectioncon;Statementsql;ResultSetrs;try{queryResult.append("");Stringuri="jdbc:mysql://localhost/factory";Stringuser="root";Stringpassword="123";con=DriverManager.getConnection(uri,user,password);课后答案网DatabaseMetaDatametadata=con.getMetaData();ResultSetrs1=metadata.getColumns(null,null,tableName,null);int字段个数=0;queryResult.append("");while(rs1.next())www.hackshp.cn{字段个数++;StringclumnName=rs1.getString(4);queryResult.append(""+clumnName+"");}queryResult.append("");sql=con.createStatement();rs=sql.executeQuery("SELECT*FROM"+tableName);while(rs.next()){queryResult.append("");for(intk=1;k<=字段个数;k++){queryResult.append(""+rs.getString(k)+"");92若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn}queryResult.append("");}queryResult.append("");con.close();}catch(SQLExceptione){queryResult.append("请输入正确的用户名和密码");}returnqueryResult;}}mysql.jsp<%@pagecontentType="text/html;charset=GB2312"%><%@pageimport="database.operation.MySqlBean"%>输入数据库的名字课后答案网输入表的名字
输入用户名称(使用默认的root用户访问数据库):www.hackshp.cn
输入密码(如果没有为root设置密码,不必输入):表查询到记录:
93若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn例子13inquireExcelinquireExcel.jsp.jsp<%@pagecontentType="text/html;charset=GB2312"%><%@pageimport="java.sql.*"%><%Connectioncon;Statementsql;ResultSetrs;try{Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");}catch(ClassNotFoundExceptione){}try{con=DriverManager.getConnection("jdbc:odbc:star","","");sql=con.createStatement();sql.executeUpdate("UPDATEmessageSET品名="电缆线"WHERE货号="ED56G"");rs=sql.executeQuery("SELECT*FROMmessage");out.print("");out.print("");out.print(""+"货号");out.print(""+"品名");out.print(""+"单位");out.print(""+"单价");课后答案网out.print(""+"库存");out.print("");while(rs.next()){out.print("");out.print(""+rs.getString(1)+"");www.hackshp.cnout.print(""+rs.getString(2)+"");out.print(""+rs.getString(3)+"");out.print(""+rs.getString(4)+"");out.print(""+rs.getString(5)+"");out.print("");}out.print("");con.close();}catch(SQLExceptione1){}94若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn%>例子14ApplicationCon.javapackagedatabase.operation;importjava.sql.*;importjava.util.LinkedList;publicclassApplcationCon{LinkedListlist;//存放Connection对象的链表publicApplcationCon(){try{Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");}catch(Exceptione){}list=newLinkedList();for(intk=0;k<=10;k++)////创建10个连接{try{Stringuri="jdbc:sqlserver://127.0.0.1:1433;DatabaseName=factory";Stringid="sa";Stringpassword="sa";课后答案网Connectioncon=DriverManager.getConnection(uri,id,password);list.add(con);}catch(SQLExceptione){}}www.hackshp.cn}publicsynchronizedConnectiongetOneConnetion(){if(list.size()>0)returnlist.removeFirst();//链表删除第一个节点,并返回该节点中的连接对象elsereturnnull;}publicsynchronizedvoidputBackOneConnetion(Connectioncon){list.addFirst(con);}95若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn}UseConBeanUseConBean.java.javapackagedatabase.operation;importjava.sql.*;publicclassUseConBean{StringtableName="";//表名StringBufferqueryResult;//查询结果Connectioncon;publicUseConBean(){queryResult=newStringBuffer();}publicvoidsetTableName(Strings){tableName=s.trim();queryResult=newStringBuffer();}publicStringgetTableName(){returntableName;}publicvoidsetConnection(Connectioncon){this.con=con;}课后答案网publicStringBuffergetQueryResult(){Statementsql;ResultSetrs;try{queryResult.append("");DatabaseMetaDatametadata=con.getMetaData();www.hackshp.cnResultSetrs1=metadata.getColumns(null,null,tableName,null);int字段个数=0;queryResult.append("");while(rs1.next()){字段个数++;StringclumnName=rs1.getString(4);queryResult.append(""+clumnName+"");}queryResult.append("");sql=con.createStatement();96若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnrs=sql.executeQuery("SELECT*FROM"+tableName);while(rs.next()){queryResult.append("");for(intk=1;k<=字段个数;k++){queryResult.append(""+rs.getString(k)+"");}queryResult.append("");}queryResult.append("");}catch(SQLExceptione){queryResult.append("请输入正确的表名"+e);}returnqueryResult;}}chaxunchaxun.jsp.jsp<%@pagecontentType="text/html;charset=GB2312"%><%@pageimport="database.operation.*"%><%@pageimport="java.sql.*"%>课后答案网<%Connectionconnection=conSet.getOneConnetion();inquire.setConnection(connection);%>www.hackshp.cn你连接的数据库是factory输入表的名字:表查询到记录:
<%conSet.putBackOneConnetion(connection);%>97若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn例子15PreparedQueryBean.javapackagedatabase.operation;importjava.sql.*;publicclassPreparedQueryBean{StringdatabaseName="";//数据库名称StringtableName="";//表的名字Stringuser="";//用户Stringpassword="";//密码StringBufferqueryResult;//查询结果publicPreparedQueryBean(){queryResult=newStringBuffer();try{Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");}catch(Exceptione){queryResult=newStringBuffer();queryResult.append(""+e);}}publicvoidsetDatabaseName(Strings)课后答案网{queryResult=newStringBuffer();databaseName=s.trim();}publicStringgetDatabaseName(){returndatabaseName;www.hackshp.cn}publicvoidsetTableName(Strings){queryResult=newStringBuffer();tableName=s.trim();}publicStringgetTableName(){returntableName;}publicvoidsetPassword(Strings){password=s.trim();;98若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn}publicStringgetPassword(){returnpassword;}publicvoidsetUser(Strings){user=s.trim();;}publicStringgetUser(){returnuser;}publicStringBuffergetQueryResult(){Connectioncon;PreparedStatementsql;ResultSetrs;try{queryResult.append("");Stringuri="jdbc:sqlserver://127.0.0.1:1433;DatabaseName="+databaseName;con=DriverManager.getConnection(uri,user,password);DatabaseMetaDatametadata=con.getMetaData();ResultSetrs1=metadata.getColumns(null,null,tableName,null);int字段个数=0;queryResult.append("");while(rs1.next()){字段个数++;课后答案网StringclumnName=rs1.getString(4);queryResult.append(""+clumnName+"");}queryResult.append("");sql=con.prepareStatement("SELECT*FROM"+tableName);//预处理语句www.hackshp.cnrs=sql.executeQuery();while(rs.next()){queryResult.append("");for(intk=1;k<=字段个数;k++){queryResult.append(""+rs.getString(k)+"");}queryResult.append("");}queryResult.append("");con.close();}99若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cncatch(SQLExceptione){queryResult.append(e);}returnqueryResult;}}pre.jsp<%@pagecontentType="text/html;charset=GB2312"%><%@pageimport="database.operation.PreparedQueryBean"%>
使用预处理语句查询数据库:
输入数据库的名字:输入表的名字:
输入用户名:输入密码:
表查询到记录:
课后答案网例子16www.hackshp.cnAddRecordBean.javapackagedatabase.operation;importjava.sql.*;publicclassAddRecordBean{Stringnumber="",//雇员号name="",//姓名birthday;//出生日期floatsalary;//薪水100若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnbooleanok=false;publicAddRecordBean(){try{Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");}catch(ClassNotFoundExceptione){}}publicvoidsetNumber(Strings){number=s.trim();try{bytebb[]=number.getBytes("ISO-8859-1");number=newString(bb,"gb2312");}catch(Exceptione){}}publicvoidsetName(Strings){name=s.trim();try{bytebb[]=name.getBytes("ISO-8859-1");name=newString(bb,"gb2312");}catch(Exceptione){}}publicvoidsetSalary(floatn){salary=n;}课后答案网publicvoidsetBirthday(Stringb){birthday=b;}publicbooleangetOk(){returnok;www.hackshp.cn}publicStringgetAddMessage(){Stringstr="";Connectioncon;PreparedStatementsql;try{Stringuri="jdbc:sqlserver://127.0.0.1:1433;DatabaseName=factory";con=DriverManager.getConnection(uri,"sa","sa");StringinsertCondition="INSERTINTOemployeeVALUES(?,?,?,?)";sql=con.prepareStatement(insertCondition);if(number.length()>0){sql.setString(1,number);101若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnsql.setString(2,name);sql.setString(3,birthday);sql.setFloat(4,salary);intm=sql.executeUpdate();if(m!=0){str="对表中添加"+m+"条记录成功";ok=true;}else{str="添加记录失败";}}else{str="必须要有雇员号";}con.close();}catch(SQLExceptione){str="你还没有提供添加的数据或"+e;}returnstr;}}课后答案网addRecord.jsp<%@pagecontentType="text/html;charset=GB2312"%><%@pageimport="java.sql.*"%><%@pageimport="database.operation.ConditionQuery"%>www.hackshp.cn<%@pageimport="database.operation.AddRecordBean"%>雇员号是主键,不可重复,请输入新记录的相应字段的值:雇员号姓名出生日期(格式必须是****-**-**)102若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn薪水

你添加记录操作的结果:

添加的记录是:<%if(add.getOk()==true){%><%}%>课后答案网www.hackshp.cn103若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn第7章JavaServlet基础HelloBeijing.java:packagestar.moon;importjava.io.*;importjavax.servlet.*;importjavax.servlet.http.*;publicclassHelloBeijingextendsHttpServlet{publicvoidinit(ServletConfigconfig)throwsServletException{super.init(config);}publicvoidservice(HttpServletRequestreqest,HttpServletResponseresponse)throwsIOException{response.setContentType("text/html;charset=GB2312");//设置响应的MIME类型PrintWriterout=response.getWriter();//获得一个向客户发送数据的输出流out.println("");out.println("

北京奥运圆满成功!

");out.println("");}}web.xml课后答案网hellowww.hackshp.cnstar.moon.HelloBeijinghello/lookHello104若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn例子1giveRadius.jsp<%@pagecontentType="text/html;Charset=GB2312"%>
输入圆的半径:Computer.javapackagestar.moon;importjava.io.*;importjavax.servlet.*;importjavax.servlet.http.*;publicclassComputerextendsHttpServlet{publicvoidinit(ServletConfigconfig)throwsServletException{super.init(config);}课后答案网publicvoidservice(HttpServletRequestrequest,HttpServletResponseresponse)throwsIOException{response.setContentType("text/html;charset=GB2312");PrintWriterout=response.getWriter();out.println("");www.hackshp.cnStringstr=request.getParameter("radius");//获取客户提交的信息doubler=0;try{r=Double.parseDouble(str);if(r>=0){out.print("
半径是"+r+"的圆的面积:");out.print("
"+Math.PI*r*r);}else{out.print("
圆的半径不可以是负数:"+r);}105若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn}catch(NumberFormatExceptione){out.print("

请输入数字字符!

");}out.println("");}}例子2showLettershowLetter.jsp.jsp<%@pagecontentType="text/html;Charset=GB2312"%>单击超链接查看希腊字母表:
查看希腊字母表ShowLetter.javapackagestar.moon;课后答案网importjava.io.*;importjavax.servlet.*;importjavax.servlet.http.*;publicclassShowLetterextendsHttpServlet{publicvoidinit(ServletConfigconfig)throwsServletExceptionwww.hackshp.cn{super.init(config);}publicvoidservice(HttpServletRequestrequest,HttpServletResponseresponse)throwsIOException{response.setContentType("text/html;charset=GB2312");PrintWriterout=response.getWriter();out.println("");out.print("
小写希腊字母:");for(charc="α";c<="ω";c++){out.print(""+c);106若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn}out.print("
大写希腊字母:");for(charc="Α";c<="Ω";c++){out.print(""+c);}out.println("");}}例子3showPI.jsp<%@pagecontentType="text/html;charset=GB2312"%>参与计算PI的值ComputerPI.java课后答案网packagestar.moon;importjava.io.*;importjavax.servlet.*;importjavax.servlet.http.*;publicclassComputerPIextendsHttpServletwww.hackshp.cn{doublesum=0,i=1,j=1;intnumber=0;publicvoidinit(ServletConfigconfig)throwsServletException{super.init(config);}publicsynchronizedvoidservice(HttpServletRequestrequest,HttpServletResponseresponse)throwsIOException{response.setContentType("text/html;charset=GB2312");PrintWriterout=response.getWriter();out.println("");107若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnnumber++;sum=sum+i/j;j=j+2;i=-i;out.println("servlet:"+getServletName()+"已经被请求了"+number+"次");out.println("
现在PI的值是:");out.println(4*sum);out.println("");}}例子4method.jsp<%@pagecontentType="text/html;charset=GB2312"%>

输入一个数,提交给servlet(Post方式):课后答案网

输入一个数,提交给servlet(Get方式):

输入一个数,提交给servlet(Post方式):www.hackshp.cnGetSqare.javapackagestar.moon;108若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnimportjava.io.*;importjavax.servlet.*;importjavax.servlet.http.*;publicclassGetSquareextendsHttpServlet{publicvoidinit(ServletConfigconfig)throwsServletException{super.init(config);}publicvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{response.setContentType("text/html;charset=GB2312");PrintWriterout=response.getWriter();out.println("");Stringnumber=request.getParameter("number");//获取客户提交的信息doublen=0;try{n=Double.parseDouble(number);out.print("
"+number+"的平方是:");out.print("
"+n*n);}catch(NumberFormatExceptione){out.print("

请输入数字字符!

");}out.println("");}课后答案网publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{doPost(request,response);}www.hackshp.cn}GetSquareOrCubic.javapackagestar.moon;importjava.io.*;importjavax.servlet.*;importjavax.servlet.http.*;publicclassGetSquareOrCubicextendsHttpServlet109若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn{publicvoidinit(ServletConfigconfig)throwsServletException{super.init(config);}publicvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{response.setContentType("text/html;charset=GB2312");PrintWriterout=response.getWriter();out.println("");Stringnumber=request.getParameter("number");//获取客户提交的信息doublen=0;try{n=Double.parseDouble(number);out.print("
"+number+"的平方是:");out.print("
"+n*n);}catch(NumberFormatExceptione){out.print("

请输入数字字符!

");}out.println("");}publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{response.setContentType("text/html;charset=GB2312");PrintWriterout=response.getWriter();课后答案网out.println("");Stringnumber=request.getParameter("number");//获取客户提交的信息doublen=0;try{n=Double.parseDouble(number);out.print("
"+number+"的立方是:");www.hackshp.cnout.print("
"+n*n*n);}catch(NumberFormatExceptione){out.print("

请输入数字字符!

");}out.println("");}}110若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn例子5input.jsp<%@pagecontentType="text/html;charset=GB2312"%>输入姓名:
输入年龄:
Verify.javapackagestar.moon;importjava.io.*;importjavax.servlet.*;importjavax.servlet.http.*;publicclassVerifyextendsHttpServlet{publicvoidinit(ServletConfigconfig)throwsServletException{super.init(config);}课后答案网publicvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{Stringname=request.getParameter("name");//获取客户提交的信息Stringage=request.getParameter("age");//获取客户提交的信息if(name.length()==0||name==null)www.hackshp.cn{response.sendRedirect("input.jsp");//重定向}elseif(age.length()==0||name==null){response.sendRedirect("input.jsp");//重定向}elseif(age.length()>0){try{intnumberAge=Integer.parseInt(age);if(numberAge<=0||numberAge>=150){response.sendRedirect("input.jsp");}111若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnelse{RequestDispatcherdispatcher=request.getRequestDispatcher("forYouShowMessage");dispatcher.forward(request,response);//转发}}catch(NumberFormatExceptione){response.sendRedirect("input.jsp");}}}publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{doPost(request,response);}}ShowMessage.javapackagestar.moon;importjava.io.*;importjavax.servlet.*;importjavax.servlet.http.*;课后答案网publicclassShowMessageextendsHttpServlet{publicvoidinit(ServletConfigconfig)throwsServletException{super.init(config);}publicvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)www.hackshp.cnthrowsServletException,IOException{response.setContentType("text/html;charset=GB2312");PrintWriterout=response.getWriter();Stringname=request.getParameter("name");//获取客户提交的信息Stringage=request.getParameter("age");//获取客户提交的信息try{bytebb[]=name.getBytes("ISO-8859-1");name=newString(bb,"gb2312");}catch(Exceptionexp){}out.print("您的姓名是:");112若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnout.print(name);out.print("
您的年龄是:");out.print(age);}publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{doPost(request,response);}}例子6Boy.javapackagestar.moon;importjava.io.*;importjavax.servlet.*;importjavax.servlet.http.*;publicclassBoyextendsHttpServlet{publicvoidinit(ServletConfigconfig)throwsServletException{super.init(config);}课后答案网publicvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{response.setContentType("text/html;charset=GB2312");PrintWriterout=response.getWriter();out.print("");www.hackshp.cnHttpSessionsession=request.getSession(true);//获取客户的会话对象session.setAttribute("number",newInteger(668));out.println("您请求的servlet对象是:"+getServletName()+",您的会话的id:");out.println("
"+session.getId());out.println("
单击超链接请求另一个servlet:");out.println("请求另一个servlet
");out.print("");}publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException113若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn{doPost(request,response);}}Look.javapackagestar.moon;importjava.io.*;importjavax.servlet.*;importjavax.servlet.http.*;publicclassLookextendsHttpServlet{publicvoidinit(ServletConfigconfig)throwsServletException{super.init(config);}publicvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{response.setContentType("text/html;charset=GB2312");PrintWriterout=response.getWriter();out.print("");HttpSessionsession=request.getSession(true);//获取客户的会话对象Integernumber=(Integer)session.getAttribute("number");//获取会话中存储的数据intn=number.intValue();课后答案网intm=n*n*n;out.println("您请求的servlet对象是:"+getServletName()+",您的会话的id:");out.println("
"+session.getId());out.println("
您的会话中存储的整数:"+n);out.println("
"+n+"的立方:"+m);www.hackshp.cnout.print("");}publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{doPost(request,response);}}114若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn例子7getLettergetLetter.jsp.jsp<%@pagecontentType="text/html;charset=GB2312"%><%session.setAttribute("message","请您猜字母");chara[]=newchar[26];intm=0;for(charc="a";c<="z";c++){a[m]=c;m++;}intrandomIndex=(int)(Math.random()*a.length);charch=a[randomIndex];//获取一个英文字母session.setAttribute("savedLetter",newCharacter(ch));%>访问或刷新该页面可以随机得到一个英文字母.
单击超链接去猜出这个字母:去猜字母inputLetterinputLetter.jsp.jsp课后答案网<%@pagecontentType="text/html;charset=GB2312"%><%Stringmessage=(String)session.getAttribute("message");//获取会话中的信息www.hackshp.cn%>输入您的猜测(a~z之间的字母):提示信息:<%=message%>单击按钮重新开始:115若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnHandleGuess.javapackagestar.moon;importjava.io.*;importjavax.servlet.*;importjavax.servlet.http.*;publicclassHandleGuessextendsHttpServlet{publicvoidinit(ServletConfigconfig)throwsServletException{super.init(config);}publicvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{HttpSessionsession=request.getSession(true);//获取客户的会话对象Stringstr=request.getParameter("clientGuessLetter");CharacterguessLetter=str.trim().charAt(0);//获取客户猜测所提交的字母CharactersavedLetter=(Character)session.getAttribute("savedLetter");charrealLetter=savedLetter.charValue();if(Character.isUpperCase(guessLetter))课后答案网{guessLetter=Character.toLowerCase(guessLetter);}if(guessLetterrealLetter){session.setAttribute("message","您猜大了");response.sendRedirect("inputLetter.jsp");}if(guessLetter==realLetter){session.setAttribute("message","您猜对了");response.sendRedirect("inputLetter.jsp");}}116若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnpublicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{doPost(request,response);}}课后答案网www.hackshp.cn117若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn第8章基于Servlet的MVC模式web.xmlcomputerSumsun.yourservlet.HandleSumcomputerSum/lookSumSeries.javapackagemoon.yourbean;publicclassSeries{doublefirstItem;//数列首项doublevar;//公差或公比课后答案网intnumber;//求和项数doublesum;//求和结果Stringname="";//数列类别publicvoidsetFirstItem(doublea){firstItem=a;www.hackshp.cn}publicdoublegetFirstItem(){returnfirstItem;}publicvoidsetVar(doubleb){var=b;}publicdoublegetVar(){returnvar;}118若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnpublicvoidsetNumber(intn){number=n;}publicdoublegetNumber(){returnnumber;}publicvoidsetSum(doubles){sum=s;}publicdoublegetSum(){returnsum;}publicvoidsetName(Stringna){name=na;}publicStringgetName(){returnname;}}inputMess.jsp<%@pagecontentType="text/html;Charset=GB2312"%>课后答案网等差数列求和:
输入首项:输入公差:求和项数:www.hackshp.cn等比数列求和:
输入首项:输入公比:求和项数:119若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnshowResult.jsp<%@pagecontentType="text/html;charset=GB2312"%><%@pageimport="moon.yourbean.*"%>数列的首项所求项数求和结果HandleSum.javapackagesun.yourservlet;课后答案网importmoon.yourbean.*;importjava.io.*;importjavax.servlet.*;importjavax.servlet.http.*;publicclassHandleSumextendsHttpServlet{publicvoidinit(ServletConfigconfig)throwsServletExceptionwww.hackshp.cn{super.init(config);}publicvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{Seriesshulie=newSeries();//创建Javabean对象request.setAttribute("lie",shulie);//将shulie存储到HttpServletRequest对象中doublea=Double.parseDouble(request.getParameter("firstItem"));doubled=Double.parseDouble(request.getParameter("var"));intn=Integer.parseInt(request.getParameter("number"));shulie.setFirstItem(a);//将数据存储在shulie中120若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnshulie.setVar(d);shulie.setNumber(n);//计算和:doublesum=0,item=a;inti=1;shulie.setName("等差数列的公差");while(i<=n)//计算等差数列的和{sum=sum+item;i++;item=item+d;}shulie.setSum(sum);RequestDispatcherdispatcher=request.getRequestDispatcher("showResult.jsp");dispatcher.forward(request,response);//请求showResult.jsp显示shulie中的数据}publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{Seriesshulie=newSeries();request.setAttribute("lie",shulie);doublea=Double.parseDouble(request.getParameter("firstItem"));doubled=Double.parseDouble(request.getParameter("var"));intn=Integer.parseInt(request.getParameter("number"));shulie.setFirstItem(a);课后答案网shulie.setVar(d);shulie.setNumber(n);//计算和:doublesum=0,item=a;inti=1;www.hackshp.cnshulie.setName("等比数列的公比");while(i<=n)//计算等比数列的和{sum=sum+item;i++;item=item*d;}shulie.setSum(sum);RequestDispatcherdispatcher=request.getRequestDispatcher("showResult.jsp");dispatcher.forward(request,response);}}121若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn计算一元二次方程的根Equation.javapackagemoon.yourbean;publicclassEquation{doublea,b,c;StringrootOne,rootTwo;booleansquareEquation;publicvoidsetA(doublea){this.a=a;}publicdoublegetA(){returna;}publicvoidsetB(doubleb){this.b=b;}publicdoublegetB(){returnb;}publicvoidsetC(doublec){this.c=c;课后答案网}publicdoublegetC(){returnc;}publicvoidsetRootOne(Stringroot)www.hackshp.cn{rootOne=root;}publicStringgetRootOne(){returnrootOne;}publicvoidsetRootTwo(Stringroot){rootTwo=root;}publicStringgetRootTwo(){returnrootTwo;122若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn}publicvoidsetIsSquareEquation(booleanb){squareEquation=b;}publicbooleangetIsSquareEquation(){returnsquareEquation;}}input.jsp<%@pagecontentType="text/html;Charset=GB2312"%>
输入一元二次方程的系数:
二次项系数a:一次项系数b:常数项c:课后答案网show.jsp<%@pagecontentType="text/html;charset=GB2312"%>www.hackshp.cn<%@pageimport="moon.yourbean.*"%>一元二次方程的系数是:
二次项系数:一次项系数:常数项:
是一元二次方程吗?
方程的两个根是:,123若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnHandleData.javapackagesun.yourservlet;importmoon.yourbean.*;importjava.io.*;importjavax.servlet.*;importjavax.servlet.http.*;publicclassHandleDataextendsHttpServlet{publicvoidinit(ServletConfigconfig)throwsServletException{super.init(config);}publicvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{Equationequ=newEquation();//创建Javabean对象request.setAttribute("equation",equ);//将equ存储到HttpServletRequest对象中doublea=Double.parseDouble(request.getParameter("a"));doubleb=Double.parseDouble(request.getParameter("b"));doublec=Double.parseDouble(request.getParameter("c"));equ.setA(a);//将数据存储在equ中equ.setB(b);equ.setC(c);if(a!=0)equ.setIsSquareEquation(true);课后答案网elseequ.setIsSquareEquation(true);doubledisk=b*b-4*a*c;if(disk<0){equ.setRootOne("无实根");www.hackshp.cnequ.setRootTwo("无实根");}else{doubleroot1=(-b+Math.sqrt(disk))/(2*a),root2=(-b-Math.sqrt(disk))/(2*a);equ.setRootOne(""+root1);equ.setRootTwo(""+root2);}RequestDispatcherdispatcher=request.getRequestDispatcher("show.jsp");dispatcher.forward(request,response);//请求show.jsp显示equ中的数据124若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn}publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{doPost(request,response);}}简单的计算器ComputerBean.javapackageflower.grass;publicclassComputerBean{doublenumberOne,numberTwo,result;Stringoperator="+";publicvoidsetNumberOne(doublen){numberOne=n;}publicdoublegetNumberOne(){returnnumberOne;}publicvoidsetNumberTwo(doublen){numberTwo=n;课后答案网}publicdoublegetNumberTwo(){returnnumberTwo;}publicvoidsetOperator(Strings)www.hackshp.cn{operator=s.trim();;}publicStringgetOperator(){returnoperator;}publicvoidsetResult(doubler){result=r;}publicdoublegetResult(){returnresult;125若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn}}inputNumber.jsp<%@pagecontentType="text/html;Charset=GB2312"%>课后答案网
输入两个数:
选择运算符号:+(加)-(减)*(乘)/(除)
www.hackshp.cnshowResult.jsp<%@pagecontentType="text/html;charset=GB2312"%><%@pageimport="moon.yourbean.*"%>运算结果:=126若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn
输入两个数:"size=10>
选择运算符号:+(加)-(减)*(乘)/(除)
HandleComputer.java课后答案网packagesun.yourservlet;importmoon.yourbean.*;importjava.io.*;importjavax.servlet.*;www.hackshp.cnimportjavax.servlet.http.*;publicclassHandleComputerextendsHttpServlet{publicvoidinit(ServletConfigconfig)throwsServletException{super.init(config);}publicvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{ComputerBeandataBean=null;HttpSessionsession=request.getSession(true);try{dataBean=(ComputerBean)session.getAttribute("ok");127若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnif(dataBean==null){dataBean=newComputerBean();//创建Javabean对象session.setAttribute("ok",dataBean);//将dataBean存储到session对象中}}catch(Exceptionexp){dataBean=newComputerBean();//创建Javabean对象session.setAttribute("ok",dataBean);//将dataBean存储到session对象中}doublenumberOne=Double.parseDouble(request.getParameter("numberOne"));doublenumberTwo=Double.parseDouble(request.getParameter("numberTwo"));Stringoperator=request.getParameter("operator");doubleresult=0;if(operator.equals("+")){result=numberOne+numberTwo;}elseif(operator.equals("-")){result=numberOne-numberTwo;}elseif(operator.equals("*")){result=numberOne*numberTwo;}elseif(operator.equals("/"))课后答案网{result=numberOne/numberTwo;}dataBean.setNumberOne(numberOne);//将数据存储在dataBean中dataBean.setNumberTwo(numberTwo);dataBean.setOperator(operator);www.hackshp.cndataBean.setResult(result);RequestDispatcherdispatcher=request.getRequestDispatcher("showResult.jsp");dispatcher.forward(request,response);//请求showResult.jsp显示dataBean中的数据}publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{doPost(request,response);}}128若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn读取文件FileMessage.javapackagemoon.yourbean;publicclassFileMessage{StringfilePath,fileName,fileContent;longfileLength;publicvoidsetFilePath(Stringstr){filePath=str;}publicStringgetFilePath(){returnfilePath;}publicvoidsetFileName(Stringstr){fileName=str;}publicStringgetFileName(){returnfileName;}publicvoidsetFileContent(Stringstr){fileContent=str;}课后答案网publicStringgetFileContent(){returnfileContent;}publicvoidsetFileLength(longlen){fileLength=len;www.hackshp.cn}publiclonggetFileLength(){returnfileLength;}}choiceFile.jsp<%@pagecontentType="text/html;Charset=GB2312"%>129若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn输入文件的路径(如:d:/1000):
输入文件的名字(如:Hello.java):
showFile.jsp<%@pagecontentType="text/html;charset=GB2312"%><%@pageimport="moon.yourbean.*"%><%@pagecontentType="text/html;charset=GB2312"%><%@pageimport="moon.yourbean.FileMessage"%>文件的位置是,文件的名字:,文件的长度:字节.
您读取的文件的内容:
课后答案网HandleFile.javapackagesun.yourservlet;importmoon.yourbean.*;www.hackshp.cnimportjava.io.*;importjavax.servlet.*;importjavax.servlet.http.*;publicclassHandleFileextendsHttpServlet{publicvoidinit(ServletConfigconfig)throwsServletException{super.init(config);}publicvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{FileMessagefile=newFileMessage();//创建Javabean对象130若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnrequest.setAttribute("file",file);StringfilePath=request.getParameter("filePath");StringfileName=request.getParameter("fileName");file.setFilePath(filePath);//将数据存储在file中file.setFileName(fileName);try{Filef=newFile(filePath,fileName);longlength=f.length();file.setFileLength(length);FileReaderin=newFileReader(f);BufferedReaderinTwo=newBufferedReader(in);StringBufferstringbuffer=newStringBuffer();Strings=null;while((s=inTwo.readLine())!=null){stringbuffer.append("n"+s);}Stringcontent=newString(stringbuffer);file.setFileContent(content);}catch(IOExceptionexp){}RequestDispatcherdispatcher=request.getRequestDispatcher("showFile.jsp");dispatcher.forward(request,response);//请求showFile.jsp显示file中的数据}publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)课后答案网throwsServletException,IOException{doPost(request,response);}}查询数据库www.hackshp.cnShowRecordByPageShowRecordByPage.java.javapackagemoon.yourbean;importcom.sun.rowset.*;publicclassShowRecordByPage{CachedRowSetImplrowSet=null;//存储表中全部记录的行集对象intpageSize=10;//每页显示的记录数intpageAllCount=0;//分页后的总页数131若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnintshowPage=1;//当前显示页StringBufferpresentPageResult;//显示当前页内容StringdatabaseName="";//数据库名称StringtableName="";//表的名字StringBufferformTitle=null;//表头publicvoidsetRowSet(CachedRowSetImplset){rowSet=set;}publicCachedRowSetImplgetRowSet(){returnrowSet;}publicvoidsetPageSize(intsize){pageSize=size;}publicintgetPageSize(){returnpageSize;}publicintgetPageAllCount(){returnpageAllCount;}publicvoidsetPageAllCount(intn){pageAllCount=n;}课后答案网publicvoidsetShowPage(intn){showPage=n;}publicintgetShowPage(){returnshowPage;www.hackshp.cn}publicvoidsetPresentPageResult(StringBufferp){presentPageResult=p;}publicStringBuffergetPresentPageResult(){returnpresentPageResult;}publicvoidsetDatabaseName(Strings){databaseName=s.trim();}publicStringgetDatabaseName()132若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn{returndatabaseName;}publicvoidsetTableName(Strings){tableName=s.trim();}publicStringgetTableName(){returntableName;}publicvoidsetFormTitle(StringBuffers){formTitle=s;}publicStringBuffergetFormTitle(){returnformTitle;}}choiceDatabase.jsp<%@pagecontentType="text/html;Charset=GB2312"%>输入SQlServer2000所管理的数据库的名字(例如:pubs、factory):
课后答案网
输入相应数据库中表的名字(例如:jobs、employee):

输入每页显示的记录数:www.hackshp.cnshowRecord.jsp<%@pagecontentType="text/html;charset=GB2312"%><%@pageimport="moon.yourbean.*"%>133若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn您查询的数据库:,查询的表:
记录分页,每页最多显示条记录,目前显示第页。课后答案网HandleDatabase.javawww.hackshp.cnpackagesun.yourservlet;importmoon.yourbean.*;importcom.sun.rowset.*;importjava.sql.*;importjava.io.*;importjavax.servlet.*;importjavax.servlet.http.*;publicclassHandleDatabaseextendsHttpServlet{int字段个数;CachedRowSetImplrowSet=null;134若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnpublicvoidinit(ServletConfigconfig)throwsServletException{super.init(config);try{Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");}catch(Exceptione){}}publicvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{Connectioncon;StringBufferpresentPageResult=newStringBuffer();ShowRecordByPagedatabaseBean=null;HttpSessionsession=request.getSession(true);try{databaseBean=(ShowRecordByPage)session.getAttribute("database");if(databaseBean==null){databaseBean=newShowRecordByPage();//创建Javabean对象session.setAttribute("database",databaseBean);}}catch(Exceptionexp){databaseBean=newShowRecordByPage();session.setAttribute("database",databaseBean);}StringdatabaseName=request.getParameter("databaseName");课后答案网StringtableName=request.getParameter("tableName");Stringps=request.getParameter("pageSize");if(ps!=null){try{intmm=Integer.parseInt(ps);databaseBean.setPageSize(mm);www.hackshp.cn}catch(NumberFormatExceptionexp){databaseBean.setPageSize(1);}}intshowPage=databaseBean.getShowPage();intpageSize=databaseBean.getPageSize();booleanboo=databaseName!=null&&tableName!=null&&databaseName.length()>0&&tableName.length()>0;if(boo){databaseBean.setDatabaseName(databaseName);//数据存储在databaseBean中135若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cndatabaseBean.setTableName(tableName);//数据存储在databaseBean中Stringuri="jdbc:sqlserver://127.0.0.1:1433;DatabaseName="+databaseName;try{字段个数=0;con=DriverManager.getConnection(uri,"sa","sa");DatabaseMetaDatametadata=con.getMetaData();ResultSetrs1=metadata.getColumns(null,null,tableName,null);intk=0;String字段[]=newString[100];while(rs1.next()){字段个数++;字段[k]=rs1.getString(4);//获取字段的名字k++;}StringBufferstr=newStringBuffer();str.append("");for(inti=0;i<字段个数;i++){str.append("");}str.append("");databaseBean.setFormTitle(str);//数据存储在databaseBean中Statementsql=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);ResultSetrs=sql.executeQuery("SELECT*FROM"+tableName);课后答案网rowSet=newCachedRowSetImpl();//创建行集对象rowSet.populate(rs);con.close();//关闭连接databaseBean.setRowSet(rowSet);//数据存储在databaseBean中rowSet.last();www.hackshp.cnintm=rowSet.getRow();//总行数intn=pageSize;intpageAllCount=((m%n)==0)?(m/n):(m/n+1);databaseBean.setPageAllCount(pageAllCount);//数据存储在databaseBean中}catch(SQLExceptionexp){}}StringwhichPage=request.getParameter("whichPage");if(whichPage==null||whichPage.length()==0){showPage=1;databaseBean.setShowPage(showPage);136若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnCachedRowSetImplrowSet=databaseBean.getRowSet();if(rowSet!=null){presentPageResult=show(showPage,pageSize,rowSet);databaseBean.setPresentPageResult(presentPageResult);}}elseif(whichPage.equals("nextPage")){showPage++;if(showPage>databaseBean.getPageAllCount())showPage=1;databaseBean.setShowPage(showPage);CachedRowSetImplrowSet=databaseBean.getRowSet();if(rowSet!=null){presentPageResult=show(showPage,pageSize,rowSet);databaseBean.setPresentPageResult(presentPageResult);}}elseif(whichPage.equals("previousPage")){showPage--;if(showPage<=0)showPage=databaseBean.getPageAllCount();databaseBean.setShowPage(showPage);CachedRowSetImplrowSet=databaseBean.getRowSet();课后答案网if(rowSet!=null){presentPageResult=show(showPage,pageSize,rowSet);databaseBean.setPresentPageResult(presentPageResult);}}www.hackshp.cndatabaseBean.setPresentPageResult(presentPageResult);RequestDispatcherdispatcher=request.getRequestDispatcher("showRecord.jsp");dispatcher.forward(request,response);//请求showRecord.jsp显示数据}publicStringBuffershow(intpage,intpageSize,CachedRowSetImplrowSet){StringBufferstr=newStringBuffer();try{rowSet.absolute((page-1)*pageSize+1);for(inti=1;i<=pageSize;i++){str.append("");for(intk=1;k<=字段个数;k++){str.append("");137若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn}str.append("");rowSet.next();}}catch(SQLExceptionexp){}returnstr;}publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{doPost(request,response);}}课后答案网www.hackshp.cn138若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn第9章JSP中使用XML例子1Score.xml<成绩><学号number="a1001"><姓名>赵一<高等数学课程性质="必修">89<大学物理课程性质="必修">88<摄影艺术课程性质="选修">良好<学号number="a1002"><姓名>钱二<高等数学课程性质="必修">77<大学物理课程性质="必修">66<摄影艺术课程性质="选修">良好课后答案网<学号number="a1003"><姓名>孙三<高等数学课程性质="必修">75<大学物理课程性质="必修">69<摄影艺术课程性质www.hackshp.cn="选修">良好<学号number="a1004"><姓名>李四<高等数学课程性质="必修">76<大学物理课程性质="必修">87<摄影艺术课程性质="选修">良好139若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cninput.jsp<%@pagecontentType="text/html;Charset=GB2312"%>输入学号,查询成绩:Number.javapackagesun.yourservlet;importjava.io.*;importorg.w3c.dom.*;importjavax.xml.parsers.*;importjavax.servlet.*;importjavax.servlet.http.*;publicclassNumberextendsHttpServlet{publicvoidinit(ServletConfigconfig)throwsServletException{super.init(config);}课后答案网publicvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{booleanboo=false;response.setContentType("text/html;charset=GB2312");PrintWriterout=response.getWriter();www.hackshp.cnout.println("");StringsearchedNumber=request.getParameter("studentNmber");try{DocumentBuilderFactoryfactory=DocumentBuilderFactory.newInstance();DocumentBuilderbuilder=factory.newDocumentBuilder();Documentdocument=builder.parse(newFile("D:\1000\Score.xml"));Elementroot=document.getDocumentElement();//获取根节点//返回根节点的Element子节点,这些子节点对应着XML文件中的“学号"标记:NodeListelemnetNodes=root.getElementsByTagName("学号");intsize=elemnetNodes.getLength();for(intk=0;k"+nodeName);StringcourseType=((Element)child).getAttribute("课程性质");StringcontentStr=((Element)child).getTextContent();if(nodeName.startsWith("姓名"))out.println(":"+contentStr);elseout.println("("+courseType+"):"+contentStr);}}}}}课后答案网if(boo==false)out.println("不存在您要查询的学号!");}catch(Exceptionee){}www.hackshp.cnout.println("");}publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{doPost(request,response);}}141若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn例子2trainListtrainList...xmlxml<北京西站><始发列车><车次><名字>T83次<运行区间>北京西-南京<开车时间>20:17<终到时间>09:10<车次><名字>T199次<运行区间>北京西-上海<开车时间>23:25<终到时间>10:10<终到列车>课后答案网<车次><名字>T84次<运行区间>南京-北京西<开车时间>21:17<终到时间>10:10www.hackshp.cn<车次><名字>T200次<运行区间>上海-北京西<开车时间>22:25<终到时间>09:10<广东站>142若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn<始发列车><车次><名字>T186次<运行区间>广东-武汉<开车时间>22:17<终到时间>09:24<车次><名字>T78次<运行区间>广东-长沙<开车时间>18:25<终到时间>11:10<终到列车><车次><名字>T193次<运行区间>南京-广东<开车时间>21:17<终到时间>10:10<车次><名字>T200次课后答案网<运行区间>上海-广东<开车时间>21:15<终到时间>12:10www.hackshp.cntraintrain.jsp.jsp<%@pagecontentType="text/html;charset=GB2312"%><%@pageimport="moon.yourbean.*"%>143若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn选择站名:北京西站广东站选择始发或终到:始发列车终到列车
,:SAXBeanSAXBean...javajavapackagemoon.yourbean;importjavax.xml.parsers.*;importorg.xml.sax.helpers.*;课后答案网importorg.xml.sax.*;publicclassSAXBean{StringstationName="北京西站";//站名StringstartOrArrive="";//始发或终到StringBuffertrainMessages=newStringBuffer();//信息SAXParserFactoryfactory=null;www.hackshp.cnSAXParsersaxParser=null;//解析器MyHandlerhandler;//事件处理器publicvoidsetStationName(Strings){stationName=s.trim();try{byteb[]=stationName.getBytes("ISO-8859-1");stationName=newString(b);}catch(Exceptionee){}}publicStringgetStationName()144若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn{returnstationName;}publicvoidsetStartOrArrive(Strings){startOrArrive=s.trim();try{byteb[]=startOrArrive.getBytes("ISO-8859-1");startOrArrive=newString(b);}catch(Exceptionee){}}publicStringgetStartOrArrive(){returnstartOrArrive;}publicStringBuffergetTrainMessages(){try{factory=SAXParserFactory.newInstance();saxParser=factory.newSAXParser();handler=newMyHandler(trainMessages,stationName,startOrArrive);saxParser.parse("D:/1000/trainList.xml",handler);}catch(Exceptione){System.out.println(e);}returntrainMessages;}}classMyHandlerextendsDefaultHandler课后答案网{StringBuffertrainMessages;StringstationName,startOrArrive;boolean站名标记=false,始发或终到标记=false;MyHandler(StringBuffermess,StringsName,StringstartOrArr){trainMessages=mess;www.hackshp.cnstationName=sName;startOrArrive=startOrArr;}publicvoidstartDocument(){trainMessages.append("");trainMessages.append("
");trainMessages.append("");trainMessages.append("");trainMessages.append("");trainMessages.append("");trainMessages.append("");145若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn}publicvoidendDocument(){trainMessages.append("
"+字段[i]+"
"+rowSet.getString(k)+"
车次名字运行区间始发时间终到时间
");}publicvoidstartElement(Stringuri,StringlocalName,StringqName,Attributesatts){qName=qName.trim();if(qName.equals(stationName)){站名标记=true;trainMessages.append(""+qName);}if(qName.equals(startOrArrive)){始发或终到标记=true;}if(qName.endsWith("车次")){trainMessages.append("");}}publicvoidendElement(Stringuri,StringlocalName,StringqName){if(qName.startsWith(stationName)){站名标记=false;课后答案网}if(qName.startsWith(startOrArrive)){始发或终到标记=false;}if(qName.endsWith("车次"))www.hackshp.cn{trainMessages.append("");}}publicvoidcharacters(char[]ch,intstart,intlength){Stringtext=newString(ch,start,length);text=text.trim();if(站名标记==true&&始发或终到标记==true&&text.length()>0){Stringstr=text.trim();trainMessages.append(""+str+"");}146若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn}}例子3type.jsp<%@pagecontentType="text/html;charset=GB2312"%>
显示几个数学公式和化合物分子式:显示formula.xml几个数学公式:平方和公式:(A+B)2=A2+2AB+B2课后答案网立方和公式:(A+B)3=A3+3A2B+3B2A2+A3www.hackshp.cn几个化合物分子式:水的分子式:H2O二氧化硫的分子式:SO2147若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn碳酸的分子式:H2CO3show.cssmath{display:block;background-color:yellow;color:green;left=100;}chemistry{display:block;background-color:cyan;color:green;left=100;}formula{display:list-item;list-style-type:lower-roman;课后答案网margin-left:60;font-size:14pt;color:black;}molecularwww.hackshp.cn{display:list-item;list-style-type:decimal;margin-left:60;font-size:14pt;color:black;}sup{display:line;font-size:10pt;font-weight:bold;148若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnfont-style:italic;color:blue;vertical-align:super;}low{display:line;font-size:8pt;font-weight:bold;color:blue;vertical-align:bottom;}课后答案网www.hackshp.cn149若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn第10章基于会员制的网络广告系统head.txt<%@pagecontentType="text/html;charset=GB2312"%>

网络广告系统

会员注册会员登录上传广告照片浏览会员的广告修改注册信息修改密码退出登录返回主页index.jsp<%@pagecontentType="text/html;charset=GB2312"%>课后答案网<%@includefile="head.txt"%>

欢迎您来这里做广告

www.hackshp.cnweb.xmlregistermyservlet.control.HandleRegisterregister150若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn/helpRegisterloginmyservlet.control.HandleLoginlogin/helpLoginuploadmyservlet.control.HandleUploadupload/helpUploadlookRecordmyservlet.control.HandleDatabase课后答案网lookRecord/helpShowMembermodifyPasswordwww.hackshp.cnmyservlet.control.HandlePasswordmodifyPassword/helpModifyPasswordgetOldMessmyservlet.control.GetOldMess151若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cngetOldMess/helpGetOldMessmodifyOldMessmyservlet.control.HandleModifyMessmodifyOldMess/helpModifyMessexitmyservlet.control.HandleExitexit/helpExitLoginRegister.javapackagemybean.data;课后答案网publicclassRegister{Stringlogname="",password="",advertiseTitle="",email="",phone="",message="";StringbackNews;publicvoidsetLogname(Stringname)www.hackshp.cn{logname=name;}publicStringgetLogname(){returnlogname;}publicvoidsetAdvertiseTitle(Strings){advertiseTitle=s;}publicStringgetAdvertiseTitle(){returnadvertiseTitle;}152若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnpublicvoidsetPassword(Stringpw){password=pw;}publicStringgetPassword(){returnpassword;}publicvoidsetEmail(Stringem){email=em;}publicStringgetEmail(){returnemail;}publicvoidsetPhone(Stringph){phone=ph;}publicStringgetPhone(){returnphone;}publicStringgetMessage(){returnmessage;}publicvoidsetMessage(Stringm){message=m;课后答案网}publicStringgetBackNews(){returnbackNews;}publicvoidsetBackNews(Strings)www.hackshp.cn{backNews=s;}}register.jsp<%@pagecontentType="text/html;charset=GB2312"%><%@includefile="head.txt"%>
153若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn输入您的信息,会员名字必须由字母和数字组成,带*号项必须填写。
会员名称:*
设置密码:*
广告标题:*
电子邮件:
联系电话:
输入您的广告词:
showRegisterMess.jsp<%@pagecontentType="text/html;charset=GB2312"%><%@pageimport="mybean.data.*"%><%@includefile="head.txt"%>课后答案网

www.hackshp.cn154若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn
注册的会员名称:
注册的广告标题:
注册的电子邮件:
注册的联系电话:
您的广告词:
HandleRegister.javapackagemyservlet.control;importmybean.data.*;importjava.sql.*;importjava.io.*;importjavax.servlet.*;importjavax.servlet.http.*;publicclassHandleRegisterextendsHttpServlet{publicvoidinit(ServletConfigconfig)throwsServletException{super.init(config);try{Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");}catch(Exceptione){}}课后答案网publicStringhandleString(Strings){try{bytebb[]=s.getBytes("iso-8859-1");s=newString(bb);}catch(Exceptionee){}www.hackshp.cnreturns;}publicvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{Connectioncon;PreparedStatementsql;Registerreg=newRegister();request.setAttribute("register",reg);Stringlogname=request.getParameter("logname").trim(),password=request.getParameter("password").trim(),155若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnadvertiseTitle=request.getParameter("advertiseTitle").trim(),email=request.getParameter("email").trim(),phone=request.getParameter("phone").trim(),message=request.getParameter("message");Stringuri="jdbc:sqlserver://127.0.0.1:1433;DatabaseName=Friend";if(logname==null)logname="";if(password==null)password="";booleanisLD=true;for(inti=0;i="a")||(c<="Z"&&c>="A")||(c<="9"&&c>="0")))isLD=false;}booleanboo=logname.length()>0&&password.length()>0&&isLD;StringbackNews="";try{con=DriverManager.getConnection(uri,"sa","sa");StringinsertCondition="INSERTINTOmemberVALUES(?,?,?,?,?,?,?)";sql=con.prepareStatement(insertCondition);if(boo){sql.setString(1,handleString(logname));sql.setString(2,handleString(password));课后答案网sql.setString(3,handleString(advertiseTitle));sql.setString(4,phone);sql.setString(5,email);sql.setString(6,handleString(message));sql.setString(7,"public.jpg");www.hackshp.cnintm=sql.executeUpdate();if(m!=0){backNews="注册成功";reg.setBackNews(backNews);reg.setLogname(logname);reg.setPassword(handleString(password));reg.setAdvertiseTitle(handleString(advertiseTitle));reg.setEmail(handleString(email));reg.setPhone(phone);reg.setMessage(handleString(message));}156若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn}else{backNews="信息填写不完整或名字中有非法字符";reg.setBackNews(backNews);}con.close();}catch(SQLExceptionexp){backNews="该会员名已被使用,请您更换名字"+exp;reg.setBackNews(backNews);}RequestDispatcherdispatcher=request.getRequestDispatcher("showRegisterMess.jsp");//转发dispatcher.forward(request,response);}publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{doPost(request,response);}}Login.javapackagemybean.data;课后答案网publicclassLogin{Stringlogname,password,backNews="";booleansuccess=false;www.hackshp.cnpublicvoidsetLogname(Stringname){logname=name;}publicStringgetLogname(){returnlogname;}publicvoidsetPassword(Stringpw){password=pw;}publicStringgetPassword(){returnpassword;157若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn}publicStringgetBackNews(){returnbackNews;}publicvoidsetBackNews(Strings){backNews=s;}publicvoidsetSuccess(booleanb){success=b;}publicbooleangetSuccess(){returnsuccess;}}login.jsp<%@pagecontentType="text/html;charset=GB2312"%><%@includefile="head.txt"%>


请您登录课后答案网登录名称:输入密码:
www.hackshp.cnshowLoginMess.jsp<%@pagecontentType="text/html;charset=GB2312"%><%@pageimport="mybean.data.Login"%><%@includefile="head.txt"%>

158若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn<%if(login.getSuccess()==true){%>
登录会员名称:<%}else{%>
登录会员名称:
登录会员密码:<%}%>
HandleLogin.javapackagemyservlet.control;importmybean.data.*;importjava.sql.*;importjava.io.*;importjavax.servlet.*;importjavax.servlet.http.*;publicclassHandleLoginextendsHttpServlet{publicvoidinit(ServletConfigconfig)throwsServletException{super.init(config);课后答案网try{Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");}catch(Exceptione){}}publicStringhandleString(Strings)www.hackshp.cn{try{bytebb[]=s.getBytes("iso-8859-1");s=newString(bb);}catch(Exceptionee){}returns;}publicvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{Connectioncon;PreparedStatementsql;159若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnLoginloginBean=null;StringbackNews="";HttpSessionsession=request.getSession(true);try{loginBean=(Login)session.getAttribute("login");if(loginBean==null){loginBean=newLogin();session.setAttribute("login",loginBean);}}catch(Exceptionee){loginBean=newLogin();session.setAttribute("login",loginBean);}Stringlogname=request.getParameter("logname").trim(),password=request.getParameter("password").trim();booleanok=loginBean.getSuccess();logname=handleString(logname);password=handleString(password);if(ok==true&&logname.equals(loginBean.getLogname())){backNews=logname+"已经登录了";loginBean.setBackNews(backNews);}else课后答案网{Stringuri="jdbc:sqlserver://127.0.0.1:1433;DatabaseName=Friend";booleanboo=(logname.length()>0)&&(password.length()>0);try{con=DriverManager.getConnection(uri,"sa","sa");Stringcondition="select*frommemberwherelogname=?andpassword=?";sql=con.prepareStatement(condition);www.hackshp.cnif(boo){sql.setString(1,logname);sql.setString(2,password);ResultSetrs=sql.executeQuery();booleanm=rs.next();if(m==true){backNews="登录成功";loginBean.setBackNews(backNews);loginBean.setSuccess(true);loginBean.setLogname(logname);}160若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnelse{backNews="您输入的用户名不存在,或密码不般配";loginBean.setBackNews(backNews);loginBean.setSuccess(false);loginBean.setLogname(logname);loginBean.setPassword(password);}}else{backNews="您输入的用户名不存在,或密码不般配";loginBean.setBackNews(backNews);loginBean.setSuccess(false);loginBean.setLogname(logname);loginBean.setPassword(password);}con.close();}catch(SQLExceptionexp){backNews=""+exp;loginBean.setBackNews(backNews);loginBean.setSuccess(false);}}课后答案网RequestDispatcherdispatcher=request.getRequestDispatcher("showLoginMess.jsp");dispatcher.forward(request,response);}publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOExceptionwww.hackshp.cn{doPost(request,response);}}UploadFile.javapackagemybean.data;publicclassUploadFile{StringfileName,savedFileName,backNews="";publicvoidsetFileName(Stringname){fileName=name;161若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn}publicStringgetFileName(){returnfileName;}publicvoidsetSavedFileName(Stringname){savedFileName=name;}publicStringgetSavedFileName(){returnsavedFileName;}publicStringgetBackNews(){returnbackNews;}publicvoidsetBackNews(Strings){backNews=s;}}upload.jsp<%@pagecontentType="text/html;charset=GB2312"%><%@includefile="head.txt"%>

文件将被上传到D:apache-tomcat-5.5.20webappsch10image中。课后答案网
选择要上传的图像照片文件(名字不可以含有非ASCII码字符,比如汉字等):
www.hackshp.cnshowUploadMess.jsp<%@pagecontentType="text/html;charset=GB2312"%><%@pageimport="mybean.data.*"%><%@includefile="head.txt"%>

162若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn
上传的文件名字:保存后的文件名字:
width=150height=120>图像效果
HandleUpload.javapackagemyservlet.control;importmybean.data.*;importjava.sql.*;importjava.io.*;importjavax.servlet.*;importjavax.servlet.http.*;publicclassHandleUploadextendsHttpServlet{publicvoidinit(ServletConfigconfig)throwsServletException{super.init(config);try{Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");}catch(Exceptione){}}publicvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)课后答案网throwsServletException,IOException{HttpSessionsession=request.getSession(true);Loginlogin=(Login)session.getAttribute("login");//获取用户登录时的Javabeanbooleanok=true;if(login==null)www.hackshp.cn{ok=false;response.sendRedirect("login.jsp");//重定向到登录页面}if(ok==true){Stringlogname=login.getLogname();uploadFileMethod(request,response,logname);//接受上传文件}}publicvoiduploadFileMethod(HttpServletRequestrequest,HttpServletResponseresponse,Stringlogname)throwsServletException,IOException{UploadFileupFile=newUploadFile();163若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnStringbackNews="";try{HttpSessionsession=request.getSession(true);request.setAttribute("upFile",upFile);StringtempFileName=(String)session.getId();Filef1=newFile(tempFileName);FileOutputStreamo=newFileOutputStream(f1);InputStreamin=request.getInputStream();byteb[]=newbyte[10000];intn;while((n=in.read(b))!=-1){o.write(b,0,n);}o.close();in.close();RandomAccessFilerandom=newRandomAccessFile(f1,"r");intsecond=1;//读出f1的第2行,析取出上传文件的名字:StringsecondLine=null;while(second<=2){secondLine=random.readLine();second++;}//获取第2行中目录符号""最后出现的位置:intposition=secondLine.lastIndexOf("\");课后答案网//截取文件名:StringfileName=secondLine.substring(position+1,secondLine.length()-1);bytecc[]=fileName.getBytes("ISO-8859-1");fileName=newString(cc);fileName=fileName.replaceAll("","");www.hackshp.cn//文件是否由字母或数字组成判断名字StringcheckedStr=fileName.substring(0,fileName.indexOf("."));booleanisLetterOrDigit=true;for(inti=0;i="a")||(c<="Z"&&c>="A")||(c<="9"&&c>="0"))){isLetterOrDigit=false;break;}}if(isLetterOrDigit==false)164若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn{response.sendRedirect("upload.jsp");//重定向到upload.jsp页面}//保存文件名是上传文件名加会员名为前缀:StringsavedFileName=logname.concat(fileName);random.seek(0);longforthEndPosition=0;//获取第4行回车符号的位置intforth=1;while((n=random.readByte())!=-1&&(forth<=4)){if(n=="n"){forthEndPosition=random.getFilePointer();forth++;}}//根据客户上传文件的名字,将该文件存入磁盘:Filedir=newFile("D:/apache-tomcat-5.5.20/webapps/ch10/image");dir.mkdir();//首先删除用户曾上传过的图像文件:Filefile[]=dir.listFiles();for(intk=0;k=0)&&(j<=6)){mark--;random.seek(mark);n=random.readByte();if(n=="n"){endPosition=random.getFilePointer();j++;}}random.seek(forthEndPosition);165若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnlongstartPoint=random.getFilePointer();while(startPoint<%@includefile="head.txt"%>
课后答案网
分页显示全体会员www.hackshp.cn
输入要查找的会员名:showAllMember.jsp<%@pagecontentType="text/html;charset=GB2312"%><%@pageimport="mybean.data.ShowByPage"%><%@includefile="head.txt"%>169若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn

显示会员信息.
每页最多显示条信息
当前显示第页,共有页。
当前显示的内容是:

会员名广告标题电话email广告词广告照片

单击“前一页”或“下一页”按纽查看信息课后答案网www.hackshp.cn
">">输入页码:
showLookedMember.jsp<%@pagecontentType="text/html;charset=GB2312"%>170若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn<%@pageimport="mybean.data.MemberInform"%>
<%@includefile="head.txt"%>会员名广告标题电话email广告词广告照片width=50height=50>
HandleDatabase.javapackagemyservlet.control;课后答案网importmybean.data.*;importcom.sun.rowset.*;importjava.sql.*;importjava.io.*;importjavax.servlet.*;www.hackshp.cnimportjavax.servlet.http.*;publicclassHandleDatabaseextendsHttpServlet{CachedRowSetImplrowSet=null;publicvoidinit(ServletConfigconfig)throwsServletException{super.init(config);try{Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");}catch(Exceptione){}}publicvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException171若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn{HttpSessionsession=request.getSession(true);Loginlogin=(Login)session.getAttribute("login");//获取用户登录时的Javabeanbooleanok=true;if(login==null){ok=false;response.sendRedirect("login.jsp");//重定向到登录页面}if(ok==true){continueDoPost(request,response);}}publicvoidcontinueDoPost(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{HttpSessionsession=request.getSession(true);Connectioncon=null;StringBufferpresentPageResult=newStringBuffer();ShowByPageshowBean=null;try{showBean=(ShowByPage)session.getAttribute("show");if(showBean==null){showBean=newShowByPage();//创建Javabean对象session.setAttribute("show",showBean);}}课后答案网catch(Exceptionexp){showBean=newShowByPage();session.setAttribute("show",showBean);}showBean.setPageSize(3);www.hackshp.cn//每页显示3条记录intshowPage=Integer.parseInt(request.getParameter("showPage"));if(showPage>showBean.getPageAllCount())showPage=1;if(showPage<=0)showPage=showBean.getPageAllCount();showBean.setShowPage(showPage);intpageSize=showBean.getPageSize();Stringuri="jdbc:sqlserver://127.0.0.1:1433;DatabaseName=Friend";try{con=DriverManager.getConnection(uri,"sa","sa");Statementsql=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);172若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnResultSetrs=sql.executeQuery("SELECT*FROMmember");rowSet=newCachedRowSetImpl();//创建行集对象rowSet.populate(rs);con.close();//关闭连接showBean.setRowSet(rowSet);//数据存储在showBean中rowSet.last();intm=rowSet.getRow();//总行数intn=pageSize;intpageAllCount=((m%n)==0)?(m/n):(m/n+1);showBean.setPageAllCount(pageAllCount);//数据存储在showBean中presentPageResult=show(showPage,pageSize,rowSet);showBean.setPresentPageResult(presentPageResult);}catch(SQLExceptionexp){}RequestDispatcherdispatcher=request.getRequestDispatcher("showAllMember.jsp");//转发dispatcher.forward(request,response);}publicStringBuffershow(intpage,intpageSize,CachedRowSetImplrowSet){StringBufferstr=newStringBuffer();try{rowSet.absolute((page-1)*pageSize+1);for(inti=1;i<=pageSize;i++){str.append("");课后答案网str.append(""+rowSet.getString(1)+"");str.append(""+rowSet.getString(3)+"");str.append(""+rowSet.getString(4)+"");str.append(""+rowSet.getString(5)+"");str.append(""+rowSet.getString(6)+"");www.hackshp.cnStrings="";str.append(""+s+"");str.append("");rowSet.next();}}catch(SQLExceptionexp){}returnstr;}publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException173若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn{HttpSessionsession=request.getSession(true);Loginlogin=(Login)session.getAttribute("login");//获取用户登录时的Javabeanbooleanok=true;if(login==null){ok=false;response.sendRedirect("login.jsp");//重定向到登录页面}if(ok==true){continueDoGet(request,response);}}publicvoidcontinueDoGet(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{MemberInforminform=newMemberInform();request.setAttribute("inform",inform);Stringlogname=request.getParameter("logname");Connectioncon=null;Stringuri="jdbc:sqlserver://127.0.0.1:1433;DatabaseName=Friend";try{con=DriverManager.getConnection(uri,"sa","sa");Statementsql=con.createStatement();ResultSetrs=sql.executeQuery("SELECT*FROMmemberwherelogname=""+logname+""");if(rs.next())课后答案网{inform.setLogname(rs.getString(1));inform.setAdvertiseTitle(rs.getString(3));inform.setPhone(rs.getString(4));inform.setEmail(rs.getString(5));inform.setMessage(rs.getString(6));www.hackshp.cninform.setPic(rs.getString(7));inform.setBackNews("查询到的会员信息:");}con.close();RequestDispatcherdispatcher=request.getRequestDispatcher("showLookedMember.jsp");//转发dispatcher.forward(request,response);}catch(SQLExceptionexp){inform.setBackNews(""+exp);System.out.println("ok1"+exp);}174若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn}}Password.javapackagemybean.data;publicclassPassword{StringoldPassword,newPassword,backNews="";publicvoidsetNewPassword(Stringpw){newPassword=pw;}publicStringgetnewPassword(){returnnewPassword;}publicvoidsetOldPassword(Stringpw){oldPassword=pw;}publicStringgetOldPassword(){returnoldPassword;}publicStringgetBackNews(){returnbackNews;}publicvoidsetBackNews(Strings)课后答案网{backNews=s;}}modifyPassword.jsp<%@pagecontentType="text/html;charset=GB2312"%>www.hackshp.cn<%@includefile="head.txt"%>

输入您的密码:
当前密码:
新密码:

175若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnshowNewPasswor.jsp<%@pagecontentType="text/html;charset=GB2312"%><%@pageimport="mybean.data.Password"%><%@includefile="head.txt"%>

您的新密码:
您的旧密码:
HandlePassword.javapackagemyservlet.control;importmybean.data.*;importjava.sql.*;importjava.io.*;importjavax.servlet.*;importjavax.servlet.http.*;publicclassHandlePasswordextendsHttpServlet{publicvoidinit(ServletConfigconfig)throwsServletException课后答案网{super.init(config);try{Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");}catch(Exceptione){}}publicvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)www.hackshp.cnthrowsServletException,IOException{HttpSessionsession=request.getSession(true);Loginlogin=(Login)session.getAttribute("login");//获取用户登录时的Javabeanbooleanok=true;if(login==null){ok=false;response.sendRedirect("login.jsp");//重定向到登录页面}if(ok==true){continueWork(request,response);176若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn}}publicvoidcontinueWork(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{HttpSessionsession=request.getSession(true);Loginlogin=(Login)session.getAttribute("login");Connectioncon=null;Stringlogname=login.getLogname();PasswordpasswordBean=newPassword();request.setAttribute("password",passwordBean);StringoldPassword=request.getParameter("oldPassword");StringnewPassword=request.getParameter("newPassword");Stringuri="jdbc:sqlserver://127.0.0.1:1433;DatabaseName=Friend";try{con=DriverManager.getConnection(uri,"sa","sa");Statementsql=con.createStatement();ResultSetrs=sql.executeQuery("SELECT*FROMmemberwherelogname=""+logname+""Andpassword=""+oldPassword+""");if(rs.next()){StringupdateString="UPDATEmemberSETpassword=""+newPassword+""wherelogname=""+logname+""";intm=sql.executeUpdate(updateString);if(m==1)课后答案网{passwordBean.setBackNews("密码更新成功");passwordBean.setOldPassword(oldPassword);passwordBean.setNewPassword(newPassword);}elsewww.hackshp.cn{passwordBean.setBackNews("密码更新失败");}}else{passwordBean.setBackNews("密码更新失败");}}catch(SQLExceptionexp){passwordBean.setBackNews("密码更新失败"+exp);}RequestDispatcherdispatcher=177若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnrequest.getRequestDispatcher("showNewPassword.jsp");//转发dispatcher.forward(request,response);}publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{doPost(request,response);}}ModifyMessage.javapackagemybean.data;publicclassModifyMessage{Stringlogname="",newAdvertiseTitle="",newEmail="",newPhone="",newMessage="",backNews;publicvoidsetLogname(Stringname){logname=name;}publicStringgetLogname(){returnlogname;}publicvoidsetNewAdvertiseTitle(Strings){newAdvertiseTitle=s;}课后答案网publicStringgetNewAdvertiseTitle(){returnnewAdvertiseTitle;}publicvoidsetNewEmail(Stringem){newEmail=em;www.hackshp.cn}publicStringgetNewEmail(){returnnewEmail;}publicvoidsetNewPhone(Stringph){newPhone=ph;}publicStringgetNewPhone(){returnnewPhone;}publicStringgetNewMessage()178若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn{returnnewMessage;}publicvoidsetNewMessage(Stringm){newMessage=m;}publicStringgetBackNews(){returnbackNews;}publicvoidsetBackNews(Strings){backNews=s;}}choiceModifyMess.jsp<%@pagecontentType="text/html;charset=GB2312"%>
<%@includefile="head.txt"%>课后答案网
inputModifyMess.jsp<%@pagecontentType="text/html;charset=GB2312"%>www.hackshp.cn<%@includefile="head.txt"%><%@pageimport="mybean.data.Register"%>

以下是您()曾注册的信息,您可以修改这些信息。179若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn

广告标题:>
联系电话:>
电子邮件:>
广告词:
showModifyMess.jsp<%@pagecontentType="text/html;charset=GB2312"%>课后答案网<%@pageimport="mybean.data.ModifyMessage"%><%@includefile="head.txt"%>
www.hackshp.cn
您修改信息如下:
新广告标题:
新电话:
新email:
新广告词:
GetOldMess.javapackagemyservlet.control;180若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnimportmybean.data.*;importjava.sql.*;importjava.io.*;importjavax.servlet.*;importjavax.servlet.http.*;publicclassGetOldMessextendsHttpServlet{publicvoidinit(ServletConfigconfig)throwsServletException{super.init(config);try{Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");}catch(Exceptione){}}publicvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{HttpSessionsession=request.getSession(true);Loginlogin=(Login)session.getAttribute("login");//获取用户登录时的Javabeanbooleanok=true;if(login==null){ok=false;response.sendRedirect("login.jsp");//重定向到登录页面}if(ok==true){continueWork(request,response);课后答案网}}publicvoidcontinueWork(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{HttpSessionsession=request.getSession(true);www.hackshp.cnLoginlogin=(Login)session.getAttribute("login");Connectioncon=null;Stringlogname=login.getLogname();Registerregister=newRegister();request.setAttribute("register",register);Stringuri="jdbc:sqlserver://127.0.0.1:1433;DatabaseName=Friend";try{con=DriverManager.getConnection(uri,"sa","sa");Statementsql=con.createStatement();ResultSetrs=sql.executeQuery("SELECT*FROMmemberwherelogname=""+logname+""");if(rs.next())181若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn{register.setLogname(rs.getString(1));register.setAdvertiseTitle(rs.getString(3));register.setPhone(rs.getString(4));register.setEmail(rs.getString(5));register.setMessage(rs.getString(6));register.setBackNews("您原来的注册信息:");}}catch(SQLExceptionexp){register.setBackNews(""+exp);}RequestDispatcherdispatcher=request.getRequestDispatcher("inputModifyMess.jsp");//转发dispatcher.forward(request,response);}publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{doPost(request,response);}}HandleModifyMess.javapackagemyservlet.control;课后答案网importmybean.data.*;importjava.sql.*;importjava.io.*;importjavax.servlet.*;importjavax.servlet.http.*;www.hackshp.cnpublicclassHandleModifyMessextendsHttpServlet{publicvoidinit(ServletConfigconfig)throwsServletException{super.init(config);try{Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");}catch(Exceptione){}}publicStringhandleString(Strings){try{bytebb[]=s.getBytes("iso-8859-1");s=newString(bb);}182若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cncatch(Exceptionee){}returns;}publicvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{HttpSessionsession=request.getSession(true);Loginlogin=(Login)session.getAttribute("login");//获取用户登录时的Javabeanbooleanok=true;if(login==null){ok=false;response.sendRedirect("login.jsp");//重定向到登录页面}if(ok==true){continueDoPost(request,response);}}publicvoidcontinueDoPost(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{HttpSessionsession=request.getSession(true);Loginlogin=(Login)session.getAttribute("login");Stringlogname=login.getLogname();Connectioncon;课后答案网PreparedStatementsql;ModifyMessagemodify=newModifyMessage();request.setAttribute("modify",modify);StringadvertiseTitle=request.getParameter("newAdvertiseTitle").trim(),email=request.getParameter("newEmail").trim(),www.hackshp.cnphone=request.getParameter("newPhone").trim(),message=request.getParameter("newMessage");Stringuri="jdbc:sqlserver://127.0.0.1:1433;DatabaseName=Friend";StringbackNews="";try{con=DriverManager.getConnection(uri,"sa","sa");StringupdateCondition="UPDATEmemberSETadvertiseTitle=?,phone=?,email=?,message=?WHERElogname=?";sql=con.prepareStatement(updateCondition);sql.setString(1,handleString(advertiseTitle));sql.setString(2,phone);sql.setString(3,handleString(email));183若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnsql.setString(4,handleString(message));sql.setString(5,logname);intm=sql.executeUpdate();if(m==1){backNews="修改信息成功";modify.setBackNews(backNews);modify.setLogname(logname);modify.setNewAdvertiseTitle(handleString(advertiseTitle));modify.setNewEmail(handleString(email));modify.setNewPhone(phone);modify.setNewMessage(handleString(message));}else{backNews="信息填写不完整或信息中有非法字符";modify.setBackNews(backNews);}con.close();}catch(SQLExceptionexp){modify.setBackNews(""+exp);}RequestDispatcherdispatcher=request.getRequestDispatcher("showModifyMess.jsp");//转发课后答案网dispatcher.forward(request,response);}publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{doPost(request,response);www.hackshp.cn}}HandleExit.javapackagemyservlet.control;importmybean.data.*;importjava.sql.*;importjava.io.*;importjavax.servlet.*;importjavax.servlet.http.*;publicclassHandleExitextendsHttpServlet184若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn{publicvoidinit(ServletConfigconfig)throwsServletException{super.init(config);}publicStringhandleString(Strings){try{bytebb[]=s.getBytes("iso-8859-1");s=newString(bb);}catch(Exceptionee){}returns;}publicvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{HttpSessionsession=request.getSession(true);Loginlogin=(Login)session.getAttribute("login");//获取用户登录时的Javabeanbooleanok=true;if(login==null){ok=false;response.sendRedirect("login.jsp");//重定向到登录页面}if(ok==true){continueDoPost(request,response);}}课后答案网publicvoidcontinueDoPost(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{HttpSessionsession=request.getSession(true);session.invalidate();www.hackshp.cn//销毁用户的session对象response.sendRedirect("index.jsp");//返回主页}publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{doPost(request,response);}}185若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn'