JSP实用教程--程序源代码

283211093

贡献于2012-03-21

字数:166258 关键词: JSP Java开发

 (第二版) 清华大学出版社(耿祥义 张跃平编著) 程序源代码 建议使用文档结构图浏览使用 (选择Word菜单→视图→文档结构图) 摘 要 JSP是一种动态网页技术标准,利用这一技术可以建立安全、跨平台的先进动态网站。 本书是一本实用教程,配备了大量的例题,叙述详细,通俗易懂,便于自学,特别注重结合实例讲解一些难点和关键技术。全书共分10章,内容包括JSP简介、JSP语法、内置对象、JSP与Javabean、文件操作、数据库操作、JavaServlet、MVC设计模式、JSP中使用XML等重要内容。本书所有知识都结合具体实例进行介绍.力求详略得当,突出JSP在开发Web动态网站方面的强大功能,使读者快速掌握和运用JSP的编程技巧。 本书不仅可以作为大学计算机及相关专业的选修课教材,也适合自学者及网站开发人员参考使用。 前 言 本书是《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章对Java Servlet在MVC开发模式中的地位给予了重点介绍,并按着MVC模式给出了易于理解MVC设计模式的例子。第9章介绍了XML语言以及在JSP中怎样有效地使用XML文件。第10章是一个完整的网站,完全按着MVC模式开发设计,其目的是掌握一般Web应用中常用基本模块的开发方法。 作者简介 耿祥义,1995年中国科学技术大学博士毕业,获理学博士学位。1997年从中山大学博士后流动站出站。现任大连交通大学教授。已编写出版《Java 2实用教程》、《Java 课程设计》、《JSP 实用教程》、《JSP 基础教程》、《XML 基础教程》等10余部教材。 张跃平,现任大连交通大学讲师。已编写和参编出版《Visual FoxPro课程设计》、《Java 2实用教程》、《JSP 实用教程》3部教材。 希望本教材能对读者学习JSP有所帮助,并请读者批评指正(xygeng0629@sina.com)。 编者 2007年05月 第1章 JSP 简介 1 例子1 1 第2章 JSP语法 2 例子1 2 <%@ page contentType="text/html;charset=GB2312" %> 2 <% date=new Date(); //java程序片 2 <%= start %> 2 例子2 2 例子3 3 例子4 3 例子5 4 例子6 4 例子7 5 例子8 5 例子9 6 例子10 7 例子11 7 例子12 8 例子13 9 第3章 JSP 内置对象 10 例子1 10 例子2 10 例子3 11 例子4 12 例子5 14 例子6 15 例子7 16 例子8 17 例子9 17 例子10 18 例子11 18 例子12 19 例子13 20 例子14 21 例子15 22 例子16 24 例子17 25 例子18 27 例子19 29 第4章 JSP与JavaBean 31 Circle.java 31 例子1 31 例子2 32 例子3 32 NewCircle.java 32 例子4 33 Student.java 33 例子5 34 Goods.java 34 例子6 35 ListFile.java 36 例子7 36 三角形bean 37 Triangle.java 37 四则运算bean 38 ComputerBean.java 38 computer.jsp 40 计数器bean 40 CounterCount.java 40 comeOne.jsp 42 comeTwo.jsp 42 浏览图像 bean 42 Play.java 42 play.jsp 43 成绩单 bean 44 ScoreList.java 44 studentScore.jsp 45 日历bean 46 CalendarBean.java 46 showCalendar.jsp 48 第5章 JSP中的文件操作 49 例子1 49 FileDir.java 49 fileAndDir.jsp 50 例子2 50 ReadFile.java 50 selectDir.jsp 52 listfile.jsp 52 例子3 53 WriterFile.java 53 writefile.jsp 54 例子4 55 UpFile.java 55 upfile.jsp 58 show.jsp 58 例子5 58 DownLoadFile.java 58 downfile.jsp 59 例子6 60 ReadByRow.java 60 selectfile.jsp 61 readByRow.jsp 62 例子7 62 Test.java 62 test.jsp 65 第6章 JSP中使用数据库 67 例子1 67 showByJdbcOdbc.jsp 67 例子2 68 showBySQLDriver.jsp 68 例子3 69 QueryBean.java 69 inquire.jsp 71 例子4 72 RandomQueryBean.java 72 random.jsp 74 例子5 75 ConditionQuery.java 75 condition.jsp 77 例子6 78 OrderQuery.java 78 sort.jsp 79 例子7 80 KeyWordQuery.java 80 keyWord.jsp 82 例子8 82 AddBean.java 82 add.jsp 84 例子9 85 ShowRecordByPage.java 85 showByPage.jsp 88 例子10 89 linkOracle.jsp 89 例子11 90 linkMySql.jsp 90 例子12 91 MySqlBean.java 91 mysql.jsp 93 例子13 94 inquireExcel.jsp 94 例子14 95 ApplicationCon.java 95 UseConBean.java 96 chaxun.jsp 97 例子15 98 PreparedQueryBean.java 98 pre.jsp 100 例子16 100 AddRecordBean.java 100 addRecord.jsp 102 第7章Java Servlet基础 104 HelloBeijing.java: 104 web.xml 104 例子1 105 giveRadius.jsp 105 Computer.java 105 例子2 106 showLetter.jsp 106 ShowLetter.java 106 例子3 107 showPI.jsp 107 ComputerPI.java 107 例子4 108 method.jsp 108 GetSqare.java 108 GetSquareOrCubic.java 109 例子5 111 input.jsp 111 Verify.java 111 ShowMessage.java 112 例子6 113 Boy.java 113 Look.java 114 例子7 115 getLetter.jsp 115 inputLetter.jsp 115 HandleGuess.java 116 第8章 基于Servlet的MVC模式 118 web.xml 118 sun.yourservlet.HandleSum 118 Series.java 118 inputMess.jsp 119 showResult.jsp 120 HandleSum.java 120 计算一元二次方程的根 122 Equation.java 122 input.jsp 123 show.jsp 123 HandleData.java 124 简单的计算器 125 ComputerBean.java 125 inputNumber.jsp 126 showResult.jsp 126 HandleComputer.java 127 读取文件 129 FileMessage.java 129 choiceFile.jsp 129 showFile.jsp 130 HandleFile.java 130 查询数据库 131 ShowRecordByPage.java 131 choiceDatabase.jsp 133 showRecord.jsp 133 HandleDatabase.java 134 第9章 JSP中使用XML 139 例子1 139 Score.xml 139 input.jsp 140 Number.java 140 例子2 142 trainList.xml 142 train.jsp 143 SAXBean.java 144 例子3 147 type.jsp 147 formula.xml 147 show.css 148 第10章 基于会员制的网络广告系统 150 head.txt 150 index.jsp 150 web.xml 150 Register.java 152 register.jsp 153 showRegisterMess.jsp 154 HandleRegister.java 155 RequestDispatcher dispatcher= 157 Login.java 157 login.jsp 158 showLoginMess.jsp 158 HandleLogin.java 159 UploadFile.java 161 upload.jsp 162 showUploadMess.jsp 162 HandleUpload.java 163 MemberInform.java 167 ShowByPage.java 168 choiceLookType.jsp 169
分页显示全体会员 169 showAllMember.jsp 169 showLookedMember.jsp 170 HandleDatabase.java 171 Password.java 175 modifyPassword.jsp 175 showNewPasswor.jsp 176 HandlePassword.java 176 RequestDispatcher dispatcher= 177 ModifyMessage.java 178 choiceModifyMess.jsp 179 inputModifyMess.jsp 179 GetOldMess.java 180 RequestDispatcher dispatcher= 182 HandleModifyMess.java 182 RequestDispatcher dispatcher= 184 HandleExit.java 184 第1章 JSP 简介 例子1 example1_1.jsp <%@ page contentType="text/html;charset=GB2312" %>

这是一个简单的JSP页面

<% int i, sum=0; for(i=1;i<=100;i++) { sum=sum+i; } %>
1到100的连续和是: <%=sum %>
第2章 JSP语法 例子1 example2_1.jsp <%@ page contentType="text/html;charset=GB2312" %> <%@ page import="java.util.Date" %> <%! Date date; // 数据声明 int start,end,sum; public int continueSum(int start,int end) // 方法声明 { for(int i=start;i<=end;i++) sum=sum+i; return sum; } %>

程序片创建Date对象: <% date=new Date(); //java程序片 out.println("
"+date); start=1; end=100; sum=continueSum(start,end); %>
从 <%= start %> 至 <%= end %> 的连续和是 <%= sum %>
例子2 example2_2.jsp: <%@ page contentType="text/html;charset=GB2312" %> <%! int i=0; %> <% i++; %>

您是第 <%= i %> 个访问本站的客户。 例子3 example2_3.jsp: <%@ page contentType="text/html;charset=GB2312" %> <%! double x,y; double multi(double x,double y) { return x*y; } double div(double x,double y) { return x/y; } %> <% x=127; y=18; out.println("调用multi方法计算"+x+"与"+y+"之积:"); double a=multi(x,y); out.println(a); x=a; out.println("
调用div方法计算"+x+"除以"+y+"的商:"); double b=div(x,y); out.println(b); %> 例子4 example2_4.jsp <%@ page contentType="text/html;Charset=GB2312" %> <%! int count=0; //被客户共享的count synchronized void setCount() //synchronized修饰的方法 { count++; } %> <% setCount(); out.println("您是第"+count+"个访问本站的客户"); %> 例子5 example2_5.jsp <%@ page contentType="text/html;Charset=GB2312" %>

输出英文字母. <% char start='A',end='M',c; int size=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 %>, <% } %> 例子6 example2_6.jsp: <%@ page contentType="text/html;charset=GB2312" %> <% double a=12.89; int x=12,y=10; %> 计算表达式a+x*y-100/x+x%5的值: <%= 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)%>
例子7 example2_7.jsp: <%@ page contentType="text/html;charset=GB2312" %> 抽取字符串"C:\myfile\jspfile\example.jsp"中的"example.jsp" <%-- 下面是成员变量的声明 --%> <%! String s="C:\\myfile\\jspfile\\example.jsp"; %> <%-- 下面是Java程序片 --%> <% int index=s.lastIndexOf("\\"); String str=s.substring(index+1); %>
<%-- 下面是Java表达式 --%> <%= str %> 例子8 first.jsp <%@ page contentType="text/html;Charset=GB2312" %>

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

启动powerpoint应用程序处理所接受到的信息. third.jsp <%@ page contentType="image/x-xbitmap" %> <%@ page import="java.awt.*" %> <%@ page import="java.io.*" %> <%@ page import="java.awt.image.*" %> <%@ page import="java.awt.geom.*" %> <%@ page import="com.sun.image.codec.jpeg.*" %> <% int width=260, height=260; BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB); Graphics g = image.getGraphics(); g.setColor(Color.white); g.fillRect(0, 0, width, height); Graphics2D g_2d=(Graphics2D)g; Ellipse2D ellipse=new Ellipse2D. Double (40,50,100,40); g_2d.setColor(Color.blue); g_2d.draw(ellipse); Polygon polygon=new Polygon(); polygon.addPoint(12,34); polygon.addPoint(51,134); polygon.addPoint(102,34); g_2d.drawPolygon(polygon); g_2d.dispose(); OutputStream outClient= response.getOutputStream(); //获取指向客户端的输出流 JPEGImageEncoder encoder=JPEGCodec.createJPEGEncoder(outClient); encoder.encode(image); %> 例子9 example2_9.jsp <%@ page contentType="text/html;charset=GB2312" %> <%@ page info="清华大学" %> <% String s=getServletInfo(); %> <%= s %>
<%=s %>出版社是中国著名出版社
<%=s %>是全国著名的高等学府 例子10 firstExample2_10.jsp <%@ page contentType="text/html;charset=GB2312" %> <%@ include file="myfile/ok.txt" %>

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

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

我是firstExample.jsp页面 例子11 example2_11.jsp <%@ page contentType="text/html;charset=GB2312" %> <% double a=3,b=4,c=5; %>
加载trangle.jsp计算三边为<%=a%>,<%=b%>,<%=c%>的三角形面积: trangle.jsp <%@ page contentType="text/html;charset=GB2312" %> <%! public String getArea(double a,double b,double c) { if(a+b>c&&a+c>b&&c+b>a) { double p=(a+b+c)/2.0; double area=Math.sqrt(p*(p-a)*(p-b)*(p-c)) ; return ""+area; } else { return(""+a+","+b+","+c+"不能构成一个三角形,无法计算面积"); } } %> <% String sideA=request.getParameter("sideA"); String sideB=request.getParameter("sideB"); String sideC=request.getParameter("sideC"); double a=Double.parseDouble(sideA); double b=Double.parseDouble(sideB); double c=Double.parseDouble(sideC); %>

