1.源程序代码:
DBUtil.java
package Util; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class DBUtil { public static Connection getConnection() { try { //加载驱动 Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance(); System.out.println("驱动加载成功!"); } catch(ClassNotFoundException | InstantiationException | IllegalAccessException e) { System.out.println("驱动加载失败!"); e.printStackTrace(); } String user="sa"; String password="woshizcy0919"; String url="jdbc:sqlserver://127.0.0.1:1433;DatabaseName=Count_DB"; Connection connection=null; try { //创建链接对象connection connection=DriverManager.getConnection(url, user, password); System.out.println("数据库连接成功!"); } catch(SQLException e) { System.out.println("数据库连接失败!"); e.printStackTrace(); } return connection; } //关闭资源的方法 public static void close(Connection connection) { if(connection!=null) { try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } } } public static void close(PreparedStatement preparedStatement) { if(preparedStatement !=null) { try { preparedStatement.close(); } catch (SQLException e) { e.printStackTrace(); } } } public static void close(ResultSet resultSet) { if(resultSet!=null) { try { resultSet.close(); } catch (SQLException e) { e.printStackTrace(); } } } }
CountModel.java
package model; public class CountModel { private int id; private int count1; private int count2; private int count3; private int result; private String sign1; private String sign2; public int getId() { return id; } public void setId(int id) { this.id = id; } public int getCount1() { return count1; } public void setCount1(int count1) { this.count1 = count1; } public int getCount2() { return count2; } public void setCount2(int count2) { this.count2 = count2; } public int getCount3() { return count3; } public void setCount3(int count3) { this.count3 = count3; } public String getSign1() { return sign1; } public void setSign1(String sign1) { this.sign1 = sign1; } public String getSign2() { return sign2; } public void setSign2(String sign2) { this.sign2 = sign2; } public int getResult() { return result; } public void setResult(int result) { this.result = result; } }
ZhiXing.java
package Main; import dao.CountModelDaoImpl; public class ZhiXing { public static void main(String[] args) { CountModelDaoImpl a=new CountModelDaoImpl(); a.chuTi1(60); a.chuTi2(60); } }
ICountModelDao.java
package dao; import java.util.List; import model.CountModel; public interface ICountModelDao { public void chuTi1(int tishu); public void chuTi2(int tishu); public List<CountModel> load1(int k); public List<CountModel> load2(int k); }
CountModelDaoImpl.java
package dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import Util.DBUtil; import model.CountModel; public class CountModelDaoImpl implements ICountModelDao { public void chuTi1(int tishu) { //获得连接的对象 Connection connection=DBUtil.getConnection(); //创建语句传输对象 PreparedStatement preparedStatement=null; try { CountModel countModel=new CountModel(); int count1 = 0; int count2 = 0; int result = 0; String sign1 = null; for(int i=1;i<=tishu;i++) { int c=(int)(Math. random()*4); switch(c) { case 0: { count1=(int)(Math.random()*50)+1; count2=(int)(Math.random()*30)+1; sign1="+"; result=count1+count2; break; } case 1: { count1=(int)(Math.random()*70); count2=(int)(Math.random()*40)+1; if(count1>=count2) { sign1="-"; result=count1-count2; break; } else { i--; continue; } } case 2: { count1=(int)(Math.random()*9)+1; count2=(int)(Math.random()*10); sign1="*"; result=count1*count2; break; } case 3: { count1=(int)(Math.random()*82); count2=(int)(Math.random()*9)+1; if((count1>=count2)&&(count1%count2==0)) { sign1="/"; result=count1/count2; break; } else { i--; continue; } } } //准备sql语句 String sql="insert into t1_count(count1,count2,sign1,result) values(?,?,?,?)"; preparedStatement=connection.prepareStatement(sql); preparedStatement.setInt(1,count1); preparedStatement.setInt(2,count2); preparedStatement.setString(3,sign1); preparedStatement.setInt(4,result); preparedStatement.executeUpdate(); } } catch (SQLException e) { e.printStackTrace(); } finally { //关闭JDBC对象 DBUtil.close(preparedStatement); DBUtil.close(connection); } } public void chuTi2(int tishu) { //获得连接的对象 Connection connection=DBUtil.getConnection(); //创建语句传输对象 PreparedStatement preparedStatement=null; try { CountModel countModel=new CountModel(); int count1 = 0; int count2 = 0; int count3 = 0; String sign1 = null; String sign2 = null; int result = 0; for(int i=1;i<=tishu;i++) { int c=(int)(Math. random()*2); switch(c) { case 0: { count1=(int)(Math.random()*50)+1; count2=(int)(Math.random()*20)+1; count3=(int)(Math.random()*30)+1; sign1="+"; sign2="+"; result=count1+count2+count3; break; } case 1: { count1=(int)(Math.random()*70); count2=(int)(Math.random()*30); count3=(int)(Math.random()*30); if(count1>=(count2+count3)) { sign1="-"; sign2="-"; result=count1-count2-count3; break; } else { i--; continue; } } } //准备sql语句 String sql="insert into t2_count(count1,count2,count3,sign1,sign2,result) values(?,?,?,?,?,?)"; preparedStatement=connection.prepareStatement(sql); preparedStatement.setInt(1,count1); preparedStatement.setInt(2,count2); preparedStatement.setInt(3,count3); preparedStatement.setString(4,sign1); preparedStatement.setString(5,sign2); preparedStatement.setInt(6,result); preparedStatement.executeUpdate(); } } catch (SQLException e) { e.printStackTrace(); } finally { //关闭JDBC对象 DBUtil.close(preparedStatement); DBUtil.close(connection); } } @Override public List<CountModel> load1(int k) { int a=(int)(Math.random()*100)+1; int b=a+k-1; Connection connection=DBUtil.getConnection(); String sql="select * from t1_count where id between "+a+" and "+b; PreparedStatement preparedStatement=null; ResultSet resultSet=null; List<CountModel> countModels=new ArrayList<CountModel>(); CountModel countModel=null; try { preparedStatement=connection.prepareStatement(sql); resultSet=preparedStatement.executeQuery(); while(resultSet.next()) { countModel=new CountModel(); countModel.setId(resultSet.getInt("id")); countModel.setCount1(resultSet.getInt("count1")); countModel.setCount2(resultSet.getInt("count2")); countModel.setSign1(resultSet.getString("sign1")); countModel.setResult(resultSet.getInt("result")); countModels.add(countModel); } } catch (SQLException e) { e.printStackTrace(); } finally { DBUtil.close(resultSet); DBUtil.close(preparedStatement); DBUtil.close(connection); } return countModels; } @Override public List<CountModel> load2(int k) { int a=(int)(Math.random()*100)+1; int b=a+k-1; Connection connection=DBUtil.getConnection(); String sql="select * from t2_count where id between "+a+" and "+b; PreparedStatement preparedStatement=null; ResultSet resultSet=null; List<CountModel> countModels=new ArrayList<CountModel>(); CountModel countModel=null; try { preparedStatement=connection.prepareStatement(sql); resultSet=preparedStatement.executeQuery(); while(resultSet.next()) { countModel=new CountModel(); countModel.setId(resultSet.getInt("id")); countModel.setCount1(resultSet.getInt("count1")); countModel.setCount2(resultSet.getInt("count2")); countModel.setCount3(resultSet.getInt("count3")); countModel.setSign1(resultSet.getString("sign1")); countModel.setSign2(resultSet.getString("sign2")); countModel.setResult(resultSet.getInt("result")); countModels.add(countModel); } } catch (SQLException e) { e.printStackTrace(); } finally { DBUtil.close(resultSet); DBUtil.close(preparedStatement); DBUtil.close(connection); } return countModels; } }
Servlet.java
package servlet; import java.io.IOException; import java.util.Date; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import dao.CountModelDaoImpl; import model.CountModel; public class Servlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request,response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //由于servlet默认的编码方式是ISO-8859-1,不支持中文,会导致中文乱码。 //所以当有中文参数提交给Servlet或由Servlet输出中文到页面时,需要在处理前将其编码方式设置为兼容中文方式,即 //方法request.setCharacterEncoding("gbk")或response.setCharacterEncoding("gb2312")。 //jsp页面page指令的pageEncoding属性的设置无法影响处理它的Servlet的编码。 //把传递过来的中文参数的编码方式改为UTF-8,兼容中文,servlet默认把传递过来的参数都按ISO-8859-1,不支持中文,会导致中文乱码。 request.setCharacterEncoding("UTF-8"); //这次必须用服务器内部跳转,如果用重定向的方法上一个request请求就结束了,接收request的是null, //也就是上一个request在url地址改变之后生命周期结束,所以不能用重定向的跳转方式,应该用服务区内部跳转。 //request.setAttribute("tishu",request.getParameter("tishu")); //考虑到tishu在跳转到jsp之后还要再次跳转,因此使用session HttpSession session=request.getSession(); session.setAttribute("tishu", request.getParameter("tishu")); if(request.getParameter("yuanshu").equals("二元运算")) { //!错误的请求重定向方式示例: /*请求重定向方式跳转到ChuTiList1.jsp,这是采用的相对路径查找, 相对路径方法查找是在当前路径下查找,而当前路径为:Count_Message/servlet/, 而ChuTiList1.jsp是在项目的根目录下所以肯定找不到 */ //response.sendRedirect("ChuTiList1.jsp"); <---错误示例 //1.请求重定向方式:请求重定向方式跳转到ChuTiList1.jsp,这是采用绝对路径查找, //request.getContextPath()表示项目的根目录,绝对路径需要加上上下文目录。 response.sendRedirect(request.getContextPath()+"/ChuTiList1.jsp"); //2.服务器内部跳转,直接在当前目录下访问那个ChuTiList2.jsp的完整目录,地址不改变,实际没有跳转,在当前目录下对目标目录只是简单的访问。 //服务器内部跳转方法下边路径的第一个斜杠表示的是项目的根目录,不加/还是查找相对路径,和上边的示例错误一样,可以用 //../ChuTiList1.jsp,这样就是先返回上一层目录,即根目录,不跳转,然后访问。 //request.getRequestDispatcher("/ChuTiList1.jsp").forward(request, response); } else { //1.请求重定向方式:跳转到ChuTiList2.jsp,request.getContextPath()表示项目的根目录,需要加上上下文目录。 response.sendRedirect(request.getContextPath()+"/ChuTiList2.jsp"); //2.服务器内部跳转,直接在当前目录下访问那个ChuTiList2.jsp的完整目录,地址不改变,实际没有跳转,在当前目录下对目标目录只是简单的访问。 //request.getRequestDispatcher("/ChuTiList2.jsp").forward(request, response); } } }
ChuTiList1.jsp
<%@page import="model.CountModel"%> <%@page import="java.util.List"%> <%@page import="dao.CountModelDaoImpl"%> <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <!-- 插入图片铺满屏幕的方法 --> <style type="text/css"> body{ background-image: url(C:\javaee-eclipse-workspace\Count_Message\images\1.png); background-size:cover; } </style> <!-- 计时的方法 --> <script type="text/javascript"> var maxtime = 3 * 60; function CountDowm() { if (maxtime >= 0) { minutes = Math.floor(maxtime / 60); seconds = Math.floor(maxtime % 60); if (seconds >= 10) msg = "距离系统自动交卷还有:" + minutes + ":" + seconds; else msg = "距离系统自动交卷还有:" + minutes + ":0" + seconds; document.all["timer"].innerHTML = msg; --maxtime; } else { document.forms("form1").submit(); } } timer = setInterval("CountDowm()", 1000);//每隔1秒调用一次方法 </script> <title>答题界面</title> </head> <% //注意!!!request.getAttribute()方法接收到的是一个对象,不能直接强制转化为int类型, //应该先用对象的toString()方法转化为字符串类型,再用Integer.parseInt()方法转化为int类型 //而request.getParameter()接收的是数据,但是request.getParameter()没有set方法 int tishu=Integer.parseInt(session.getAttribute("tishu").toString());//把传递过来的对象转化为int类型 CountModelDaoImpl countModelDaoImpl=new CountModelDaoImpl(); List<CountModel> countModels=countModelDaoImpl.load1(tishu); session.setAttribute("countModels",countModels); %> <body> <form name="form1" method="post" action="CheckAnswer1.jsp"> <H3 align="center">小学二年级数学口算测试题</H3> <hr> <div id="timer"></div> <table align="center" border="1" width="300"> <tr><th>题号</th><th colspan="2">题目</th><th>计算结果</th></tr> <% int i=0; for( CountModel countModel : countModels ){ %> <tr> <td> <%=(i+1)%></td> <td colspan="2"> <%=countModel.getCount1() %> <%=countModel.getSign1() %> <%=countModel.getCount2() %> = </td> <td><input type="text" name="answer" size="5"></td> </tr> <% i++; } %> </table> <p></p> <p style=" margin:0 auto; text-align:center;"><input align="center" type="submit" value="提交答案"></p> </form> </body> </html>
CheckAnswer1.jsp
<%@page import="model.CountModel"%> <%@page import="java.util.List"%> <%@page import="dao.CountModelDaoImpl"%> <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <!-- 插入图片铺满屏幕的方法 --> <style type="text/css"> body{ background-image: url(C:\javaee-eclipse-workspace\Count_Message\images\1.png); background-size:cover; } </style> <title>测试结果</title> </head> <% //CountModelDaoImpl countModelDaoImpl=new CountModelDaoImpl(); //int tishu=Integer.parseInt(session.getAttribute("tishu").toString()); List<CountModel> countModels=(List<CountModel>)session.getAttribute("countModels"); String[] answers=request.getParameterValues("answer"); %> <body> <form method="post" action="ChuTiList1.jsp"> <H3 align="center">小学二年级数学口算练习题</H3> <hr> <table align="center" border="1" width="400"> <tr><th>题号</th><th colspan="2">题目</th><th>计算结果</th><th>正误</th><th>正确答案</th></tr> <% int i=0; int a=0; int b=0; int c=0; double s; for( CountModel countModel : countModels ) { %> <tr> <td> <%=(i+1)%></td> <td colspan="2"> <%=countModel.getCount1() %> <%=countModel.getSign1() %> <%=countModel.getCount2() %> = </td> <td> <%=answers[i]%> </td> <td> <% if(answers[i]=="") { a++; %> <font color="gray">未答</font> <% } else if(countModel.getResult()==Integer.parseInt(answers[i])) { b++; %> <font color="blue">正确</font> <% } else { c++; %> <font color="red">错误</font> <% } %> </td> <td><%=countModel.getResult()%></td> </tr> <% i++; } s=100.0/i*b; String str=String.format("%.1f", s); %> </table> <p></p> <hr> <table align="right" border="1" width="150"> <tr><th colspan="2"><font color="red">测试结果</font></th></tr> <tr><th>题数</th><th><%=i %></th><tr> <tr><th>正确</th><th><%=b %></th><tr> <tr><th>错误</th><th><%=c %></th><tr> <tr><th>未答</th><th><%=a %></th><tr> <tr><th><font color="red">测试成绩</font></th><th><font color="red"><%=str %></font></th><tr> </table> <p></p> <div align="center"><p><input type="submit" value="再测一次"></p></div> </form> </body> </html>
ChuTiList2.jsp
<%@page import="model.CountModel"%> <%@page import="java.util.List"%> <%@page import="dao.CountModelDaoImpl"%> <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <!-- 插入图片铺满屏幕的方法 --> <style type="text/css"> body{ background-image: url(C:\javaee-eclipse-workspace\Count_Message\images\1.png); background-size:cover; } </style> <!-- 计时的方法 --> <script type="text/javascript"> var maxtime = 3 * 60; function CountDowm() { if (maxtime >= 0) { minutes = Math.floor(maxtime / 60); seconds = Math.floor(maxtime % 60); if (seconds >= 10) msg = "距离系统自动交卷还有:" + minutes + ":" + seconds; else msg = "距离系统自动交卷还有:" + minutes + ":0" + seconds; document.all["timer"].innerHTML = msg; --maxtime; } else { document.forms("form2").submit(); } } timer = setInterval("CountDowm()", 1000);//每隔1秒调用一次方法 </script> <title>答题界面</title> </head> <% //注意!!!request.getAttribute()方法接收到的是一个对象,不能直接强制转化为int类型, //应该先用对象的toString()方法转化为字符串类型,再用Integer.parseInt()方法转化为int类型 //而request.getParameter()接收的是数据,但是request.getParameter()没有set方法 int tishu=Integer.parseInt(session.getAttribute("tishu").toString());//把传递过来的对象转化为int类型 CountModelDaoImpl countModelDaoImpl=new CountModelDaoImpl(); List<CountModel> countModels=countModelDaoImpl.load2(tishu); session.setAttribute("countModels", countModels); %> <body> <form name="form2" method="post" action="CheckAnswer2.jsp"> <H3 align="center">小学二年级数学口算测试题</H3> <hr> <div id="timer"></div> <table align="center" border="1" width="300"> <tr><th>题号</th><th colspan="2">题目</th><th>计算结果</th></tr> <% int i=0; for( CountModel countModel : countModels ) { %> <tr> <td> <%=(i+1)%></td> <td colspan="2"> <%=countModel.getCount1() %> <%=countModel.getSign1() %> <%=countModel.getCount2() %> <%=countModel.getSign2() %> <%=countModel.getCount3() %> = </td> <td><input type="text" name="answer" size="5"></td> </tr> <% i++; } %> </table> <p></p> <p style=" margin:0 auto; text-align:center;"><input align="center" type="submit" value="提交答案"></p> </form> </body> </html>
CheckAnswer2.jsp
<%@page import="model.CountModel"%> <%@page import="java.util.List"%> <%@page import="dao.CountModelDaoImpl"%> <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <!-- 插入图片铺满屏幕的方法 --> <style type="text/css"> body{ background-image: url(C:\javaee-eclipse-workspace\Count_Message\images\1.png); background-size:cover; } </style> <title>测试结果</title> </head> <% List<CountModel> countModels=(List<CountModel>)session.getAttribute("countModels"); String[] answers=request.getParameterValues("answer"); %> <body> <form method="post" action="ChuTiList2.jsp"> <H3 align="center">小学二年级数学口算练习题</H3> <hr> <table align="center" border="1" width="400"> <tr><th>题号</th><th colspan="2">题目</th><th>计算结果</th><th>正误</th><th>正确答案</th></tr> <% int i=0; int a=0; int b=0; int c=0; double s; for( CountModel countModel : countModels ){ %> <tr> <td> <%=(i+1)%></td> <td colspan="2"> <%=countModel.getCount1() %> <%=countModel.getSign1() %> <%=countModel.getCount2() %> <%=countModel.getSign2() %> <%=countModel.getCount3() %> = </td> <td> <%=answers[i]%> </td> <td> <% if(answers[i]=="") { a++; %> <font color="gray">未答</font> <% } else if(countModel.getResult()==Integer.parseInt(answers[i])) { b++; %> <font color="blue">正确</font> <% } else { c++; %> <font color="red">错误</font> <% } %> </td> <td><%=countModel.getResult()%></td> </tr> <% i++; } s=100.0/i*b; String str=String.format("%.1f", s); %> </table> <p></p> <hr> <table align="right" border="1" width="150"> <tr><th colspan="2"><font color="red">测试结果</font></th></tr> <tr><th>题数</th><th><%=i %></th><tr> <tr><th>正确</th><th><%=b %></th><tr> <tr><th>错误</th><th><%=c %></th><tr> <tr><th>未答</th><th><%=a %></th><tr> <tr><th><font color="red">测试成绩</font></th><th><font color="red"><%=str %></font></th><tr> </table> <p></p> <div align="center"><p><input type="submit" value="再测一次"></p></div> </form> </body> </html>
2.运行结果截图:
3.总结分析:
(1)保留double类型数值的小数位数:如double x; 可以用String.format("%.2f", x); 保留两位小数。
(2)request和session的生命周期:request是请求,在一次请求和回复中有效;session是会话,从你登陆到你登出整个过程有效。
(3)关于路径跳转问题的总结在本篇Servlet.java代码的注释中。
(4)request.getAttribute()方法得到的是object类型的变量,如果转化为int类型,需要先调用.toString方法转化为字符串类型,再调用Integer.parseInt()方法将String类型转换为int类型。
(5)request/session.getAttribute得到的是object类型的变量,如果传递的是对象数组,可以直接强制类型转化。
4.未解决问题:
ChuTiList1.jsp
List<CountModel> countModels=countModelDaoImpl.load1(tishu);
request.setAttribute("countModels",countModels);
CheckAnswer1.jsp
List<CountModel> countModels=(List<CountModel>)request.getAttribute("countModels");
上述代码是修改之前的,是错误的,对象数组并没有传递过去,用的是request的setAttribute和getAttribute方法,从一个jsp页面出发,到另外一个jsp页面接收的request请求为空?一次请求回复应该是可以的,但不知道为什么就是接收不到,后来改用session的setAttribute和getAttribute方法就可以执行了,按生命周期来说也这种现象也不合理,虽然session的生命周期长,但是在一次请求和接收中始终在request的生命周期里不应该为空啊…这个问题在网上也没有找到合理的解释,现在刚开始接触servlet和jsp,这个疑问留待深入学习之后再探索...
5.备注:
有两部分代码是引用的(暂时没学JavaScript和CSS),一部分是用JavaScript写的倒计时代码,还有一部分是用CSS写的插入图片平铺代码。