我是被加载的文件,负责计算三角形的面积
给我传递的三边是:<%=sideA%>,<%=sideB%>,<%=sideC%>
三角形的面积:<%= getArea(a,b,c)%>
例子12 example2_12.jsp <%@ page contentType="text/html;charset=GB2312" %> <% double i=Math.random(); if(i>0.5) { %> <% } else { %> <% } %> frontSide.jsp <%@ page contentType="text/html;charset=GB2312" %> <% String s=request.getParameter("number"); out.println("
传递过来的值是"+s); %>
钱币图像
reverseSide.jsp <%@ page contentType="text/html;charset=GB2312" %> <% String s=request.getParameter("number"); out.println("传递过来的值是"+s); %>
钱币图像
例子13 example2_13.jsp: <%@ page contentType="text/html;charset=GB2312" %> Plugin tag OBJECT or EMBED not supported by browser. 第3章 JSP 内置对象 例子1 example3_1.jsp <%@ page contentType="text/html;charset=GB2312" %>

computer.jsp <%@ page contentType="text/html;charset=GB2312" %> <% String sideA=request.getParameter("sizeA"); String sideB=request.getParameter("sizeB"); String sideC=request.getParameter("sizeC"); try { double a=Double.parseDouble(sideA); double b=Double.parseDouble(sideB); double c=Double.parseDouble(sideC); double p=(a+b+c)/2,area=0; area=Math.sqrt(p*(p-a)*(p-b)*(p-c)); out.println("
三角形面积"+area); } catch(NumberFormatException ee) { out.println("
请输入数字字符"); } %>
例子2 example3_2.jsp(如图3.2所示) <%@ page contentType="text/html;charset=GB2312" %>
<% String textContent=request.getParameter("girl"); double number=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(NumberFormatException e) { out.print("
"+"请输入数字字符"); } %>
例子3 example3_3.jsp <%@ page contentType="text/html;Charset=GB2312" %>
showMessage1.jsp <%@ page contentType="text/html;Charset=GB2312" %>

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

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

获取文本框提交的信息: <% String textContent=request.getParameter("boy"); byte b[]=textContent.getBytes("ISO-8859-1"); textContent=new String(b); %>
<%=textContent%>

获取按钮的名字: <% String buttonName=request.getParameter("submit"); byte c[]=buttonName.getBytes("ISO-8859-1"); buttonName=new String(c); %>
<%=buttonName%> 例子4 example3_4.jsp <%@ page contentType="text/html;Charset=GB2312" %> <%@ page import="java.util.*" %> <% String protocol=request.getProtocol(); //协议 String path=request.getServletPath(); //请求的页面 String method=request.getMethod(); //提交信息的方式 String userAgentHeader=request.getHeader("User-Agent");//User-Agent头的值 String acceptHeader=request.getHeader("accept");//accept头的值 String hostHeader=request.getHeader("Host");//Host头的值 String acceptEncodingHeader=request.getHeader("accept-encoding");//accept-encoding头的值 String clientIP=request.getRemoteAddr();//客户的IP地址 String serverName=request.getServerName();//服务器的名称 int serverPort=request.getServerPort(); // 服务器的端口号 %>
客户使用的协议是:<%=protocol %>
客户请求的页面:<%=path %>
客户提交信息的方式:<%=method %>
头文件中User-Agent头的值:<%=userAgentHeader %>
accept头的值:<%=acceptHeader %>
Host头的值:<%=hostHeader %>
accept-encoding头的值:<%=acceptEncodingHeader %>
客户的IP地址:<%=clientIP %>
服务器的端口号:<%=serverPort %>
获取客户端提交的所有参数的名字: <% Enumeration enumOne=request.getParameterNames(); while(enumOne.hasMoreElements()) {String s=(String)enumOne.nextElement(); out.println(s); } %>
获取头名字的一个枚举: <% Enumeration enum_headed=request.getHeaderNames(); while(enum_headed.hasMoreElements()) {String s=(String)enum_headed.nextElement(); out.println(s); } %>
获取头文件中指定头名字cookie 的全部值的一个枚举: <% Enumeration enum_headedValues=request.getHeaders("cookie"); while(enum_headedValues.hasMoreElements()) { String s=(String)enum_headedValues.nextElement(); out.println(s); } %>
例子5 example3_5.jsp <%@ page contentType="text/html;Charset=GB2312" %>


输入您的姓名:

选择性别:

选择您喜欢的球队: 国际米兰队 AC米兰队 罗马队 慕尼黑队
receive.jsp <%@ page contentType="text/html;Charset=GB2312" %> <% String yourName=request.getParameter("name"); //获取text提交的值 String yourSex=request.getParameter("R"); //获取radio提交的值 String secretMess=request.getParameter("secret"); //获取hidden提交的值 String itemName[]=request.getParameterValues("item"); //获取checkbox提交的值 out.println("

您的姓名:"+yourName+"

"); out.println("

您的性别:"+yourSex+"

"); out.println("

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

选择计算和的方式:

选择n的值:

sum.jsp <%@ page contentType="text/html;charset=GB2312" %>
<% long sum=0; String s1=request.getParameter("sum"); String s2=request.getParameter("n"); if(s1.equals("1")) {int n=Integer.parseInt(s2); for(int i=1;i<=n;i++) {sum=sum+i; } } else if(s1.equals("2")) {int n=Integer.parseInt(s2); for(int i=1;i<=n;i++) {sum=sum+i*i; } } else if(s1.equals("3")) {int n=Integer.parseInt(s2); for(int i=1;i<=n;i++) {sum=sum+i*i*i; } } %>

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

例子7 example3_7.jsp <%@ page contentType="text/html;Charset=GB2312" %>
输入您的姓名:
选择性别:
选择您喜欢的球队: 国际米兰队 AC米兰队 罗马队 慕尼黑队
例子8 example3_8.jsp <%@ page contentType="text/html;charset=GB2312" %>

选择一副图像:
选择视频或音乐:
show.jsp <%@ page contentType="text/html;charset=GB2312" %> <% String s1=request.getParameter("image"); String s2=request.getParameter("video"); %> 图像 视频 例子9 example3_9.jsp <%@ page contentType="text/html;charset=GB2312" %>

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

将当前页面保存为word文档吗?

<% String str=request.getParameter("submit"); if(str==null) { str=""; } if(str.equals("yes")) { response.setContentType("application/msword;charset=GB2312"); } %>
例子10 example3_10.jsp <%@ page contentType="text/html;charset=GB2312" %> <%@ page import="java.util.*" %>

现在的时间是:
<% out.println(""+new Date()); response.setHeader("Refresh","5"); %>
例子11 example3_11.jsp <%@ page contentType="text/html;charset=GB2312" %>

填写姓名:

form.jsp <%@ page contentType="text/html;Charset=GB2312" %>  <% String str=request.getParameter("boy"); if(str.length()==0) { response.sendRedirect("example3_11.jsp"); } else { out.print("欢迎您来到本网页!"); out.print(str); } %> 例子12 example3_12.jsp <%@ page contentType="text/html;charset=GB2312" %>

点击下面的超链接:
bird1:欢迎你吗?
bird2:欢迎你吗?
bird3:欢迎你吗?
bird1.jsp <% response.setStatus(408); out.print("不显示了"); %> bird2.jsp <%@ page contentType="text/html;charset=GB2312" %> <% response.setStatus(200); out.println("ok"); %> bird3.jsp <%@ page contentType="text/html;charset=GB2312" %> <% response.setStatus(500); %> 例子13 first.jsp <%@ page contentType="text/html;charset=GB2312" %> 我是first.jsp页面,输入你的姓名连接到second.jsp <% String id=session.getId(); out.println("您的session对象的ID是:
"+id); %>

second.jsp <%@ page contentType="text/html;Charset=GB2312" %> 我是second.jsp页面 <% String id=session.getId(); out.println("您的session对象的ID是:
"+id); %>
点击超链接,连接到third.jsp的页面。
欢迎去third.jsp页面! third.jsp <%@ page contentType="text/html;charset=GB2312" %> 我是third.jsp页面 <% String id=session.getId(); out.println("您的session对象的ID是:
"+id); %>
点击超链接,连接到first.jsp的页面。 欢迎去first.jsp! 例子14 main.jsp <%@ page contentType="text/html;Charset=GB2312" %>

欢迎来到本页面,请输入您的姓名

<% String name=request.getParameter("name"); if(name==null) { name=""; } else { session.setAttribute("customerName",name); } %> <% if(name.length()>0) { %>

点击超链接,连接到book.jsp的页面,去选择书籍。 欢迎去选择书籍! <% } %> book.jsp <%@ page contentType="text/html;charset=GB2312" %>

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

请选择您要购买的书籍:

Java教程 数据库原理 操作系统 C语言教程
<% String bookName[]=request.getParameterValues("choice"); if(bookName!=null) { for(int k=0;k 去结帐: 欢迎去count.jsp! count.jsp <%@ page contentType="text/html;Charset=GB2312" %> <%@ page import="java.util.*" %> 这里是结帐处,您的姓名以及选择的书籍: <% String personName=(String)session.getAttribute("customerName"); out.println("
您的姓名:"+personName); Enumeration enumGoods=session.getAttributeNames(); out.println("
购物车中的商品:
"); while(enumGoods.hasMoreElements()) { String key=(String)enumGoods.nextElement(); String goods=(String)session.getAttribute(key); if(!(goods.equals(personName))) out.println(goods+"
"); } %> 连接到book.jsp的页面,继续购买书籍:欢迎去book.jsp!
连接到main.jsp的页面,去修改姓名:欢迎去main.jsp!
例子15 getNumber.jsp <%@ page contentType="text/html;charset=GB2312" %>

随机分给了你一个1到100之间的数,请猜! <% int number=(int)(Math.random()*100)+1; session.setAttribute("count",new Integer(0)); session.setAttribute("save",new Integer(number)); %>

输入你的所猜的数:

result.jsp <% String str=request.getParameter("boy"); if(str.length()==0) { response.sendRedirect("getNumber.jsp"); } else { int guessNumber=Integer.parseInt(str); Integer integer=(Integer)session.getAttribute("save"); int realnumber=integer.intValue(); if(guessNumber==realnumber) { int n=((Integer)session.getAttribute("count")).intValue(); n=n+1; session.setAttribute("count",new Integer(n)); response.sendRedirect("success.jsp"); } else if(guessNumber>realnumber) { int n=((Integer)session.getAttribute("count")).intValue(); n=n+1; session.setAttribute("count",new Integer(n)); response.sendRedirect("large.jsp"); } else if(guessNumber large.jsp <%@ page contentType="text/html;charset=GB2312" %>

所猜的数比实际的数大,请再猜:

small.jsp <%@ page contentType="text/html;charset=GB2312" %>

所猜的数比实际的数小,请再猜:

success.jsp <%@ page contentType="text/html;charset=GB2312" %> <% int count=((Integer)session.getAttribute("count")).intValue(); int num=((Integer)session.getAttribute("save")).intValue(); %>

恭喜你,猜对了

您共猜了<%=count%>次

这个数字就是<%=num%> 例子16 example3_16.jsp <%@ page contentType="text/html;Charset=GB2312" %> <%@ page import="java.util.*" %> <% session.setMaxInactiveInterval(15); boolean boo=session.isNew(); out.println("
如果你第一次访问当前web服务目录,您的会话是新的"); out.println("
如果你不是首次访问当前web服务目录,您的会话不是新的"); out.println("
会话是新的吗?:"+boo); out.println("
欢迎来到本页面,您的session允许的最长发呆时间为"+ session.getMaxInactiveInterval()+"秒"); out.println("
您的session的创建时间是"+new Date(session.getCreationTime())); out.println("
您的session的Id是"+session.getId()); Long lastTime=(Long)session.getAttribute("lastTime"); if(lastTime==null) { long n=session.getLastAccessedTime(); session.setAttribute("lastTime",new Long(n)); } else { long m=session.getLastAccessedTime(); long n=((Long)session.getAttribute("lastTime")).longValue(); out.println("
您的发呆时间大约是"+(m-n)+"毫秒,大约"+(m-n)/1000+"秒"); session.setAttribute("lastTime",new Long(m)); } %> 例子17 comeOne.jsp <%@ page contentType="text/html;Charset=GB2312" %> <%@ taglib prefix="person" tagdir="/WEB-INF/tags" %>

Welcome欢迎您访问本站,这是本网站的comeTwo.jsp页面
您是第 <%=(String)session.getAttribute("count")%> 个访问本网站的客户。 欢迎去comeTwo.jsp参观 comeTwo.jsp <%@ page contentType="text/html;Charset=GB2312" %> <%@ taglib prefix="person" tagdir="/WEB-INF/tags" %>

欢迎您访问本站,这是本网站的comeOne.jsp页面
您是第 <%=(String)session.getAttribute("count")%> 个访问本网站的客户。 欢迎去comeOne.jsp参观 count.jsp <%@ page contentType="text/html;charset=GB2312" %> <%@ page import="java.io.*" %> <%! int number=0; File file=new File("countNumber.txt") ; synchronized void countPeople()//计算访问次数的同步方法 { if(!file.exists()) { number++; try { file.createNewFile(); FileOutputStream out=new FileOutputStream(file); DataOutputStream dataOut=new DataOutputStream(out); dataOut.writeInt(number); out.close(); dataOut.close(); } catch(IOException ee){} } else { try{ FileInputStream in=new FileInputStream(file); DataInputStream dataIn=new DataInputStream(in); number=dataIn.readInt(); number++; in.close(); dataIn.close(); FileOutputStream out=new FileOutputStream(file); DataOutputStream dataOut=new DataOutputStream(out); dataOut.writeInt(number); out.close(); dataOut.close(); } catch(IOException ee){} } } %> <% String str=(String)session.getAttribute("count"); if(session.isNew()) { out.println("请首先访问其它网页"); } else { if(str==null) { countPeople(); String personCount=String.valueOf(number); session.setAttribute("count",personCount); } } %> 例子18 submit.jsp <%@ page contentType="text/html;charset=GB2312" %>

输入您的名字:

输入您的留言标题:

输入您的留言:

messagePane.jsp <%@ page contentType="text/html;Charset=GB2312" %> <%@ page import="java.util.*" %> <%! Vector v=new Vector(); int i=0; ServletContext application; synchronized void sendMessage(String s) { application=getServletContext();; i++; v.add("No."+i+","+s); application.setAttribute("Mess",v); } %> <% String name=request.getParameter("peopleName"); String title=request.getParameter("Title"); String messages=request.getParameter("messages"); if(name==null) {name="guest"+(int)(Math.random()*10000); } if(title==null) {title="无标题"; } if(messages==null) {messages="无信息"; } String s="姓名:"+name+"#"+"标题:"+title+"#"+"内容:"+"
"+messages; sendMessage(s); out.print("您的信息已经提交!"); %> 返回 showMessage.jsp <%@ page contentType="text/html;charset=GB2312" %> <%@ page import="java.util.*" %> <% Vector v=(Vector)application.getAttribute("Mess"); for(int i=0;i"+str); } } %> 例子19 example3_19.jsp <%@ page contentType="text/html;charset=GB2312" %> <%@ page import="java.util.*"%> <%! public String getDayWeek(int n) { String week[]={"星期日","星期一","星期二","星期三","星期四","星期五","星期六"}; return week[n]; } %> <% Calendar calendar=Calendar.getInstance(); //创建一个日历对象。 calendar.setTime(new Date());//用当前时间初始化日历时间。 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); int hour=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(""); out.println(""); out.println(""); out.println(""); out.println(""); if(日.equals("26")) {out.print("

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

"); } else { out.print("

注意防范病毒!

"); } %>  第4章 JSP与JavaBean Circle.java package tom.jiafei import java.io.*; public class Circle { int radius; public Circle() { radius=1; } public int getRadius() { return radius; } public void setRadius(int newRadius) {radius=newRadius; } public double circleArea() {return Math.PI*radius*radius; } public double circlLength() {return 2.0*Math.PI*radius; } } 例子1 useBean.jsp <%@ page contentType="text/html;charset=GB2312" %> <%@ page import="tom.jiafei.Circle"%> <%--通过上述JSP标记,客户获得了一个作用域是page,名字是circle的bean --%> <% circle.setRadius(888); %>

圆的半径是:<%=circle.getRadius()%>

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

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

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

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

修改后的圆的半径是:<%=girl.getRadius()%>
bean1.jsp
例子3 appbean.jsp <%@ page contentType="text/html;charset=GB2312" %> <%@ page import="tom.jiafei.*"%>

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

修改后的圆的半径是:<%=girl.getRadius()%> NewCircle.java package tom.jiafei; import java.io.*; public class NewCircle { double radius=1,circleArea,circleLength; public double getRadius() { return radius; } public void setRadius(double newRadius) { radius=newRadius; } public double getCircleArea() { circleArea=Math.PI*radius*radius; return circleArea; } public double getCircleLength() { circleLength=2.0*Math.PI*radius; return circleLength; } } 例子4 beanGetProperty.jsp <%@ page contentType="text/html;charset=GB2312" %> <%@ page import="tom.jiafei.NewCircle"%> <% apple.setRadius(100);%> 圆的半径是:
圆的面积是:
圆的周长是: Student.java public class Student { String name=null; long number; double height,weight; public String getName() { return name; } public void setName(String newName) {name=newName; } public long getNumber() {return number; } public void setNumber(long newNumber) { number=newNumber; } public double getHeight() {return height; } public void setHeight(double newHeight) { height=newHeight; } public double getWeight() {return weight; } public void setWeight(double newWeight) { weight=newWeight; } } 例子5 student.jsp <%@ page contentType="text/html;charset=GB2312" %> <%@ page import="tom.jiafei.Student"%> 名字是:
学号是:
身高是:
体重是: 公斤
Goods.java package tom.jiafei; public class Goods { String name,goodsNumber; double price; public String getName() { return name; } public void setName(String newName) { name=newName; } public String getGoodsNumber() { return goodsNumber; } public void setGoodsNumber(String s) { goodsNumber=s; } public double getPrice() { return price; } public void setPrice(double newPrice) { price=newPrice; } } 例子6 goods.jsp <%@ page contentType="text/html;Charset=GB2312" %> <%@ page import="tom.jiafei.*"%>
输入商品的名称:
输入商品的代号:
输入商品的价格:

提交表单才能设置商品的信息
商品的名称:
商品的代号:
商品的价格:
ListFile.java package tom.jiafei; import java.io.*; class FileName implements FilenameFilter { String str=null; FileName (String s) { str="."+s; } public boolean accept(File dir,String name) { return name.endsWith(str); } } public class ListFile { String extendsName=null; StringBuffer allFileName; public void setExtendsName(String s) { extendsName=s; } public String getExtendsName() { return extendsName; } public StringBuffer getFileName() { File dir=new File("d:/2000"); FileName help=new FileName(extendsName); String file_name[]=dir.list(help); for(int i=0;i <%@ page import="tom.jiafei.*"%>
输入文件的扩展名:

扩展名是 的文件有:
三角形bean Triangle.java package red.star; public class Triangle { double sideA=-1,sideB=-1,sideC=-1, area=-1; boolean triangle; public void setSideA(double a) { sideA=a; } public double getSideA() { return sideA; } public void setSideB(double b) { sideB=b; } public double getSideB() { return sideB; } public void setSideC(double c) { sideC=c; } public double getSideC() { return sideC; } public double getArea() { double p=(sideA+sideB+sideC)/2.0; if(triangle) area=Math.sqrt(p*(p-sideA)*(p-sideB)*(p-sideC)); return area; } public boolean isTriangle() { if(sideA <%@ page import="red.star.Triangle"%>
输入三角形三边: 边A: 边B: 边C: 三角形的三边是: 边A:, 边B:, 边C:.
这三个边能构成一个三角形吗?
面积是:
四则运算bean ComputerBean.java package red.star; public class ComputerBean { double numberOne,numberTwo,result; String operator="+"; public void setNumberOne(double n) { numberOne=n; } public double getNumberOne() { return numberOne; } public void setNumberTwo(double n) { numberTwo=n; } public double getNumberTwo() { return numberTwo; } public void setOperator(String s) { operator=s.trim();; } public String getOperator() { return operator; } public double getResult() { if(operator.equals("+")) { result=numberOne+numberTwo; } else if(operator.equals("-")) { result=numberOne-numberTwo; } else if(operator.equals("*")) { result=numberOne*numberTwo; } else if(operator.equals("/")) { result=numberOne/numberTwo; } return result; } } computer.jsp <%@ page contentType="text/html;Charset=GB2312" %> <%@ page import="red.star.*" %>
size=6> size=6> =
计数器bean CounterCount.java package red.star; import java.io.*; public class ComputerCount { int number=0; boolean isCome=false; File file=new File("count.dat") ; private void countPeople() { if(!file.exists()) { number++; try { file.createNewFile(); FileOutputStream out=new FileOutputStream(file); DataOutputStream dataOut=new DataOutputStream(out); dataOut.writeInt(number); out.close(); dataOut.close(); } catch(IOException ee){} } else { try{ FileInputStream in=new FileInputStream(file); DataInputStream dataIn=new DataInputStream(in); number=dataIn.readInt(); number++; in.close(); dataIn.close(); FileOutputStream out=new FileOutputStream(file); DataOutputStream dataOut=new DataOutputStream(out); dataOut.writeInt(number); out.close(); dataOut.close(); } catch(IOException ee){} } isCome=true; } public int getNumber() { if(isCome==false) countPeople(); return number; } } comeOne.jsp <%@ page contentType="text/html;Charset=GB2312" %> <%@ page import="red.star.*" %>

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

Welcome欢迎您访问本站,这是本网站的comeTwo.jsp页面
您是第 个访问本网站的客户。 欢迎去comeOne.jsp参观 浏览图像 bean Play.java package red.star; import java.io.*; class FileName implements FilenameFilter { public boolean accept(File dir,String name) { boolean boo=false; if(name.endsWith(".jpg")||name.endsWith(".JPG")) boo=true; return boo; } } public class Play { int imageNumber=0,max; String pictureName[],playImage; public Play() { File dir=new File("D:/apache-tomcat-5.5.20/webapps/ch4/image"); pictureName=dir.list(new FileName()); max=pictureName.length; } public void setImageNumber(int n) { if(n<0) n=max-1; if(n==max) n=0; imageNumber=n; } public int getImageNumber() { return imageNumber; } public String getPlayImage() { playImage=new String(""); return playImage; } } play.jsp <%@ page contentType="text/html;Charset=GB2312" %> <%@ page import="red.star.*" %> 单击"上一张"或"下一张"按钮浏览图像

现在的时间:"+年+"年"+月+"月"+日+"日"+星期+""+hour+"点"+minute+"分"+second+"秒
成绩单 bean ScoreList.java package red.star; public class ScoreList { String studentName,courseName="",score=""; StringBuffer scoreWatch=new StringBuffer(); public void setScore(String n) { score=n; } public void setStudentName(String s) { studentName=s; } public void setCourseName(String s) { courseName=s; } public String getCourseName() { return courseName; } public StringBuffer getScoreWatch() { if(studentName!=null&&studentName.length()>0&&score.length()>0) { scoreWatch.append(""); scoreWatch.append(""); scoreWatch.append(studentName); scoreWatch.append(""); scoreWatch.append(""); scoreWatch.append(""+score); scoreWatch.append(""); scoreWatch.append(""); studentName=""; score=""; } return scoreWatch; } } studentScore.jsp <%@ page contentType="text/html;Charset=GB2312" %> <%@ page import="red.star.*" %>
课程名称: >
学生姓名:
学生成绩:

日历bean CalendarBean.java package red.star; import java.util.*; public class CalendarBean { String calendar=null; int year=-1,month=-1; public void setYear(int year) { this.year=year; } public int getYear() { return year; } public void setMonth(int month) { this.month=month; } public int getMonth() { return month; } public String getCalendar() { StringBuffer buffer=new StringBuffer(); Calendar rili=Calendar.getInstance(); rili.set(year,month-1,1); //将日历翻到year年month月1日,注意0表示一月, //依次类推,11表示12月。 //获取1日是星期几(get方法返回的值是1表示星期日,返回的值是7表示星期六): int 星期几=rili.get(Calendar.DAY_OF_WEEK)-1; int day=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)) { day=29; } else { day=28; } } String a[]=new String[42]; for(int i=0;i<星期几;i++) { a[i]="**"; } for(int i=星期几,n=1;i<星期几+day;i++) { a[i]=String.valueOf(n) ; n++; } for(int i=星期几+day,n=1;i<42;i++) { a[i]="**" ; } //用表格显示数组: buffer.append(""); buffer.append("") ; String weekday[]={"星期日","星期一","星期二","星期三","星期四","星期五","星期六"}; for(int k=0;k<7;k++) { buffer.append(""); } buffer.append("") ; for(int k=0;k<42;k=k+7) { buffer.append("") ; for(int j=k;j"+a[j]+""); } buffer.append("") ; } buffer.append(" <%@ page import="red.star.CalendarBean" %>
输入日历的年份: 选择日历的月份:
月的日历:
第5章 JSP中的文件操作 例子1 FileDir.java package user.file; import java.io.*; public class FileDir { String newWebDirName,oldWebDirName; StringBuffer allFiles; public FileDir() { allFiles=new StringBuffer(); } public void setNewWebDirName(String s) { newWebDirName=s; if(newWebDirName!=null) { File dir=new File("d:\\apache-tomcat-5.5.20\\webApps",newWebDirName); dir.mkdir(); } } public String getNewWebDirName() { return newWebDirName; } public void setOldWebDirName(String s) { oldWebDirName=s; } public String getOldWebDirName() { return oldWebDirName; } public StringBuffer getAllFiles() { if(oldWebDirName!=null) { File dir=new File("d:\\apache-tomcat-5.5.20\\webApps",oldWebDirName); File a[]=dir.listFiles(); for(int k=0;k子目录:"+a[k].getName()); } for(int k=0;k文件:"+a[k].getName()); } } return allFiles; } } fileAndDir.jsp <%@ page contentType="text/html;charset=GB2312" %> <%@ page import="user.file.FileDir" %>
输入新的Web服务目录的名字:
输入已有的Web服务目录的名字: 新创建的Web服务目录:
已有的Web服务目录 下的子目录和文件:
例子2 ReadFile.java package user.file; import java.io.*; public class ReadFile { String fileDir="c:/",fileName=""; String listFile,readContent; public void setFileDir(String s) { fileDir=s; } public String getFileDir() { return fileDir; } public void setFileName(String s) { fileName=s; } public String getFileName() { return fileName; } public String getListFile() { File dir=new File(fileDir); File file_name[]=dir.listFiles(); StringBuffer list=new StringBuffer(); for(int i=0;i"; } catch(IOException e) { readContent=""; } return readContent; } } selectDir.jsp <%@ page contentType="text/html;charset=GB2312" %>

请选择一个目录:
listfile.jsp <%@ page contentType="text/html;charset=GB2312" %> <%@ page import="user.file.ReadFile" %>

该目录 有如下文件:
输入一个文件名字: 文件: 内容如下:

重新选择目录 例子3 WriterFile.java package user.file; import java.io.*; public class WriterFile { String filePath=null, fileName=null, fileContent=null; boolean success; public void setFilePath(String s) { filePath=s; try{ File path=new File(filePath); path.mkdir(); } catch(Exception e){} } public String getFilePath() { return filePath; } public void setFileName(String s) { fileName=s; } public String getFileName() { return fileName; } public void setFileContent(String s) { fileContent=s; byte content[]=fileContent.getBytes(); try{ File file=new File(filePath,fileName); FileOutputStream in=new FileOutputStream(file) ; in.write(content,0,content.length); in.close(); success=true; } catch(Exception e) { success=false; } } public boolean isSuccess() { return success; } } writefile.jsp <%@ page contentType="text/html;Charset=GB2312" %> <%@ page import="user.file.WriterFile" %>
请选择一个目录:
输入保存文件的名字:
输入文件的内容:

<% if(ok.isSuccess()==true) { %> 你写文件成功,文件所在目录:
文件名字: <% } %>
例子4 UpFile.java package user.file; import java.io.*; import javax.servlet.http.*; public class UpFile { HttpServletRequest request; HttpSession session; String upFileMessage=""; public void setRequest(HttpServletRequest request) { this.request=request; } public void setSession(HttpSession session) { this.session=session; } public String getUpFileMessage() { String fileName=null; try{ String tempFileName=(String)session.getId();//客户的session的id File f1=new File("D:/apache-tomcat-5.5.20/webapps/ch5",tempFileName); FileOutputStream o=new FileOutputStream(f1); InputStream in=request.getInputStream(); byte b[]=new byte[10000]; int n; while( (n=in.read(b))!=-1) //将客户上传的全部信息存入f1 { o.write(b,0,n); } o.close(); in.close(); RandomAccessFile random=new RandomAccessFile(f1,"r"); int second=1; //读出f1的第2行,析取出上传文件的名字: String secondLine=null; while(second<=2) { secondLine=random.readLine(); second++; } //获取第2行中目录符号'\'最后出现的位置 int position=secondLine.lastIndexOf('\\'); //客户上传的文件的名字是: fileName=secondLine.substring(position+1,secondLine.length()-1); byte cc[]=fileName.getBytes("ISO-8859-1"); fileName=new String(cc); session.setAttribute("Name",fileName);//供show.jsp页面使用 random.seek(0); //再定位到文件f1的开头。 //获取第4行回车符号的位置: long forthEndPosition=0; int forth=1; while((n=random.readByte())!=-1&&(forth<=4)) { if(n=='\n') { forthEndPosition=random.getFilePointer(); forth++; } } //根据客户上传文件的名字,将该文件存入磁盘: File f2= new File("D:/apache-tomcat-5.5.20/webapps/ch5",fileName); RandomAccessFile random2=new RandomAccessFile(f2,"rw"); //确定出文件f1中包含客户上传的文件的内容的最后位置,即倒数第6行。 random.seek(random.length()); long endPosition=random.getFilePointer(); long mark=endPosition; int j=1; while((mark>=0)&&(j<=6)) { mark--; random.seek(mark); n=random.readByte(); if(n=='\n') { endPosition=random.getFilePointer(); j++; } } //将random流指向文件f1的第4行结束的位置: random.seek(forthEndPosition); long startPoint=random.getFilePointer(); //从f1读出客户上传的文件存入f2(读取第4行结束位置至倒数第6行之间的内容) while(startPoint <%@ page import="user.file.UpFile" %>

选择要上传的文件:

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

如果上传的是图像文件,可单击超链接查看图像:
查看图像 show.jsp <%@ page contentType="text/html;Charset=GB2312" %> <% String pic=(String)session.getAttribute("Name"); out.print(pic); out.print(""); %> 例子5 DownLoadFile.java package user.file; import java.io.*; import javax.servlet.http.*; public class DownLoadFile { HttpServletResponse response; String fileName; public void setResponse(HttpServletResponse response) { this.response=response; } public String getFileName() { return fileName; } public void setFileName(String s) { fileName=s; File fileLoad=new File("f:/2000",fileName); //客户使用下载文件的对话框: response.setHeader("Content-disposition","attachment;filename="+fileName); } } downfile.jsp <%@ page contentType="text/html;charset=GB2312" %> <%@ page import="user.file.DownLoadFile" %> <%@ page import="java.io.*" %>

选择要下载的文件:
<% downFile.setResponse(response); %> 例子6 ReadByRow.java package user.file; import java.io.*; public class ReadByRow { FileReader inOne; BufferedReader inTwo; String fileName; StringBuffer readMessage; int rows=0; public ReadByRow() { readMessage=new StringBuffer(); } public void setFileName(String s) { fileName=s; readMessage=new StringBuffer(); rows=0; File f=new File("D:/2000",fileName); try{ inOne=new FileReader(f); inTwo=new BufferedReader(inOne); } catch(IOException exp){} } public String getFileName() { return fileName; } public void setRows(int n) { rows=n; } public int getRows() { return rows; } public StringBuffer getReadMessage() { int i=1; try{ while(i<=rows) { String str=inTwo.readLine(); if(str==null) { inOne.close(); inTwo.close(); readMessage.append("文件读取完毕"); break; } else { readMessage.append("\n"+str); } i++; } } catch(Exception exp){} return readMessage; } } selectfile.jsp <%@ page contentType="text/html;charset=GB2312" %> <%@ page import="user.file.*" %>
选择一个文件:
输入每次读取的行数:
readByRow.jsp <%@ page contentType="text/html;charset=GB2312" %> <%@ page import="user.file.ReadByRow" %> 正在读取的文件的名字: 重新选择文件
例子7 Test.java package user.file; import java.io.*; public class Test { String fileName="", //存放考题文件名字的字符串 correctAnswer="", //存放正确答案的字符串 testContent="", //存放试题的字符串 selection="" ; //客户提交的答案的字符串 int score=0; //考试者的得分 int giveAnswerCount=0; //记录考试者提交答案的次数 String name="",number=""; //考试者姓名、学号 public void setFileName(String name) { fileName=name; selection="" ; score=0; giveAnswerCount=0; } public String getFileName() { return fileName; } public void setGiveAnswerCount(int number) { giveAnswerCount=number; } public int getGiveAnswerCount() { return giveAnswerCount; } public void setName(String s) { name=s; } public void setNumber(String num) { number=num; } public String getCorrectAnswer() //读取试题文件的第一行:标准答案 { try { File f=new File("D:/2000",fileName); FileReader in=new FileReader(f); BufferedReader buffer=new BufferedReader(in); correctAnswer=(buffer.readLine()).trim();//读取一行,去掉前后空格 buffer.close(); in.close(); } catch(Exception e) {} if(giveAnswerCount==1) { return correctAnswer; } else return "你只有一次提交答案的机会,不允许2次提交答案"; } public String getTestContent() //获取试题的内容 { StringBuffer temp=new StringBuffer(); try { if(fileName.length()>0) { File f=new File("D:/2000",fileName); FileReader in=new FileReader(f); BufferedReader buffer=new BufferedReader(in); String str=buffer.readLine(); //该行不显示给用户 while((str=buffer.readLine())!=null) //读出全部题目 { temp.append("\n"+str); } buffer.close(); in.close(); } } catch(Exception e){} return new String(temp); } public void setSelection(String s) { selection=s.trim(); } public String getSelection() { return selection; } public int getScore() { score=0; if(giveAnswerCount==1) { int length1=selection.length(); int length2=correctAnswer.length(); int min=(int)(Math.min(length1,length2)); int i=0; while(i <%@ page import="user.file.Test" %>
输入姓名: 输入学号: 请选择试题:
在文本框输入全部题目的答案,答案之间不允许有空格:

试题的正确答案:
您提交的答案:
您的分数 第6章 JSP中使用数据库 例子1 showByJdbcOdbc.jsp <%@ page contentType="text/html;charset=GB2312" %> <%@ page import="java.sql.*" %> <% Connection con; Statement sql; ResultSet rs; try{ Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); } catch(ClassNotFoundException e) { out.print(e); } try { con=DriverManager.getConnection("jdbc:odbc:mymoon","sa","sa"); sql=con.createStatement(); rs=sql.executeQuery("SELECT * FROM employee WHERE salary>3000"); out.print("

"+weekday[k]+"
"); out.print(""); out.print(""); while(rs.next()) { out.print(""); out.print(""); out.print(""); out.print(""); out.print(""); out.print("") ; } out.print("
"+"雇员号"); out.print(""+"姓名"); out.print(""+"出生日期"); out.print(""+"薪水"); out.print("
"+rs.getString(1)+""+rs.getString(2)+""+rs.getDate("birthday")+""+rs.getFloat("salary")+"
"); con.close(); } catch(SQLException e) { out.print(e); } %> 例子2 showBySQLDriver.jsp <%@ page contentType="text/html;charset=GB2312" %> <%@ page import="java.sql.*" %> <% Connection con; Statement sql; ResultSet rs; try { Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); } catch(Exception e) { out.print(e); } try { String uri= "jdbc:sqlserver://127.0.0.1:1433;DatabaseName=factory"; String user="sa"; String password="sa"; con=DriverManager.getConnection(uri,user,password); sql=con.createStatement(); rs=sql.executeQuery("SELECT * FROM employee WHERE salary>3000"); out.print(""); out.print(""); out.print(""); while(rs.next()) { out.print(""); out.print(""); out.print(""); out.print(""); out.print(""); out.print("") ; } out.print("
"+"雇员号"); out.print(""+"姓名"); out.print(""+"出生日期"); out.print(""+"薪水"); out.print("
"+rs.getString(1)+""+rs.getString(2)+""+rs.getDate("birthday")+""+rs.getFloat("salary")+"
"); con.close(); } catch(SQLException e) { out.print(e); } %> 例子3 QueryBean.java package database.operation; import java.sql.*; public class QueryBean { String databaseName=""; //数据库名 String tableName=""; //表名 String user="" ; //用户 String secret="" ; //密码 StringBuffer queryResult; //查询结果 public QueryBean() { queryResult=new StringBuffer(); try{ Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); } catch(Exception e) {} } public void setDatabaseName(String s) { databaseName=s.trim(); queryResult=new StringBuffer(); } public String getDatabaseName() { return databaseName; } public void setTableName(String s) { tableName=s.trim(); queryResult=new StringBuffer(); } public String getTableName() { return tableName; } public void setSecret(String s) { secret=s.trim(); queryResult=new StringBuffer(); } public String getSecret() { return secret; } public void setUser(String s) { user=s.trim(); queryResult=new StringBuffer(); } public String getUser() { return user; } public StringBuffer getQueryResult() { Connection con; Statement sql; ResultSet rs; try { queryResult.append(""); String uri= "jdbc:sqlserver://127.0.0.1:1433;DatabaseName="+databaseName; String id=user; String password=secret; con=DriverManager.getConnection(uri,id,password); DatabaseMetaData metadata=con.getMetaData(); ResultSet rs1=metadata.getColumns(null,null,tableName,null); int 字段个数=0; queryResult.append(""); while(rs1.next()) { 字段个数++; String clumnName=rs1.getString(4); queryResult.append(""); } queryResult.append(""); sql=con.createStatement(); rs=sql.executeQuery("SELECT * FROM "+tableName); while(rs.next()) { queryResult.append(""); for(int k=1;k<=字段个数;k++) { queryResult.append(""); } queryResult.append(""); } queryResult.append("
"+clumnName+"
"+rs.getString(k)+"
"); con.close(); } catch(SQLException e) { queryResult.append("请输入正确的用户名和密码"); } return queryResult; } } inquire.jsp <%@ page contentType="text/html;charset=GB2312" %> <%@ page import="database.operation.QueryBean" %>
输入数据库名: 输入表的名字:
输入用户名: 输入密码:
表查询到记录:
例子4 RandomQueryBean.java package database.operation; import java.sql.*; import java.util.*; public class RandomQueryBean { String databaseName=""; //数据库名称 String tableName=""; //表的名字 int count; //记录总数 int randomNumber; //随机输出的记录数 StringBuffer randomQueryResult; //查询结果 Connection con; Statement sql; ResultSet rs; public RandomQueryBean() { randomQueryResult=new StringBuffer(); try{ Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); } catch(Exception e){ } } public void setDatabaseName(String s) { databaseName=s.trim(); randomQueryResult=new StringBuffer(); } public String getDatabaseName() { return databaseName; } public void setTableName(String s) { tableName=s.trim(); randomQueryResult=new StringBuffer(); } public String getTableName() { return tableName; } public void setRandomNumber(int n) { randomNumber=n; randomQueryResult=new StringBuffer(); } public int getRandomNumber() { return randomNumber; } public int getCount() { try{ String uri="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(SQLException exp) { count=-1; } return count; } public StringBuffer getRandomQueryResult() { randomQueryResult=new StringBuffer(); try { randomQueryResult.append(""); String uri= "jdbc:sqlserver://127.0.0.1:1433;DatabaseName="+databaseName; con=DriverManager.getConnection(uri,"sa","sa"); DatabaseMetaData metadata=con.getMetaData(); ResultSet rs1=metadata.getColumns(null,null,tableName,null); int 字段个数=0; randomQueryResult.append(""); while(rs1.next()) { 字段个数++; String clumnName=rs1.getString(4); randomQueryResult.append(""); } randomQueryResult.append(""); sql=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); rs=sql.executeQuery("SELECT * FROM "+tableName); rs.last(); count=rs.getRow(); Vector vector=new Vector(); for(int i=1;i<=count;i++) { vector.add(new Integer(i)); } int 抽取数目=Math.min(randomNumber,count); while(抽取数目>0) { int i=(int)(Math.random()*vector.size()); int index=(vector.elementAt(i)).intValue();//vector中随机抽取一个元素 rs.absolute(index); //游标移到这一行 randomQueryResult.append(""); for(int k=1;k<=字段个数;k++) { randomQueryResult.append(""); } randomQueryResult.append(""); 抽取数目--; vector.removeElementAt(i); //将抽取过的元素从vector中删除 } randomQueryResult.append("
"+clumnName+"
"+rs.getString(k)+"
"); con.close(); } catch(SQLException e){ } randomNumber=0; return randomQueryResult; } } random.jsp <%@ page contentType="text/html;charset=GB2312" %> <%@ page import="database.operation.*" %>
随机查询数据库表中的记录:
输入数据库的名字: 输入表的名字:
输入要随机查询的记录数:
表中共有 条记录.
随机输出 条记录:
例子5 ConditionQuery.java package database.operation; import java.sql.*; public class ConditionQuery { String number ; //雇员号 float salaryMax,salaryMin; //薪水范围 StringBuffer queryResultByNumber, queryResultBySalary; public ConditionQuery() { queryResultByNumber=new StringBuffer(); queryResultBySalary=new StringBuffer(); try{ Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); } catch(Exception e){ } } public void setNumber(String s) { number=s.trim(); queryResultByNumber=new StringBuffer(); queryResultBySalary=new StringBuffer(); } public String getNumber() { return number; } public void setSalaryMax(float n) { salaryMax=n; queryResultByNumber=new StringBuffer(); queryResultBySalary=new StringBuffer(); } public float getSalaryMax() { return salaryMax; } public void setSalaryMin(float n) { salaryMin=n; queryResultByNumber=new StringBuffer(); queryResultBySalary=new StringBuffer(); } public float getSalaryMin() { return salaryMin; } public StringBuffer getQueryResultByNumber() { String condition="SELECT * FROM employee Where number = '"+number+"'"; queryResultByNumber=f(condition); return queryResultByNumber; } public StringBuffer getQueryResultBySalary() { String condition="SELECT * FROM employee Where salary <= "+salaryMax +" AND "+"salary >= "+salaryMin; queryResultBySalary=f(condition); return queryResultBySalary; } private StringBuffer f(String condition) { StringBuffer str=new StringBuffer(); Connection con; Statement sql; ResultSet rs; try { String uri="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(""); str.append(""); str.append(""); } str.append("
"+"number"); str.append(""+"name"); str.append(""+"birthday"); str.append(""+"salary"); while(rs.next()) { str.append("
"+rs.getString(1)+""+rs.getString(2)+""+rs.getDate(3)+""+rs.getFloat(4)+"
"); con.close(); } catch(SQLException e) { System.out.println(e); } return str; } } condition.jsp <%@ page contentType="text/html;charset=GB2312" %> <%@ page import="database.operation.*" %>
雇员查询(根据雇员号查询)
输入雇员号:
雇员查询(根据薪水查询)
薪水在之间 根据雇员号查询到的记录:
薪水在之间的记录:
例子6 OrderQuery.java package database.operation; import java.sql.*; public class OrderQuery { String orderType; //排序方式 StringBuffer orderResult; //排序结果 public OrderQuery() { orderResult=new StringBuffer(); try{ Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); } catch(Exception e){ } } public void setOrderType(String s) { orderType=s.trim(); try{ byte bb[]=orderType.getBytes("ISO-8859-1"); orderType=new String(bb,"gb2312"); } catch(Exception e){} } public String getOrderType() { return orderType; } public StringBuffer getOrderResult() { String orderCondition="SELECT * FROM employee ORDER BY "+orderType; Connection con; Statement sql; ResultSet rs; try { String uri="jdbc:sqlserver://127.0.0.1:1433;DatabaseName=factory"; con=DriverManager.getConnection(uri,"sa","sa"); sql=con.createStatement(); rs=sql.executeQuery(orderCondition); orderResult.append("
"); orderResult.append(""); orderResult.append(""); orderResult.append(""); orderResult.append(""); orderResult.append(""); orderResult.append(""); } orderResult.append("
"+"number"); orderResult.append(""+"name"); orderResult.append(""+"birthday"); orderResult.append(""+"salary"); while(rs.next()) { orderResult.append("
"+rs.getString(1)+""+rs.getString(2)+""+rs.getDate(3)+""+rs.getFloat(4)+"
"); con.close(); } catch(SQLException e) { System.out.println(e); } return orderResult; } } sort.jsp <%@ page contentType="text/html;charset=GB2312" %> <%@ page import="database.operation.*" %>
排序记录:按姓氏排序 按薪水排序 根据排序方式:,排序的记录
例子7 KeyWordQuery.java package database.operation; import java.sql.*; public class KeyWordQuery { String ziduan="", //字段 keyWord=""; //关键字 StringBuffer queryResult; public KeyWordQuery() { queryResult=new StringBuffer(); try{ Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); } catch(Exception e){ } } public void setKeyWord(String s) { keyWord=s.trim(); try{ byte bb[]=keyWord.getBytes("ISO-8859-1"); keyWord=new String(bb,"gb2312"); } catch(Exception e){} } public String getKeyWord() { return keyWord; } public void setZiduan(String s) { ziduan=s.trim(); try{ byte bb[]=ziduan.getBytes("ISO-8859-1"); ziduan=new String(bb,"gb2312"); } catch(Exception e){} } public String getZiduan() { return ziduan; } public StringBuffer getQueryResult() { String condition="SELECT * FROM employee Where "+ziduan+" Like '%"+keyWord+"%'"; StringBuffer str=f(condition); return str; } public StringBuffer f(String condition) { StringBuffer str=new StringBuffer(); Connection con; Statement sql; ResultSet rs; try { String uri="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(""); str.append(""); str.append(""); } str.append("
"+"雇员号"); str.append(""+"姓名"); str.append(""+"出生日期"); str.append(""+"薪水"); while(rs.next()) { str.append("
"+rs.getString(1)+""+rs.getString(2)+""+rs.getDate(3)+""+rs.getString(4)+"
"); con.close(); } catch(SQLException e) { System.out.println(e); } return str; } } keyWord.jsp <%@ page contentType="text/html;charset=GB2312" %> <%@ page import="database.operation.*" %>
选择: 含有: 含有关键字 的记录:
例子8 AddBean.java package database.operation; import java.sql.*; public class AddBean { String number="", //雇员号 name="", //姓名 birthday=""; //出生日期 float salary; //薪水 String addMessage=""; public AddBean() { try{ Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); } catch(Exception e){ } } public void setNumber(String s) { number=s.trim(); } public void setName(String s) { name=s.trim(); try{ byte bb[]=name.getBytes("ISO-8859-1"); name=new String(bb,"gb2312"); } catch(Exception e){} } public void setBirthday(String s) { birthday=s.trim(); } public void setSalary(float n) { salary=n; } public String getAddMessage() { String insertCondition="INSERT employee VALUES( '"+number+ "', '"+name+"','"+birthday+"',"+salary+")"; String str=""; Connection con; Statement sql; try { String uri="jdbc:sqlserver://127.0.0.1:1433;DatabaseName=factory"; con=DriverManager.getConnection(uri,"sa","sa"); sql=con.createStatement(); if(number.length()>0) { int m=sql.executeUpdate(insertCondition); if(m!=0) { str="对表中添加"+m+"条记录成功"; } else { str="添加记录失败"; } } else { str="必须要有雇员号"; } con.close(); } catch(SQLException e) { str="输入的雇员不允许重复"+e; } return str; } } add.jsp <%@ page contentType="text/html;charset=GB2312" %> <%@ page import="java.sql.*" %> <%@ page import="database.operation.*" %> 雇员号是主键,不可重复,请输入新记录的相应字段的值:
输入雇员号: 输姓名:
输入出生日期(****-**-**): 输入薪水:

你添加记录操作的结果:

数据库当前的数据记录是: 例子9 ShowRecordByPage.java package database.operation; import java.sql.*; import com.sun.rowset.*; public class ShowRecordByPage { int pageSize=10; //每页显示的记录数 int pageAllCount=0; //分页后的总页数 int showPage=1 ; //当前显示页 StringBuffer presentPageResult; //显示当前页内容 CachedRowSetImpl rowSet; //用于存储ResultSet对象 String databaseName=""; //数据库名称 String tableName=""; //表的名字 String user="" ; //用户 String password="" ; //密码 String 字段[]=new String[100] ; int 字段个数=0; public ShowRecordByPage() { presentPageResult=new StringBuffer(); try{ Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance(); } catch(Exception e){} } public void setPageSize(int size) { pageSize=size; 字段个数=0; String uri="jdbc:sqlserver://127.0.0.1:1433;DatabaseName="+databaseName; try{ Connection con=DriverManager.getConnection(uri,user,password); DatabaseMetaData metadata=con.getMetaData(); ResultSet rs1=metadata.getColumns(null,null,tableName,null); int k=0; while(rs1.next()) { 字段个数++; 字段[k]=rs1.getString(4); //获取字段的名字 k++; } Statement sql=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); ResultSet rs=sql.executeQuery("SELECT * FROM "+tableName); rowSet=new CachedRowSetImpl(); //创建行集对象 rowSet.populate(rs); con.close(); //关闭连接 rowSet.last(); int m=rowSet.getRow(); //总行数 int n=pageSize; pageAllCount=((m%n)==0)?(m/n):(m/n+1); } catch(Exception exp){} } public int getPageSize() { return pageSize; } public int getPageAllCount() { return pageAllCount; } public void setShowPage(int n) { showPage=n; } public int getShowPage() { return showPage; } public StringBuffer getPresentPageResult() { if(showPage>pageAllCount) showPage=1; if(showPage<=0) showPage=pageAllCount; presentPageResult=show(showPage); return presentPageResult; } public StringBuffer show(int page) { StringBuffer str=new StringBuffer(); str.append("

"); str.append(""); for(int i=0;i<字段个数;i++) { str.append(""); } str.append(""); try{ rowSet.absolute((page-1)*pageSize+1); for(int i=1;i<=pageSize;i++) { str.append(""); for(int k=1;k<=字段个数;k++) { str.append(""); } str.append(""); rowSet.next(); } } catch(SQLException exp){} str.append("
"+字段[i]+"
"+rowSet.getString(k)+"
"); return str; } public void setDatabaseName(String s) { databaseName=s.trim(); } public String getDatabaseName() { return databaseName; } public void setTableName(String s) { tableName=s.trim(); } public String getTableName() { return tableName; } public void setPassword(String s) { password=s.trim();; } public void setUser(String s) { user=s.trim(); } public String getUser() { return user; } } showByPage.jsp <%@ page contentType="text/html;charset=GB2312" %> <%@ page import="java.sql.*" %> <%@ page import="database.operation.*" %> 数据库 表的记录将被分页显示。
共有 页.
每页最多显示条记录。
当前显示第 页,
单击“前一页”或“下一页”按纽查看记录
输入页码:
例子10 linkOracle.jsp <%@ page contentType="text/html;charset=GB2312" %> <%@ page import="java.sql.*" %> <% Connection con=null; Statement sql=null; ResultSet rs=null; try{ Class.forName("oracle.jdbc.driver.OracleDriver"); } catch(ClassNotFoundException e){} try { con=DriverManager.getConnection("jdbc:oracle:thin:@192.168.0.35:1521:Lea", "scott","tiger"); sql=con.createStatement(); rs=sql.executeQuery("select * from emp"); out.print(""); out.print(""); out.print(""); while(rs.next()) { out.print(""); int n=rs.getInt(1); out.print(""); String e=rs.getString(2); out.print(""); out.print("") ; } out.print("
"+"EMPNO"); out.print(""+"Ename"); out.print("
"+n+""+e+"
"); con.close(); } catch(SQLException e1) {out.print(""+e1); } %> 例子11 linkMySql.jsp <%@ page contentType="text/html;charset=GB2312" %> <%@ page import="java.sql.*" %> <% Connection con; Statement sql; ResultSet rs; try { Class.forName("com.mysql.jdbc.Driver"); } catch(Exception e) { out.print(e); } try { String uri= "jdbc:mysql://localhost/factory"; con=DriverManager.getConnection(uri,"root","123"); sql=con.createStatement(); rs=sql.executeQuery("SELECT * FROM employee"); out.print(""); while(rs.next()) { out.print(""); out.print(""); out.print(""); out.print(""); out.print(""); out.print("") ; } out.print("
"+rs.getString(1)+""+rs.getString(2)+""+rs.getDate(3)+""+rs.getFloat(4)+"
"); con.close(); } catch(SQLException e1) { out.print(e1); } %> 例子12 MySqlBean.java package database.operation; import java.sql.*; public class MySqlBean { String databaseName=""; //数据库名 String tableName=""; //表名 String user="" ; //用户 String secret="" ; //密码 StringBuffer queryResult; //查询结果 public MySqlBean() { queryResult=new StringBuffer(); try{ Class.forName("com.mysql.jdbc.Driver"); } catch(Exception e){} } public void setDatabaseName(String s) { databaseName=s.trim(); queryResult=new StringBuffer(); } public String getDatabaseName() { return databaseName; } public void setTableName(String s) { tableName=s.trim(); queryResult=new StringBuffer(); } public String getTableName() { return tableName; } public void setSecret(String s) { secret=s.trim(); queryResult=new StringBuffer(); } public String getSecret() { return secret; } public void setUser(String s) { user=s.trim(); queryResult=new StringBuffer(); } public String getUser() { return user; } public StringBuffer getQueryResult() { Connection con; Statement sql; ResultSet rs; try { queryResult.append(""); String uri= "jdbc:mysql://localhost/factory"; String user="root"; String password="123"; con=DriverManager.getConnection(uri,user,password); DatabaseMetaData metadata=con.getMetaData(); ResultSet rs1=metadata.getColumns(null,null,tableName,null); int 字段个数=0; queryResult.append(""); while(rs1.next()) { 字段个数++; String clumnName=rs1.getString(4); queryResult.append(""); } queryResult.append(""); sql=con.createStatement(); rs=sql.executeQuery("SELECT * FROM "+tableName); while(rs.next()) { queryResult.append(""); for(int k=1;k<=字段个数;k++) { queryResult.append(""); } queryResult.append(""); } queryResult.append("
"+clumnName+"
"+rs.getString(k)+"
"); con.close(); } catch(SQLException e) { queryResult.append("请输入正确的用户名和密码"); } return queryResult; } } mysql.jsp <%@ page contentType="text/html;charset=GB2312" %> <%@ page import="database.operation.MySqlBean" %>
输入数据库的名字 输入表的名字
输入用户名称(使用默认的root用户访问数据库):
输入密码(如果没有为root设置密码,不必输入):
表查询到记录:
例子13 inquireExcel.jsp <%@ page contentType="text/html;charset=GB2312" %> <%@ page import="java.sql.*" %> <% Connection con; Statement sql; ResultSet rs; try{ Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); } catch(ClassNotFoundException e){} try{ con=DriverManager.getConnection("jdbc:odbc:star","",""); sql=con.createStatement(); sql.executeUpdate("UPDATE message SET 品名='电缆线' WHERE 货号='ED56G'"); rs=sql.executeQuery("SELECT * FROM message"); out.print(""); out.print(""); out.print(""); while(rs.next()) { out.print(""); out.print(""); out.print(""); out.print(""); out.print(""); out.print(""); out.print("") ; } out.print("
"+"货号"); out.print(""+"品名"); out.print(""+"单位"); out.print(""+"单价"); out.print(""+"库存"); out.print("
"+rs.getString(1)+""+rs.getString(2)+""+rs.getString(3)+""+rs.getString(4)+""+rs.getString(5)+"
"); con.close(); } catch(SQLException e1) {} %> 例子14 ApplicationCon.java package database.operation; import java.sql.*; import java.util.LinkedList; public class ApplcationCon { LinkedList list; //存放Connection对象的链表 public ApplcationCon() { try { Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); } catch(Exception e) {} list=new LinkedList(); for(int k=0;k<=10;k++) ////创建10个连接 { try{ String uri= "jdbc:sqlserver://127.0.0.1:1433;DatabaseName=factory"; String id="sa"; String password="sa"; Connection con=DriverManager.getConnection(uri,id,password); list.add(con); } catch(SQLException e){} } } public synchronized Connection getOneConnetion() { if(list.size()>0) return list.removeFirst();//链表删除第一个节点,并返回该节点中的连接对象 else return null; } public synchronized void putBackOneConnetion(Connection con) { list.addFirst(con); } } UseConBean.java package database.operation; import java.sql.*; public class UseConBean { String tableName=""; //表名 StringBuffer queryResult; //查询结果 Connection con; public UseConBean() { queryResult=new StringBuffer(); } public void setTableName(String s) { tableName=s.trim(); queryResult=new StringBuffer(); } public String getTableName() { return tableName; } public void setConnection(Connection con) { this.con=con; } public StringBuffer getQueryResult() { Statement sql; ResultSet rs; try{ queryResult.append(""); DatabaseMetaData metadata=con.getMetaData(); ResultSet rs1=metadata.getColumns(null,null,tableName,null); int 字段个数=0; queryResult.append(""); while(rs1.next()) { 字段个数++; String clumnName=rs1.getString(4); queryResult.append(""); } queryResult.append(""); sql=con.createStatement(); rs=sql.executeQuery("SELECT * FROM "+tableName); while(rs.next()) { queryResult.append(""); for(int k=1;k<=字段个数;k++) { queryResult.append(""); } queryResult.append(""); } queryResult.append("
"+clumnName+"
"+rs.getString(k)+"
"); } catch(SQLException e) { queryResult.append("请输入正确的表名"+e); } return queryResult; } } chaxun.jsp <%@ page contentType="text/html;charset=GB2312" %> <%@ page import="database.operation.*" %> <%@ page import="java.sql.*" %> <% Connection connection=conSet.getOneConnetion(); inquire.setConnection(connection); %> 你连接的数据库是factory
输入表的名字:
表查询到记录:
<% conSet.putBackOneConnetion(connection); %>
例子15 PreparedQueryBean.java package database.operation; import java.sql.*; public class PreparedQueryBean { String databaseName=""; //数据库名称 String tableName=""; //表的名字 String user="" ; //用户 String password="" ; //密码 StringBuffer queryResult; //查询结果 public PreparedQueryBean() { queryResult=new StringBuffer(); try{ Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); } catch(Exception e) { queryResult=new StringBuffer(); queryResult.append(""+e); } } public void setDatabaseName(String s) { queryResult=new StringBuffer(); databaseName=s.trim(); } public String getDatabaseName() { return databaseName; } public void setTableName(String s) { queryResult=new StringBuffer(); tableName=s.trim(); } public String getTableName() { return tableName; } public void setPassword(String s) { password=s.trim();; } public String getPassword() { return password; } public void setUser(String s) { user=s.trim();; } public String getUser() { return user; } public StringBuffer getQueryResult() { Connection con; PreparedStatement sql; ResultSet rs; try { queryResult.append(""); String uri= "jdbc:sqlserver://127.0.0.1:1433;DatabaseName="+databaseName; con=DriverManager.getConnection(uri,user,password); DatabaseMetaData metadata=con.getMetaData(); ResultSet rs1=metadata.getColumns(null,null,tableName,null); int 字段个数=0; queryResult.append(""); while(rs1.next()) { 字段个数++; String clumnName=rs1.getString(4); queryResult.append(""); } queryResult.append(""); sql=con.prepareStatement("SELECT * FROM "+tableName); //预处理语句 rs=sql.executeQuery(); while(rs.next()) { queryResult.append(""); for(int k=1;k<=字段个数;k++) { queryResult.append(""); } queryResult.append(""); } queryResult.append("
"+clumnName+"
"+rs.getString(k)+"
"); con.close(); } catch(SQLException e) { queryResult.append(e); } return queryResult; } } pre.jsp <%@ page contentType="text/html;charset=GB2312" %> <%@ page import=" database.operation.PreparedQueryBean" %>
使用预处理语句查询数据库:
输入数据库的名字: 输入表的名字:
输入用户名: 输入密码:
表查询到记录:
例子16 AddRecordBean.java package database.operation; import java.sql.*; public class AddRecordBean { String number="", //雇员号 name="", //姓名 birthday; //出生日期 float salary; //薪水 boolean ok=false; public AddRecordBean() { try { Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); } catch(ClassNotFoundException e){} } public void setNumber(String s) { number=s.trim(); try{ byte bb[]=number.getBytes("ISO-8859-1"); number=new String(bb,"gb2312"); } catch(Exception e){} } public void setName(String s) { name=s.trim(); try{ byte bb[]=name.getBytes("ISO-8859-1"); name=new String(bb,"gb2312"); } catch(Exception e){} } public void setSalary(float n) { salary=n; } public void setBirthday(String b) { birthday=b; } public boolean getOk() { return ok; } public String getAddMessage() { String str=""; Connection con; PreparedStatement sql; try { String uri="jdbc:sqlserver://127.0.0.1:1433;DatabaseName=factory"; con=DriverManager.getConnection(uri,"sa","sa"); String insertCondition="INSERT INTO employee VALUES (?,?,?,?)"; sql=con.prepareStatement(insertCondition); if(number.length()>0) { sql.setString(1,number); sql.setString(2,name); sql.setString(3,birthday); sql.setFloat(4,salary); int m=sql.executeUpdate(); if(m!=0) { str="对表中添加"+m+"条记录成功"; ok=true; } else { str="添加记录失败"; } } else { str="必须要有雇员号"; } con.close(); } catch(SQLException e) { str="你还没有提供添加的数据或"+e; } return str; } } addRecord.jsp <%@ page contentType="text/html;charset=GB2312"%> <%@ page import="java.sql.*" %> <%@ page import="database.operation.ConditionQuery"%> <%@ page import="database.operation.AddRecordBean"%> 雇员号是主键,不可重复,请输入新记录的相应字段的值:
雇员号 姓名 出生日期(格式必须是****-**-**) 薪水


你添加记录操作的结果:

添加的记录是: <% if(add.getOk()==true) { %> <% } %> 第7章Java Servlet基础 HelloBeijing.java: package star.moon; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class HelloBeijing extends HttpServlet { public void init(ServletConfig config) throws ServletException { super.init(config); } public void service(HttpServletRequest reqest,HttpServletResponse response) throws IOException { response.setContentType("text/html;charset=GB2312");//设置响应的MIME类型 PrintWriter out=response.getWriter();//获得一个向客户发送数据的输出流 out.println(""); out.println("

北京奥运圆满成功!

"); out.println(""); } } web.xml hello star.moon.HelloBeijing hello /lookHello 例子1 giveRadius.jsp <%@ page contentType="text/html;Charset=GB2312" %>

输入圆的半径:
Computer.java package star.moon; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class Computer extends HttpServlet { public void init(ServletConfig config) throws ServletException { super.init(config); } public void service(HttpServletRequest request,HttpServletResponse response) throws IOException { response.setContentType("text/html;charset=GB2312"); PrintWriter out=response.getWriter(); out.println(""); String str=request.getParameter("radius"); //获取客户提交的信息 double r=0; try{ r=Double.parseDouble(str); if(r>=0) { out.print("
半径是 "+r+" 的圆的面积:"); out.print("
"+Math.PI*r*r); } else { out.print("
圆的半径不可以是负数:"+r); } } catch(NumberFormatException e) { out.print("

请输入数字字符!

"); } out.println(""); } } 例子2 showLetter.jsp <%@ page contentType="text/html;Charset=GB2312" %> 单击超链接查看希腊字母表:
查看希腊字母表
ShowLetter.java package star.moon; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class ShowLetter extends HttpServlet { public void init(ServletConfig config) throws ServletException { super.init(config); } public void service(HttpServletRequest request,HttpServletResponse response) throws IOException { response.setContentType("text/html;charset=GB2312"); PrintWriter out=response.getWriter(); out.println(""); out.print("
小写希腊字母: "); for(char c='α';c<='ω';c++) { out.print(" "+c); } out.print("
大写希腊字母: "); for(char c='Α';c<='Ω';c++) { out.print(" "+c); } out.println(""); } } 例子3 showPI.jsp <%@ page contentType="text/html;charset=GB2312" %> 参与计算PI的值 ComputerPI.java package star.moon; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class ComputerPI extends HttpServlet { double sum=0,i=1,j=1; int number=0; public void init(ServletConfig config) throws ServletException {super.init(config); } public synchronized void service(HttpServletRequest request, HttpServletResponse response) throws IOException { response.setContentType("text/html;charset=GB2312"); PrintWriter out=response.getWriter(); out.println(""); number++; sum=sum+i/j; j=j+2; i=-i; out.println("servlet:"+getServletName()+"已经被请求了"+number+"次"); out.println("
现在PI的值是:"); out.println(4*sum); out.println(""); } } 例子4 method.jsp <%@ page contentType="text/html;charset=GB2312" %>

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

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

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

GetSqare.java package star.moon; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class GetSquare extends HttpServlet { public void init(ServletConfig config) throws ServletException {super.init(config); } public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException { response.setContentType("text/html;charset=GB2312"); PrintWriter out=response.getWriter(); out.println(""); String number=request.getParameter("number"); //获取客户提交的信息 double n=0; try{ n=Double.parseDouble(number); out.print("
"+number+"的平方是:"); out.print("
"+n*n); } catch(NumberFormatException e) { out.print("

请输入数字字符!

"); } out.println(""); } public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException { doPost(request,response); } } GetSquareOrCubic.java package star.moon; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class GetSquareOrCubic extends HttpServlet { public void init(ServletConfig config) throws ServletException {super.init(config); } public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException { response.setContentType("text/html;charset=GB2312"); PrintWriter out=response.getWriter(); out.println(""); String number=request.getParameter("number"); //获取客户提交的信息 double n=0; try{ n=Double.parseDouble(number); out.print("
"+number+"的平方是:"); out.print("
"+n*n); } catch(NumberFormatException e) { out.print("

请输入数字字符!

"); } out.println(""); } public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException { response.setContentType("text/html;charset=GB2312"); PrintWriter out=response.getWriter(); out.println(""); String number=request.getParameter("number"); //获取客户提交的信息 double n=0; try{ n=Double.parseDouble(number); out.print("
"+number+"的立方是:"); out.print("
"+n*n*n); } catch(NumberFormatException e) { out.print("

请输入数字字符!

"); } out.println(""); } } 例子5 input.jsp <%@ page contentType="text/html;charset=GB2312" %>
输入姓名:
输入年龄:
Verify.java package star.moon; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class Verify extends HttpServlet { public void init(ServletConfig config) throws ServletException {super.init(config); } public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException { String name=request.getParameter("name"); //获取客户提交的信息 String age=request.getParameter("age"); //获取客户提交的信息 if(name.length()==0||name==null) { response.sendRedirect("input.jsp"); //重定向 } else if(age.length()==0||name==null) { response.sendRedirect("input.jsp"); //重定向 } else if(age.length()>0) { try { int numberAge=Integer.parseInt(age); if(numberAge<=0||numberAge>=150) { response.sendRedirect("input.jsp"); } else { RequestDispatcher dispatcher= request.getRequestDispatcher("forYouShowMessage"); dispatcher.forward(request, response); //转发 } } catch(NumberFormatException e) { response.sendRedirect("input.jsp"); } } } public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException { doPost(request,response); } } ShowMessage.java package star.moon; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class ShowMessage extends HttpServlet { public void init(ServletConfig config) throws ServletException {super.init(config); } public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException { response.setContentType("text/html;charset=GB2312"); PrintWriter out=response.getWriter(); String name=request.getParameter("name"); //获取客户提交的信息 String age=request.getParameter("age"); //获取客户提交的信息 try{ byte bb[]=name.getBytes("ISO-8859-1"); name=new String(bb,"gb2312"); } catch(Exception exp){} out.print("您的姓名是:"); out.print(name); out.print("
您的年龄是:"); out.print(age); } public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException { doPost(request,response); } } 例子6 Boy.java package star.moon; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class Boy extends HttpServlet { public void init(ServletConfig config) throws ServletException {super.init(config); } public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException { response.setContentType("text/html;charset=GB2312"); PrintWriter out=response.getWriter(); out.print(""); HttpSession session=request.getSession(true); //获取客户的会话对象 session.setAttribute("number",new Integer(668)); out.println("您请求的servlet对象是:"+getServletName()+",您的会话的id:"); out.println("
"+session.getId()); out.println("
单击超链接请求另一个servlet:"); out.println("
请求另一个servlet"); out.print(""); } public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException { doPost(request,response); } } Look.java package star.moon; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class Look extends HttpServlet { public void init(ServletConfig config) throws ServletException {super.init(config); } public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException { response.setContentType("text/html;charset=GB2312"); PrintWriter out=response.getWriter(); out.print(""); HttpSession session=request.getSession(true); //获取客户的会话对象 Integer number=(Integer)session.getAttribute("number");//获取会话中存储的数据 int n=number.intValue(); int m=n*n*n; out.println("您请求的servlet对象是:"+getServletName()+",您的会话的id:"); out.println("
"+session.getId()); out.println("
您的会话中存储的整数:"+n); out.println("
"+n+"的立方:"+m); out.print(""); } public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException { doPost(request,response); } } 例子7 getLetter.jsp <%@ page contentType="text/html;charset=GB2312" %> <% session.setAttribute("message","请您猜字母"); char a[]=new char[26]; int m=0; for(char c='a';c<='z';c++) { a[m]=c; m++; } int randomIndex=(int)(Math.random()*a.length); char ch=a[randomIndex]; //获取一个英文字母 session.setAttribute("savedLetter",new Character(ch)); %> 访问或刷新该页面可以随机得到一个英文字母.
单击超链接去猜出这个字母:去猜字母
inputLetter.jsp <%@ page contentType="text/html;charset=GB2312" %> <% String message=(String)session.getAttribute("message"); //获取会话中的信息 %> HandleGuess.java package star.moon; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class HandleGuess extends HttpServlet { public void init(ServletConfig config) throws ServletException {super.init(config); } public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException { HttpSession session=request.getSession(true); //获取客户的会话对象 String str=request.getParameter("clientGuessLetter"); Character guessLetter=str.trim().charAt(0); //获取客户猜测所提交的字母 Character savedLetter=(Character)session.getAttribute("savedLetter"); char realLetter=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"); } } public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException { doPost(request,response); } } 第8章 基于Servlet的MVC模式 web.xml computerSum sun.yourservlet.HandleSum computerSum /lookSum Series.java package moon.yourbean; public class Series { double firstItem; //数列首项 double var; //公差或公比 int number; //求和项数 double sum; //求和结果 String name=""; //数列类别 public void setFirstItem(double a) { firstItem=a; } public double getFirstItem() { return firstItem; } public void setVar(double b) { var=b; } public double getVar() { return var; } public void setNumber(int n) { number=n; } public double getNumber() { return number; } public void setSum(double s) { sum=s; } public double getSum() { return sum; } public void setName(String na) { name=na; } public String getName() { return name; } } inputMess.jsp <%@ page contentType="text/html;Charset=GB2312" %>
等差数列求和:
输入首项: 输入公差: 求和项数:
等比数列求和:
输入首项: 输入公比: 求和项数:
showResult.jsp <%@ page contentType="text/html;charset=GB2312" %> <%@ page import="moon.yourbean.*"%>
输入您的猜测(a~z之间的字母):
提示信息: <%= message%>
单击按钮重新开始:
数列的首项 所求项数 求和结果
HandleSum.java package sun.yourservlet; import moon.yourbean.*; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class HandleSum extends HttpServlet { public void init(ServletConfig config) throws ServletException {super.init(config); } public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException { Series shulie=new Series(); //创建Javabean对象 request.setAttribute("lie",shulie);//将shulie存储到HttpServletRequest对象中 double a=Double.parseDouble(request.getParameter("firstItem")); double d=Double.parseDouble(request.getParameter("var")); int n=Integer.parseInt(request.getParameter("number")); shulie.setFirstItem(a); //将数据存储在shulie中 shulie.setVar(d); shulie.setNumber(n); //计算和: double sum=0,item=a; int i=1; shulie.setName("等差数列的公差"); while(i<=n) //计算等差数列的和 { sum=sum+item; i++; item=item+d; } shulie.setSum(sum); RequestDispatcher dispatcher=request.getRequestDispatcher("showResult.jsp"); dispatcher.forward(request,response); //请求showResult.jsp显示shulie中的数据 } public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException { Series shulie=new Series(); request.setAttribute("lie",shulie); double a=Double.parseDouble(request.getParameter("firstItem")); double d=Double.parseDouble(request.getParameter("var")); int n=Integer.parseInt(request.getParameter("number")); shulie.setFirstItem(a); shulie.setVar(d); shulie.setNumber(n); //计算和: double sum=0,item=a; int i=1; shulie.setName("等比数列的公比"); while(i<=n) //计算等比数列的和 { sum=sum+item; i++; item=item*d; } shulie.setSum(sum); RequestDispatcher dispatcher=request.getRequestDispatcher("showResult.jsp"); dispatcher.forward(request,response); } } 计算一元二次方程的根 Equation.java package moon.yourbean; public class Equation { double a,b,c; String rootOne,rootTwo; boolean squareEquation; public void setA(double a) { this.a=a; } public double getA() { return a; } public void setB(double b) { this.b=b; } public double getB() { return b; } public void setC(double c) { this.c=c; } public double getC() { return c; } public void setRootOne(String root) { rootOne=root; } public String getRootOne() { return rootOne; } public void setRootTwo(String root) { rootTwo=root; } public String getRootTwo() { return rootTwo; } public void setIsSquareEquation(boolean b) { squareEquation=b; } public boolean getIsSquareEquation() { return squareEquation; } } input.jsp <%@ page contentType="text/html;Charset=GB2312" %>

输入一元二次方程的系数:
二次项系数a: 一次项系数b: 常数项c:
show.jsp <%@ page contentType="text/html;charset=GB2312" %> <%@ page import="moon.yourbean.*"%> 一元二次方程的系数是:
二次项系数: 一次项系数: 常数项:
是一元二次方程吗?
方程的两个根是:,
HandleData.java package sun.yourservlet; import moon.yourbean.*; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class HandleData extends HttpServlet { public void init(ServletConfig config) throws ServletException {super.init(config); } public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException { Equation equ=new Equation(); //创建Javabean对象 request.setAttribute("equation",equ);// 将equ存储到HttpServletRequest对象中 double a=Double.parseDouble(request.getParameter("a")); double b=Double.parseDouble(request.getParameter("b")); double c=Double.parseDouble(request.getParameter("c")); equ.setA(a); //将数据存储在equ中 equ.setB(b); equ.setC(c); if(a!=0) equ.setIsSquareEquation(true); else equ.setIsSquareEquation(true); double disk=b*b-4*a*c; if(disk<0) { equ.setRootOne("无实根"); equ.setRootTwo("无实根"); } else { double root1=(-b+Math.sqrt(disk))/(2*a), root2=(-b-Math.sqrt(disk))/(2*a); equ.setRootOne(""+root1); equ.setRootTwo(""+root2); } RequestDispatcher dispatcher=request.getRequestDispatcher("show.jsp"); dispatcher.forward(request,response); //请求show.jsp显示equ中的数据 } public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException { doPost(request,response); } } 简单的计算器 ComputerBean.java package flower.grass; public class ComputerBean { double numberOne,numberTwo,result; String operator="+"; public void setNumberOne(double n) { numberOne=n; } public double getNumberOne() { return numberOne; } public void setNumberTwo(double n) { numberTwo=n; } public double getNumberTwo() { return numberTwo; } public void setOperator(String s) { operator=s.trim();; } public String getOperator() { return operator; } public void setResult(double r) { result=r; } public double getResult() { return result; } } inputNumber.jsp <%@ page contentType="text/html;Charset=GB2312" %>
输入两个数:
选择运算符号:
showResult.jsp <%@ page contentType="text/html;charset=GB2312" %> <%@ page import="moon.yourbean.*" %> 运算结果: =
输入两个数: " size=10>
选择运算符号:
HandleComputer.java package sun.yourservlet; import moon.yourbean.*; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class HandleComputer extends HttpServlet { public void init(ServletConfig config) throws ServletException {super.init(config); } public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException { ComputerBean dataBean=null; HttpSession session=request.getSession(true); try{ dataBean=(ComputerBean)session.getAttribute("ok"); if(dataBean==null) { dataBean=new ComputerBean(); //创建Javabean对象 session.setAttribute("ok",dataBean);//将dataBean存储到session对象中 } } catch(Exception exp) { dataBean=new ComputerBean(); //创建Javabean对象 session.setAttribute("ok",dataBean);// 将dataBean存储到session对象中 } double numberOne=Double.parseDouble(request.getParameter("numberOne")); double numberTwo=Double.parseDouble(request.getParameter("numberTwo")); String operator=request.getParameter("operator"); double result=0; if(operator.equals("+")) { result=numberOne+numberTwo; } else if(operator.equals("-")) { result=numberOne-numberTwo; } else if(operator.equals("*")) { result=numberOne*numberTwo; } else if(operator.equals("/")) { result=numberOne/numberTwo; } dataBean.setNumberOne(numberOne); //将数据存储在dataBean中 dataBean.setNumberTwo(numberTwo); dataBean.setOperator(operator); dataBean.setResult(result); RequestDispatcher dispatcher= request.getRequestDispatcher("showResult.jsp"); dispatcher.forward(request, response);//请求showResult.jsp显示dataBean中的数据 } public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException { doPost(request,response); } } 读取文件 FileMessage.java package moon.yourbean; public class FileMessage { String filePath,fileName,fileContent; long fileLength; public void setFilePath(String str) { filePath=str; } public String getFilePath() { return filePath; } public void setFileName(String str) { fileName=str; } public String getFileName() { return fileName; } public void setFileContent(String str) { fileContent=str; } public String getFileContent() { return fileContent; } public void setFileLength(long len) { fileLength=len; } public long getFileLength() { return fileLength; } } choiceFile.jsp <%@ page contentType="text/html;Charset=GB2312" %> 输入文件的路径(如:d:/1000):
输入文件的名字(如:Hello.java):
showFile.jsp <%@ page contentType="text/html;charset=GB2312" %> <%@ page import="moon.yourbean.*" %> <%@ page contentType="text/html;charset=GB2312" %> <%@ page import="moon.yourbean.FileMessage" %> 文件的位置是 , 文件的名字: , 文件的长度: 字节.
您读取的文件的内容:
HandleFile.java package sun.yourservlet; import moon.yourbean.*; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class HandleFile extends HttpServlet { public void init(ServletConfig config) throws ServletException {super.init(config); } public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException { FileMessage file=new FileMessage(); //创建Javabean对象 request.setAttribute("file",file); String filePath=request.getParameter("filePath"); String fileName=request.getParameter("fileName"); file.setFilePath(filePath); //将数据存储在file中 file.setFileName(fileName); try{ File f=new File(filePath,fileName); long length=f.length(); file.setFileLength(length); FileReader in=new FileReader(f) ; BufferedReader inTwo=new BufferedReader(in); StringBuffer stringbuffer=new StringBuffer(); String s=null; while ((s=inTwo.readLine())!=null) { stringbuffer.append("\n"+s); } String content=new String(stringbuffer); file.setFileContent(content); } catch(IOException exp){} RequestDispatcher dispatcher= request.getRequestDispatcher("showFile.jsp"); dispatcher.forward(request, response);//请求showFile.jsp显示file中的数据 } public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException { doPost(request,response); } } 查询数据库 ShowRecordByPage.java package moon.yourbean; import com.sun.rowset.*; public class ShowRecordByPage { CachedRowSetImpl rowSet=null; //存储表中全部记录的行集对象 int pageSize=10; //每页显示的记录数 int pageAllCount=0; //分页后的总页数 int showPage=1 ; //当前显示页 StringBuffer presentPageResult; //显示当前页内容 String databaseName=""; //数据库名称 String tableName=""; //表的名字 StringBuffer formTitle=null; //表头 public void setRowSet(CachedRowSetImpl set) { rowSet=set; } public CachedRowSetImpl getRowSet() { return rowSet; } public void setPageSize(int size) { pageSize=size; } public int getPageSize() { return pageSize; } public int getPageAllCount() { return pageAllCount; } public void setPageAllCount(int n) { pageAllCount=n; } public void setShowPage(int n) { showPage=n; } public int getShowPage() { return showPage; } public void setPresentPageResult(StringBuffer p) { presentPageResult=p; } public StringBuffer getPresentPageResult() { return presentPageResult; } public void setDatabaseName(String s) { databaseName=s.trim(); } public String getDatabaseName() { return databaseName; } public void setTableName(String s) { tableName=s.trim(); } public String getTableName() { return tableName; } public void setFormTitle(StringBuffer s) { formTitle=s; } public StringBuffer getFormTitle() { return formTitle; } } choiceDatabase.jsp <%@ page contentType="text/html;Charset=GB2312" %>
输入SQlServer 2000所管理的数据库的名字(例如:pubs、factory):

输入相应数据库中表的名字(例如:jobs、employee):

输入每页显示的记录数:
showRecord.jsp <%@ page contentType="text/html;charset=GB2312" %> <%@ page import="moon.yourbean.*" %> 您查询的数据库:, 查询的表:
记录分 页, 每页最多显示 条记录, 目前显示第 页。
HandleDatabase.java package sun.yourservlet; import moon.yourbean.*; import com.sun.rowset.*; import java.sql.*; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class HandleDatabase extends HttpServlet { int 字段个数; CachedRowSetImpl rowSet=null; public void init(ServletConfig config) throws ServletException { super.init(config); try { Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); } catch(Exception e){} } public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException { Connection con; StringBuffer presentPageResult=new StringBuffer(); ShowRecordByPage databaseBean=null; HttpSession session=request.getSession(true); try{ databaseBean=(ShowRecordByPage)session.getAttribute("database"); if(databaseBean==null) { databaseBean=new ShowRecordByPage(); //创建Javabean对象 session.setAttribute("database",databaseBean); } } catch(Exception exp) { databaseBean=new ShowRecordByPage(); session.setAttribute("database",databaseBean); } String databaseName=request.getParameter("databaseName"); String tableName=request.getParameter("tableName"); String ps= request.getParameter("pageSize"); if(ps!=null) { try{ int mm=Integer.parseInt(ps); databaseBean.setPageSize(mm); } catch(NumberFormatException exp) { databaseBean.setPageSize(1); } } int showPage=databaseBean.getShowPage(); int pageSize=databaseBean.getPageSize(); boolean boo=databaseName!=null&&tableName!=null&& databaseName.length()>0&&tableName.length()>0; if(boo) { databaseBean.setDatabaseName(databaseName);//数据存储在databaseBean中 databaseBean.setTableName(tableName); //数据存储在databaseBean中 String uri="jdbc:sqlserver://127.0.0.1:1433;DatabaseName="+databaseName; try{ 字段个数=0; con=DriverManager.getConnection(uri,"sa","sa"); DatabaseMetaData metadata=con.getMetaData(); ResultSet rs1=metadata.getColumns(null,null,tableName,null); int k=0; String 字段[]=new String[100] ; while(rs1.next()) { 字段个数++; 字段[k]=rs1.getString(4); //获取字段的名字 k++; } StringBuffer str=new StringBuffer(); str.append(""); for(int i=0;i<字段个数;i++) { str.append(""); } str.append(""); databaseBean.setFormTitle(str); //数据存储在databaseBean中 Statement sql=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); ResultSet rs=sql.executeQuery("SELECT * FROM "+tableName); rowSet=new CachedRowSetImpl(); //创建行集对象 rowSet.populate(rs); con.close(); //关闭连接 databaseBean.setRowSet(rowSet); //数据存储在databaseBean中 rowSet.last(); int m=rowSet.getRow(); //总行数 int n=pageSize; int pageAllCount=((m%n)==0)?(m/n):(m/n+1); databaseBean.setPageAllCount(pageAllCount);//数据存储在databaseBean中 } catch(SQLException exp){} } String whichPage=request.getParameter("whichPage"); if(whichPage==null||whichPage.length()==0) { showPage=1; databaseBean.setShowPage(showPage); CachedRowSetImpl rowSet=databaseBean.getRowSet(); if(rowSet!=null) { presentPageResult=show(showPage,pageSize,rowSet); databaseBean.setPresentPageResult(presentPageResult); } } else if(whichPage.equals("nextPage")) { showPage++; if(showPage>databaseBean.getPageAllCount()) showPage=1; databaseBean.setShowPage(showPage); CachedRowSetImpl rowSet=databaseBean.getRowSet(); if(rowSet!=null) { presentPageResult=show(showPage,pageSize,rowSet); databaseBean.setPresentPageResult(presentPageResult); } } else if(whichPage.equals("previousPage")) { showPage--; if(showPage<=0) showPage=databaseBean.getPageAllCount(); databaseBean.setShowPage(showPage); CachedRowSetImpl rowSet=databaseBean.getRowSet(); if(rowSet!=null) { presentPageResult=show(showPage,pageSize,rowSet); databaseBean.setPresentPageResult(presentPageResult); } } databaseBean.setPresentPageResult(presentPageResult); RequestDispatcher dispatcher= request.getRequestDispatcher("showRecord.jsp"); dispatcher.forward(request, response); //请求showRecord.jsp显示数据 } public StringBuffer show(int page,int pageSize,CachedRowSetImpl rowSet) { StringBuffer str=new StringBuffer(); try{ rowSet.absolute((page-1)*pageSize+1); for(int i=1;i<=pageSize;i++) { str.append(""); for(int k=1;k<=字段个数;k++) { str.append(""); } str.append(""); rowSet.next(); } } catch(SQLException exp){} return str; } public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException { doPost(request,response); } } 第9章 JSP中使用XML 例子1 Score.xml <成绩> <学号 number="a1001"> <姓名>赵一 <高等数学 课程性质="必修">89 <大学物理 课程性质="必修">88 <摄影艺术 课程性质="选修">良好 <学号 number="a1002"> <姓名>钱二 <高等数学 课程性质="必修">77 <大学物理 课程性质="必修">66 <摄影艺术 课程性质="选修">良好 <学号 number="a1003"> <姓名>孙三 <高等数学 课程性质="必修">75 <大学物理 课程性质="必修">69 <摄影艺术 课程性质="选修">良好 <学号 number="a1004"> <姓名>李四 <高等数学 课程性质="必修">76 <大学物理 课程性质="必修">87 <摄影艺术 课程性质="选修">良好 input.jsp <%@ page contentType="text/html;Charset=GB2312" %> 输入学号,查询成绩: Number.java package sun.yourservlet; import java.io.*; import org.w3c.dom.*; import javax.xml.parsers.*; import javax.servlet.*; import javax.servlet.http.*; public class Number extends HttpServlet { public void init(ServletConfig config) throws ServletException {super.init(config); } public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException { boolean boo=false; response.setContentType("text/html;charset=GB2312"); PrintWriter out=response.getWriter(); out.println(""); String searchedNumber=request.getParameter("studentNmber"); try{ DocumentBuilderFactory factory=DocumentBuilderFactory. newInstance(); DocumentBuilder builder= factory.newDocumentBuilder(); Document document= builder. parse(new File("D:\\1000\\Score.xml")) ; Element root=document.getDocumentElement() ; //获取根节点 //返回根节点的Element子节点,这些子节点对应着XML文件中的“学号"标记: NodeList elemnetNodes=root.getElementsByTagName("学号") ; int size=elemnetNodes.getLength(); for(int k=0;k"+nodeName); String courseType=((Element)child).getAttribute("课程性质"); String contentStr=((Element)child).getTextContent(); if(nodeName.startsWith("姓名")) out.println(":"+contentStr); else out.println("("+courseType+") :"+contentStr); } } } } } if(boo==false) out.println("不存在您要查询的学号!"); } catch(Exception ee) {} out.println(""); } public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException { doPost(request,response); } } 例子2 trainList.xml  <北京西站> <始发列车> <车次> <名字>T83次 <运行区间>北京西-南京 <开车时间>20:17 <终到时间>09:10 <车次> <名字>T199次 <运行区间>北京西-上海 <开车时间>23:25 <终到时间>10:10 <终到列车> <车次> <名字>T84次 <运行区间>南京-北京西 <开车时间>21:17 <终到时间>10:10 <车次> <名字>T200次 <运行区间>上海-北京西 <开车时间>22:25 <终到时间>09:10 <广东站> <始发列车> <车次> <名字>T186次 <运行区间>广东-武汉 <开车时间>22:17 <终到时间>09:24 <车次> <名字>T78次 <运行区间>广东-长沙 <开车时间>18:25 <终到时间>11:10 <终到列车> <车次> <名字>T193次 <运行区间>南京-广东 <开车时间>21:17 <终到时间>10:10 <车次> <名字>T200次 <运行区间>上海-广东 <开车时间>21:15 <终到时间>12:10 train.jsp <%@ page contentType="text/html;charset=GB2312" %> <%@ page import="moon.yourbean.*"%>
选择站名: 选择始发或终到: 始发列车 终到列车
, :
SAXBean.java package moon.yourbean; import javax.xml.parsers.*; import org.xml.sax.helpers.*; import org.xml.sax.*; public class SAXBean { String stationName="北京西站"; //站名 String startOrArrive="" ; //始发或终到 StringBuffer trainMessages=new StringBuffer(); //信息 SAXParserFactory factory=null; SAXParser saxParser=null; //解析器 MyHandler handler; //事件处理器 public void setStationName(String s) { stationName=s.trim(); try{ byte b[]=stationName.getBytes("ISO-8859-1"); stationName=new String(b); } catch(Exception ee){} } public String getStationName() { return stationName; } public void setStartOrArrive(String s) { startOrArrive=s.trim(); try{ byte b[]=startOrArrive.getBytes("ISO-8859-1"); startOrArrive=new String(b); } catch(Exception ee){} } public String getStartOrArrive() { return startOrArrive; } public StringBuffer getTrainMessages() { try{ factory=SAXParserFactory.newInstance() ; saxParser=factory.newSAXParser(); handler=new MyHandler(trainMessages,stationName,startOrArrive); saxParser.parse("D:/1000/trainList.xml",handler); } catch(Exception e){ System.out.println(e);} return trainMessages; } } class MyHandler extends DefaultHandler { StringBuffer trainMessages; String stationName,startOrArrive; boolean 站名标记=false,始发或终到标记=false; MyHandler(StringBuffer mess,String sName,String startOrArr) { trainMessages=mess; stationName=sName; startOrArrive=startOrArr; } public void startDocument() { trainMessages.append("
"+字段[i]+"
"+rowSet.getString(k)+"
"); trainMessages.append(""); trainMessages.append(""); trainMessages.append(""); trainMessages.append(""); trainMessages.append(""); trainMessages.append(""); } public void endDocument() { trainMessages.append("
车次名字运行区间始发时间终到时间
"); } public void startElement(String uri,String localName, String qName,Attributes atts) { qName=qName.trim(); if(qName.equals(stationName)) { 站名标记=true; trainMessages.append(" "+qName); } if(qName.equals(startOrArrive)) { 始发或终到标记=true; } if(qName.endsWith("车次")) { trainMessages.append(""); } } public void endElement(String uri,String localName,String qName) { if(qName.startsWith(stationName)) { 站名标记=false; } if(qName.startsWith(startOrArrive)) { 始发或终到标记=false; } if(qName.endsWith("车次")) { trainMessages.append(""); } } public void characters(char[] ch,int start,int length) { String text=new String(ch,start,length); text=text.trim(); if(站名标记==true&&始发或终到标记==true&&text.length()>0) { String str=text.trim(); trainMessages.append(""+str+""); } } } 例子3 type.jsp <%@ page contentType="text/html;charset=GB2312" %>
显示几个数学公式和化合物分子式:显示 formula.xml   几个数学公式: 平方和公式: (A+B)2= A2+2AB+B2 立方和公式: (A+B)3= A3+3A2B+3B2A2+A3 几个化合物分子式: 水的分子式: H2O 二氧化硫的分子式: SO2 碳酸的分子式: H2CO3 show.css math { 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; } molecular { display:list-item; list-style-type:decimal; margin-left:60; font-size:14pt; color:black; } sup { display:line; font-size:10pt; font-weight:bold; font-style:italic; color:blue; vertical-align:super; } low { display:line; font-size:8pt; font-weight:bold; color:blue; vertical-align:bottom; } 第10章 基于会员制的网络广告系统 head.txt <%@ page contentType="text/html;charset=GB2312" %>

网 络 广 告 系 统

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

欢迎您来这里做广告

web.xml register myservlet.control.HandleRegister register /helpRegister login myservlet.control.HandleLogin login /helpLogin upload myservlet.control.HandleUpload upload /helpUpload lookRecord myservlet.control.HandleDatabase lookRecord /helpShowMember modifyPassword myservlet.control.HandlePassword modifyPassword /helpModifyPassword getOldMess myservlet.control.GetOldMess getOldMess /helpGetOldMess modifyOldMess myservlet.control.HandleModifyMess modifyOldMess /helpModifyMess exit myservlet.control.HandleExit exit /helpExitLogin Register.java package mybean.data; public class Register { String logname="",password="",advertiseTitle="", email="", phone="", message=""; String backNews; public void setLogname(String name) { logname=name; } public String getLogname() { return logname; } public void setAdvertiseTitle(String s) { advertiseTitle=s; } public String getAdvertiseTitle() { return advertiseTitle; } public void setPassword(String pw) { password=pw; } public String getPassword() { return password; } public void setEmail(String em) { email=em; } public String getEmail() { return email; } public void setPhone(String ph) { phone=ph; } public String getPhone() { return phone; } public String getMessage() { return message; } public void setMessage(String m) { message=m; } public String getBackNews() { return backNews; } public void setBackNews(String s) { backNews=s; } } register.jsp <%@ page contentType="text/html;charset=GB2312" %> <%@ include file="head.txt" %>
输入您的信息,会员名字必须由字母和数字组成,带*号项必须填写。
会员名称:*
设置密码:*
广告标题:*
电子邮件:
联系电话:
输入您的广告词:
showRegisterMess.jsp <%@ page contentType="text/html;charset=GB2312" %> <%@ page import="mybean.data.*"%> <%@ include file="head.txt" %>

注册的会员名称:
注册的广告标题:
注册的电子邮件:
注册的联系电话:
您的广告词:
HandleRegister.java package myservlet.control; import mybean.data.*; import java.sql.*; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class HandleRegister extends HttpServlet { public void init(ServletConfig config) throws ServletException { super.init(config); try { Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); } catch(Exception e){} } public String handleString(String s) { try{ byte bb[]=s.getBytes("iso-8859-1"); s=new String(bb); } catch(Exception ee){} return s; } public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException { Connection con; PreparedStatement sql; Register reg=new Register(); request.setAttribute("register",reg); String logname=request.getParameter("logname").trim(), password=request.getParameter("password").trim(), advertiseTitle=request.getParameter("advertiseTitle").trim(), email=request.getParameter("email").trim(), phone=request.getParameter("phone").trim(), message=request.getParameter("message"); String uri="jdbc:sqlserver://127.0.0.1:1433;DatabaseName=Friend"; if(logname==null) logname=""; if(password==null) password=""; boolean isLD=true; for(int i=0;i='a')||(c<='Z'&&c>='A')||(c<='9'&&c>='0'))) isLD=false; } boolean boo=logname.length()>0&&password.length()>0&&isLD; String backNews=""; try{ con=DriverManager.getConnection(uri,"sa","sa"); String insertCondition="INSERT INTO member VALUES (?,?,?,?,?,?,?)"; 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"); int m=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)); } } else { backNews="信息填写不完整或名字中有非法字符"; reg.setBackNews(backNews); } con.close(); } catch(SQLException exp) { backNews="该会员名已被使用,请您更换名字"+exp; reg.setBackNews(backNews); } RequestDispatcher dispatcher= request.getRequestDispatcher("showRegisterMess.jsp");//转发 dispatcher.forward(request, response); } public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException { doPost(request,response); } } Login.java package mybean.data; public class Login { String logname, password, backNews=""; boolean success=false; public void setLogname(String name) { logname=name; } public String getLogname() {return logname; } public void setPassword(String pw) { password=pw; } public String getPassword() {return password; } public String getBackNews() { return backNews; } public void setBackNews(String s) { backNews=s; } public void setSuccess(boolean b) { success=b; } public boolean getSuccess() { return success; } } login.jsp <%@ page contentType="text/html;charset=GB2312" %> <%@ include file="head.txt" %>


请您登录
登录名称:
输入密码:

showLoginMess.jsp <%@ page contentType="text/html;charset=GB2312" %> <%@ page import="mybean.data.Login"%> <%@ include file="head.txt" %>

<% if(login.getSuccess()==true) { %>
登录会员名称: <% } else { %>
登录会员名称:
登录会员密码: <% } %>
HandleLogin.java package myservlet.control; import mybean.data.*; import java.sql.*; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class HandleLogin extends HttpServlet { public void init(ServletConfig config) throws ServletException { super.init(config); try { Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); } catch(Exception e){} } public String handleString(String s) { try{ byte bb[]=s.getBytes("iso-8859-1"); s=new String(bb); } catch(Exception ee){} return s; } public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException { Connection con; PreparedStatement sql; Login loginBean=null; String backNews=""; HttpSession session=request.getSession(true); try{ loginBean=(Login)session.getAttribute("login"); if(loginBean==null) { loginBean=new Login(); session.setAttribute("login",loginBean); } } catch(Exception ee) { loginBean=new Login(); session.setAttribute("login",loginBean); } String logname=request.getParameter("logname").trim(), password=request.getParameter("password").trim(); boolean ok=loginBean.getSuccess(); logname=handleString(logname); password=handleString(password); if(ok==true&&logname.equals(loginBean.getLogname())) { backNews=logname+"已经登录了"; loginBean.setBackNews(backNews); } else { String uri="jdbc:sqlserver://127.0.0.1:1433;DatabaseName=Friend"; boolean boo=(logname.length()>0)&&(password.length()>0); try{ con=DriverManager.getConnection(uri,"sa","sa"); String condition="select * from member where logname =? and password =?"; sql=con.prepareStatement(condition); if(boo) { sql.setString(1,logname); sql.setString(2,password); ResultSet rs=sql.executeQuery(); boolean m=rs.next(); if(m==true) { backNews="登录成功"; loginBean.setBackNews(backNews); loginBean.setSuccess(true); loginBean.setLogname(logname); } else { 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(SQLException exp) { backNews=""+exp; loginBean.setBackNews(backNews); loginBean.setSuccess(false); } } RequestDispatcher dispatcher=request.getRequestDispatcher("showLoginMess.jsp"); dispatcher.forward(request, response); } public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException { doPost(request,response); } } UploadFile.java package mybean.data; public class UploadFile { String fileName,savedFileName, backNews=""; public void setFileName(String name) { fileName=name; } public String getFileName() {return fileName; } public void setSavedFileName(String name) { savedFileName=name; } public String getSavedFileName() {return savedFileName; } public String getBackNews() { return backNews; } public void setBackNews(String s) { backNews=s; } } upload.jsp <%@ page contentType="text/html;charset=GB2312" %> <%@ include file="head.txt" %>

文件将被上传到 D:\apache-tomcat-5.5.20\webapps\ch10\image中。
选择要上传的图像照片文件(名字不可以含有非ASCII码字符,比如汉字等):

showUploadMess.jsp <%@ page contentType="text/html;charset=GB2312" %> <%@ page import="mybean.data.*"%> <%@ include file="head.txt" %>


上传的文件名字: 保存后的文件名字:
width=150 height=120>图像效果
HandleUpload.java package myservlet.control; import mybean.data.*; import java.sql.*; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class HandleUpload extends HttpServlet { public void init(ServletConfig config) throws ServletException { super.init(config); try { Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); } catch(Exception e){} } public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException { HttpSession session=request.getSession(true); Login login=(Login)session.getAttribute("login"); //获取用户登录时的Javabean boolean ok=true; if(login==null) { ok=false; response.sendRedirect("login.jsp"); //重定向到登录页面 } if(ok==true) { String logname=login.getLogname(); uploadFileMethod(request,response,logname); //接受上传文件 } } public void uploadFileMethod(HttpServletRequest request,HttpServletResponse response, String logname) throws ServletException,IOException { UploadFile upFile=new UploadFile(); String backNews=""; try{ HttpSession session=request.getSession(true); request.setAttribute("upFile",upFile); String tempFileName=(String)session.getId(); File f1=new File(tempFileName); FileOutputStream o=new FileOutputStream(f1); InputStream in=request.getInputStream(); byte b[]=new byte[10000]; int n; while( (n=in.read(b))!=-1) { o.write(b,0,n); } o.close(); in.close(); RandomAccessFile random=new RandomAccessFile(f1,"r"); int second=1; //读出f1的第2行,析取出上传文件的名字: String secondLine=null; while(second<=2) { secondLine=random.readLine(); second++; } //获取第2行中目录符号'\'最后出现的位置: int position=secondLine.lastIndexOf('\\'); //截取文件名: String fileName=secondLine.substring(position+1,secondLine.length()-1); byte cc[]=fileName.getBytes("ISO-8859-1"); fileName=new String(cc); fileName=fileName.replaceAll(" ",""); //文件是否由字母或数字组成判断名字 String checkedStr=fileName.substring(0,fileName.indexOf(".")); boolean isLetterOrDigit=true; for(int i=0;i='a')||(c<='Z'&&c>='A')||(c<='9'&&c>='0'))) { isLetterOrDigit=false; break; } } if(isLetterOrDigit==false) { response.sendRedirect("upload.jsp"); //重定向到upload.jsp页面 } //保存文件名是上传文件名加会员名为前缀: String savedFileName=logname.concat(fileName); random.seek(0); long forthEndPosition=0; //获取第4行回车符号的位置 int forth=1; while((n=random.readByte())!=-1&&(forth<=4)) { if(n=='\n') { forthEndPosition=random.getFilePointer(); forth++; } } //根据客户上传文件的名字,将该文件存入磁盘: File dir=new File("D:/apache-tomcat-5.5.20/webapps/ch10/image"); dir.mkdir(); //首先删除用户曾上传过的图像文件: File file[]=dir.listFiles(); for(int k=0;k=0)&&(j<=6)) { mark--; random.seek(mark); n=random.readByte(); if(n=='\n') { endPosition=random.getFilePointer(); j++; } } random.seek(forthEndPosition); long startPoint=random.getFilePointer(); while(startPoint <%@ include file="head.txt" %>

分页显示全体会员
输入要查找的会员名: showAllMember.jsp <%@ page contentType="text/html;charset=GB2312" %> <%@ page import="mybean.data.ShowByPage" %> <%@ include file="head.txt" %>

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

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

单击“前一页”或“下一页”按纽查看信息
输入页码:
showLookedMember.jsp <%@ page contentType="text/html;charset=GB2312" %> <%@ page import="mybean.data.MemberInform" %>
<%@ include file="head.txt" %>
会员名广告标题电话 email广告词广告照片
width=50 height=50>
HandleDatabase.java package myservlet.control; import mybean.data.*; import com.sun.rowset.*; import java.sql.*; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class HandleDatabase extends HttpServlet { CachedRowSetImpl rowSet=null; public void init(ServletConfig config) throws ServletException { super.init(config); try { Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); } catch(Exception e){} } public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException { HttpSession session=request.getSession(true); Login login=(Login)session.getAttribute("login"); //获取用户登录时的Javabean boolean ok=true; if(login==null) { ok=false; response.sendRedirect("login.jsp"); //重定向到登录页面 } if(ok==true) { continueDoPost(request,response); } } public void continueDoPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException { HttpSession session=request.getSession(true); Connection con=null; StringBuffer presentPageResult=new StringBuffer(); ShowByPage showBean=null; try{ showBean=(ShowByPage)session.getAttribute("show"); if(showBean==null) { showBean=new ShowByPage(); //创建Javabean对象 session.setAttribute("show",showBean); } } catch(Exception exp) { showBean=new ShowByPage(); session.setAttribute("show",showBean); } showBean.setPageSize(3); //每页显示3条记录 int showPage=Integer.parseInt(request.getParameter("showPage")); if(showPage>showBean.getPageAllCount()) showPage=1; if(showPage<=0) showPage=showBean.getPageAllCount(); showBean.setShowPage(showPage); int pageSize=showBean.getPageSize(); String uri="jdbc:sqlserver://127.0.0.1:1433;DatabaseName= Friend"; try{ con=DriverManager.getConnection(uri,"sa","sa"); Statement sql=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); ResultSet rs=sql.executeQuery("SELECT * FROM member"); rowSet=new CachedRowSetImpl(); //创建行集对象 rowSet.populate(rs); con.close(); //关闭连接 showBean.setRowSet(rowSet); //数据存储在showBean中 rowSet.last(); int m=rowSet.getRow(); //总行数 int n=pageSize; int pageAllCount=((m%n)==0)?(m/n):(m/n+1); showBean.setPageAllCount(pageAllCount);//数据存储在showBean中 presentPageResult=show(showPage,pageSize,rowSet); showBean.setPresentPageResult(presentPageResult); } catch(SQLException exp){} RequestDispatcher dispatcher= request.getRequestDispatcher("showAllMember.jsp");//转发 dispatcher.forward(request, response); } public StringBuffer show(int page,int pageSize,CachedRowSetImpl rowSet) { StringBuffer str=new StringBuffer(); try{ rowSet.absolute((page-1)*pageSize+1); for(int i=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)+""); String s=""; str.append(""+s+""); str.append(""); rowSet.next(); } } catch(SQLException exp){} return str; } public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException { HttpSession session=request.getSession(true); Login login=(Login)session.getAttribute("login"); //获取用户登录时的Javabean boolean ok=true; if(login==null) { ok=false; response.sendRedirect("login.jsp"); //重定向到登录页面 } if(ok==true) { continueDoGet(request,response); } } public void continueDoGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException { MemberInform inform=new MemberInform(); request.setAttribute("inform",inform); String logname=request.getParameter("logname"); Connection con=null; String uri="jdbc:sqlserver://127.0.0.1:1433;DatabaseName= Friend"; try{ con=DriverManager.getConnection(uri,"sa","sa"); Statement sql=con.createStatement(); ResultSet rs= sql.executeQuery("SELECT * FROM member where logname = '"+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)); inform.setPic(rs.getString(7)); inform.setBackNews("查询到的会员信息:"); } con.close(); RequestDispatcher dispatcher= request.getRequestDispatcher("showLookedMember.jsp");//转发 dispatcher.forward(request, response); } catch(SQLException exp) { inform.setBackNews(""+exp);System.out.println("ok1"+exp); } } } Password.java package mybean.data; public class Password { String oldPassword,newPassword,backNews=""; public void setNewPassword(String pw) { newPassword=pw; } public String getnewPassword() {return newPassword; } public void setOldPassword(String pw) { oldPassword=pw; } public String getOldPassword() {return oldPassword; } public String getBackNews() { return backNews; } public void setBackNews(String s) { backNews=s; } } modifyPassword.jsp <%@ page contentType="text/html;charset=GB2312" %> <%@ include file="head.txt" %>

输入您的密码:


当前密码:
新密码:
showNewPasswor.jsp <%@ page contentType="text/html;charset=GB2312" %> <%@ page import="mybean.data.Password"%> <%@ include file="head.txt" %>

您的新密码:
您的旧密码:
HandlePassword.java package myservlet.control; import mybean.data.*; import java.sql.*; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class HandlePassword extends HttpServlet { public void init(ServletConfig config) throws ServletException { super.init(config); try { Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); } catch(Exception e){} } public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException { HttpSession session=request.getSession(true); Login login=(Login)session.getAttribute("login"); //获取用户登录时的Javabean boolean ok=true; if(login==null) { ok=false; response.sendRedirect("login.jsp"); //重定向到登录页面 } if(ok==true) { continueWork(request,response); } } public void continueWork(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException { HttpSession session=request.getSession(true); Login login=(Login)session.getAttribute("login"); Connection con=null; String logname=login.getLogname(); Password passwordBean=new Password(); request.setAttribute("password",passwordBean); String oldPassword=request.getParameter("oldPassword"); String newPassword=request.getParameter("newPassword"); String uri="jdbc:sqlserver://127.0.0.1:1433;DatabaseName= Friend"; try{ con=DriverManager.getConnection(uri,"sa","sa"); Statement sql=con.createStatement(); ResultSet rs= sql.executeQuery("SELECT * FROM member where logname='"+ logname+"'And password='"+oldPassword+"'"); if(rs.next()) { String updateString="UPDATE member SET password='"+ newPassword+"' where logname='"+logname+"'"; int m=sql.executeUpdate(updateString); if(m==1) { passwordBean.setBackNews("密码更新成功"); passwordBean.setOldPassword(oldPassword); passwordBean.setNewPassword(newPassword); } else { passwordBean.setBackNews("密码更新失败"); } } else { passwordBean.setBackNews("密码更新失败"); } } catch(SQLException exp) { passwordBean.setBackNews("密码更新失败"+exp); } RequestDispatcher dispatcher= request.getRequestDispatcher("showNewPassword.jsp");//转发 dispatcher.forward(request, response); } public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException { doPost(request,response); } } ModifyMessage.java package mybean.data; public class ModifyMessage { String logname="",newAdvertiseTitle="",newEmail="",newPhone="", newMessage="",backNews; public void setLogname(String name) { logname=name; } public String getLogname() { return logname; } public void setNewAdvertiseTitle(String s) { newAdvertiseTitle=s; } public String getNewAdvertiseTitle() { return newAdvertiseTitle; } public void setNewEmail(String em) { newEmail=em; } public String getNewEmail() { return newEmail; } public void setNewPhone(String ph) { newPhone=ph; } public String getNewPhone() { return newPhone; } public String getNewMessage() { return newMessage; } public void setNewMessage(String m) { newMessage=m; } public String getBackNews() { return backNews; } public void setBackNews(String s) { backNews=s; } } choiceModifyMess.jsp <%@ page contentType="text/html;charset=GB2312" %>
<%@ include file="head.txt" %>
inputModifyMess.jsp <%@ page contentType="text/html;charset=GB2312" %> <%@ include file="head.txt" %> <%@ page import="mybean.data.Register"%>

以下是您()曾注册的信息, 您可以修改这些信息。

广告标题: >
联系电话: >
电子邮件:>
广告词:
showModifyMess.jsp <%@ page contentType="text/html;charset=GB2312" %> <%@ page import="mybean.data.ModifyMessage"%> <%@ include file="head.txt" %>

您修改信息如下:
新广告标题:
新电话:
新email:
新广告词:
GetOldMess.java package myservlet.control; import mybean.data.*; import java.sql.*; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class GetOldMess extends HttpServlet { public void init(ServletConfig config) throws ServletException { super.init(config); try { Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); } catch(Exception e){} } public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException { HttpSession session=request.getSession(true); Login login=(Login)session.getAttribute("login");//获取用户登录时的Javabean boolean ok=true; if(login==null) { ok=false; response.sendRedirect("login.jsp"); //重定向到登录页面 } if(ok==true) { continueWork(request,response); } } public void continueWork(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException { HttpSession session=request.getSession(true); Login login=(Login)session.getAttribute("login"); Connection con=null; String logname=login.getLogname(); Register register=new Register(); request.setAttribute("register",register); String uri="jdbc:sqlserver://127.0.0.1:1433;DatabaseName= Friend"; try{ con=DriverManager.getConnection(uri,"sa","sa"); Statement sql=con.createStatement(); ResultSet rs= sql.executeQuery("SELECT * FROM member where logname='"+logname+"'"); if(rs.next()) { 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(SQLException exp) { register.setBackNews(""+exp); } RequestDispatcher dispatcher= request.getRequestDispatcher("inputModifyMess.jsp");//转发 dispatcher.forward(request, response); } public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException { doPost(request,response); } } HandleModifyMess.java package myservlet.control; import mybean.data.*; import java.sql.*; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class HandleModifyMess extends HttpServlet { public void init(ServletConfig config) throws ServletException { super.init(config); try { Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); } catch(Exception e){} } public String handleString(String s) { try{ byte bb[]=s.getBytes("iso-8859-1"); s=new String(bb); } catch(Exception ee){} return s; } public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException { HttpSession session=request.getSession(true); Login login=(Login)session.getAttribute("login");//获取用户登录时的Javabean boolean ok=true; if(login==null) { ok=false; response.sendRedirect("login.jsp"); //重定向到登录页面 } if(ok==true) { continueDoPost(request,response); } } public void continueDoPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException { HttpSession session=request.getSession(true); Login login=(Login)session.getAttribute("login"); String logname=login.getLogname(); Connection con; PreparedStatement sql; ModifyMessage modify=new ModifyMessage(); request.setAttribute("modify",modify); String advertiseTitle=request.getParameter("newAdvertiseTitle").trim(), email=request.getParameter("newEmail").trim(), phone=request.getParameter("newPhone").trim(), message=request.getParameter("newMessage"); String uri="jdbc:sqlserver://127.0.0.1:1433;DatabaseName=Friend"; String backNews=""; try{ con=DriverManager.getConnection(uri,"sa","sa"); String updateCondition= "UPDATE member SET advertiseTitle=?,phone=?,email=?,message=? WHERE logname=?"; sql=con.prepareStatement(updateCondition); sql.setString(1,handleString(advertiseTitle)); sql.setString(2,phone); sql.setString(3,handleString(email)); sql.setString(4,handleString(message)); sql.setString(5,logname); int m=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(SQLException exp) { modify.setBackNews(""+exp); } RequestDispatcher dispatcher= request.getRequestDispatcher("showModifyMess.jsp");//转发 dispatcher.forward(request, response); } public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException { doPost(request,response); } } HandleExit.java package myservlet.control; import mybean.data.*; import java.sql.*; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class HandleExit extends HttpServlet { public void init(ServletConfig config) throws ServletException { super.init(config); } public String handleString(String s) { try{ byte bb[]=s.getBytes("iso-8859-1"); s=new String(bb); } catch(Exception ee){} return s; } public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException { HttpSession session=request.getSession(true); Login login=(Login)session.getAttribute("login"); //获取用户登录时的Javabean boolean ok=true; if(login==null) { ok=false; response.sendRedirect("login.jsp"); //重定向到登录页面 } if(ok==true) { continueDoPost(request,response); } } public void continueDoPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException { HttpSession session=request.getSession(true); session.invalidate(); //销毁用户的session对象 response.sendRedirect("index.jsp"); //返回主页 } public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException { doPost(request,response); } }

下载文档,方便阅读与编辑

文档的实际排版效果,会与网站的显示效果略有不同!!

需要 10 金币 [ 分享文档获得金币 ]
4 人已下载

下载文档

相关文档