博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
软件工程结对作业01
阅读量:6706 次
发布时间:2019-06-25

本文共 85422 字,大约阅读时间需要 284 分钟。

 

设计思想:

 主要功能:

生成试题:在HTML页面输入题目选项(有无括号,数值范围,题目个数等属性)点击提交按钮使用jQuery的响应按钮的点击事件发送ajax post请求,将题目选项参数传到servletservlet获取参数值,调用生成试题的方法生成指定选项的试题,并将试题信息存入到session中已备判断用户的答案的正确性,将试题信息返回,在ajax成功接收到试题信息之后将试题信息显示在页面上。并将输入题目选项的块隐藏,将显示试题的块显示。

判断结果:点击交卷按钮后,jQuery响应按钮点击事件,将利用ajax将答案信息传入到servletservlet获取答案,并从session中获取题目信息,将用户的答案与正确答案进行比较,并调用操作数据库的方法将试题信息存储到数据库,将结果传回,ajax收到传回的数据后将结果显示在页面上。

 

编程总结和体会:

1)程序的设计非常重要,在具体编码之前要把程序有什么功能怎么写设计好,有了一个清晰的设计思路,才能高效正确地写出代码。

2)要将整体的框架分清楚,合理地进行封装,可以方便地进行改动。

 

 运行结果截图:

输入做题选项界面:

 

 

答题界面:

 

判断结果界面:

 

查询历史试题界面:

 

查询结果页面:

 

 

 

 

 

 

PSP表格

实现程序之前估计各个模块所耗费时间

 

 

实现程序之后各个模块实际花费的时间

 

 

源程序代码:

 

package beans;import java.util.Stack;import func.FenShu;import func.MyException;public class ShiTi {    private int id,userScore, length,shiJuanID;    private String tiMu, rightAnswer, userAnswer, username,logicOrder;                public int getId() {        return id;    }    public void setId(int id) {        this.id = id;    }    public int getShiJuanID() {        return shiJuanID;    }    public void setShiJuanID(int shiJuanID) {        this.shiJuanID = shiJuanID;    }    public int getUserScore() {        return userScore;    }    public void setUserScore(int userScore) {        this.userScore = userScore;    }    public int getLength() {        return length;    }    public void setLength(int length) {        this.length = length;    }                    public String getTiMu() {        return tiMu;    }    public void setTiMu(String tiMu) {        this.tiMu = tiMu;        try {            expressCalculate();        } catch (MyException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }// 计算答案        this.length = (tiMu.split(" ").length + 1) / 2;    }    public String getRightAnswer() {        return rightAnswer;    }    public void setRightAnswer(String rightAnswer) {        this.rightAnswer = rightAnswer;    }    public String getUserAnswer() {        return userAnswer;    }    public void setUserAnswer(String userAnswer) {        this.userAnswer = userAnswer;    }            public String getUsername() {        return username;    }    public void setUsername(String username) {        this.username = username;    }    public String getLogicOrder() {        return logicOrder;    }    public void setLogicOrder(String logicOrder) {        this.logicOrder = logicOrder;    }    public ShiTi() {    }                                                    // 表达式计算,参数为字符串类型的运算式    private void expressCalculate() throws MyException {        if(this.tiMu == null)        {            throw new MyException("试题无效");        }        String express = this.tiMu;                        Stack
num = new Stack
(); Stack
symbolS = new Stack
(); symbolS.push("#"); express += "#"; String order = ""; char ch; int i = 0; ch = express.charAt(i); while ((!symbolS.peek().equals("#")) || (ch != '#')) {
// while循环开始 if (isNumber(ch)) {
// 读到的不是空格,说明开始读运算数 String readNumStr = ""; while (true) { readNumStr += ch; ch = express.charAt(++i); if (ch == ' ' || ch == '#' || ch == ')') {
// 读到的是空格,或,说明运算数结束 break; } } num.push(readNumStr); } else if (ch == ' ') { if ((i + 1) < express.length()) {
// 未到字符串末尾 ch = express.charAt(++i); } }else {
// 读到的是运算符 char compare = priorityCompare(symbolS.peek(), ch + ""); if (compare == '=') {
// 若优先级相等,则说明ch是右括号,栈顶为左括号,此时将栈顶弹出,读取下一个字符 symbolS.pop(); ch = express.charAt(++i); } else if (compare == '>') {
// ch的优先级小于栈顶的优先级,要说明栈顶的运算符应该先计算,所以应弹栈运算 // 弹出两个运算数,弹出一个运算符 String bStr = num.pop(); String aStr = num.pop(); String symbolT = symbolS.pop(); // 计算该字表达式 String c = yunSuan(aStr, bStr, symbolT); if (c.equals("ERROR")) {
// 如果计算函数返回error则说明计算过程出现了负数,说明该运算式不符合要求,停止计算,计算结果为error,返回; this.rightAnswer = "ERROR"; return; } else {
// 计算过程正常,则将计算结果压栈 order += aStr + "," + symbolT + "," + bStr + ",";// 将运算的子表达式加进运算顺序字符串中,操作数和操作符用逗号隔开 num.push(c); } } else if(compare == 'E') { this.rightAnswer = "ERROR"; return; } else {
// 说明ch优先级大于栈顶元素的优先级,则应将ch压栈,读取下一个运算符 symbolS.push(ch + ""); if ((i + 1) < express.length()) { ch = express.charAt(++i); } } } } this.rightAnswer = num.pop(); this.logicOrder = order; } // 判断ch是否为数字 private boolean isNumber(char ch) { if (ch >= '0' && ch <= '9') { return true; } return false; } /* * 子表达式计算,参数为两个运算数的字符串形式,和一个运算符,也为字符串类型 返回计算结果的字符串形式 * 如果减法运算出现负数,或除数为0,或分数的分母为0则返回ERROR * */ private String yunSuan(String aStr, String bStr, String symbol) throws MyException { if(aStr == null || bStr == null || symbol == null) { throw new MyException("子表达式出现错误!"); } int adivIndex = aStr.indexOf("/"); int bdivIndex = bStr.indexOf("/"); if ((adivIndex == -1) && (bdivIndex == -1)) {
// a.b都是整数 int a = Integer.parseInt(aStr); int b = Integer.parseInt(bStr); switch (symbol.charAt(0)) { case '+': return a + b + ""; case '-': { if (a < b) { return "ERROR"; } return a - b + ""; } case '*': { return a * b + ""; } case '/': { if (b == 0) { return "ERROR"; } else if (a % b == 0) { return a / b + ""; } return new FenShu(a, b).toString(); } default: return "ERROR"; } } else {
// a,b中存在分数,则将a,b都当做分数进行运算 FenShu a = new FenShu(aStr); FenShu b = new FenShu(bStr); switch (symbol.charAt(0)) { case '+': return a.add(b).toString(); case '-': { FenShu c = a.subtract(b); if(c.getNumerator() < 0) { return "ERROR"; } return c.toString(); } case '*': return a.multiply(b).toString(); case '/': return a.divide(b).toString(); default: return "ERROR"; } } } // 判断运算符优先级 private char priorityCompare(String a, String b) { char[][] priority = { { '>', '>', '<', '<', '<', '>', '>' }, { '>', '>', '<', '<', '<', '>', '>' }, { '>', '>', '>', '>', '<', '>', '>' }, { '>', '>', '>', '>', '<', '>', '>' }, { '<', '<', '<', '<', '<', '=', '>' }, { '>', '>', '>', '>', ' ', '>', '>' }, { '<', '<', '<', '<', '<', ' ', '=' } }; int a_index = index_symbol(a); int b_index = index_symbol(b); if(a_index == -1 || b_index == -1) { return 'E'; } return priority[a_index][b_index]; } // 获取运算符对应的下标 private int index_symbol(String a) { String p = "+-*/()#"; // System.out.println("判断运算符对应的下标:" + a); return p.indexOf(a); } }
ShiTi.java

 

package beans;import java.util.Date;public class ShiJuan {    private int id,shiTiNum, grade,shiJuanID;    private String username;        private Date date;                public int getShiJuanID() {        return shiJuanID;    }    public void setShiJuanID(int shiJuanID) {        this.shiJuanID = shiJuanID;    }    public int getId() {        return id;    }    public void setId(int id) {        this.id = id;    }    public int getShiTiNum() {        return shiTiNum;    }    public void setShiTiNum(int shiTiNum) {        this.shiTiNum = shiTiNum;    }    public int getGrade() {        return grade;    }    public void setGrade(int grade) {        this.grade = grade;    }            public String getUsername() {        return username;    }    public void setUsername(String username) {        this.username = username;    }    public Date getDate() {        return date;    }    public void setDate(Date date) {        this.date = date;    }            public ShiJuan() {    }}
ShiJuan.java

 

package beans;public class UserInfo {    private String username, password;    private int shiTiNum, shiJuanNum,rightNum;    public String getUsername() {        return username;    }    public void setUsername(String username) {        this.username = username;    }    public String getPassword() {        return password;    }    public void setPassword(String password) {        this.password = password;    }    public int getShiTiNum() {        return shiTiNum;    }    public void setShiTiNum(int shiTiNum) {        this.shiTiNum = shiTiNum;    }    public int getShiJuanNum() {        return shiJuanNum;    }    public void setShiJuanNum(int shiJuanNum) {        this.shiJuanNum = shiJuanNum;    }            public int getRightNum() {        return rightNum;    }    public void setRightNum(int rightNum) {        this.rightNum = rightNum;    }    public UserInfo() {    }}
UserInfo.java

 

package dao;import java.io.BufferedInputStream;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.IOException;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.util.Properties;public class DBUtil {        private static String driverName;    private static String username;    private static String password;    private static String url;        //    static //    {//        driverName = "com.mysql.jdbc.Driver";//        url = "jdbc:mysql://localhost:3306/siZeWeb?useSSL=false&useUnicode=true&characterEncoding=UTF-8";//        username = "root";//        password = "490272";//    }        //从属性文件加载参数(URL 用户名 密码)    static    {        Properties prop = new Properties();        try {            prop.load(DBUtil.class.getResourceAsStream("/db.properties"));            driverName = prop.getProperty("driverName");            url = prop.getProperty("url");            username = prop.getProperty("username");            password = prop.getProperty("password");                    } catch (FileNotFoundException e) {            // TODO Auto-generated catch block            e.printStackTrace();        } catch (IOException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }    }                                    public static void main(String[] args) {        Connection conn = getDBConnection();        closeDB(conn, null, null);    }        //获取数据库连接    public static Connection getDBConnection()    {        Connection conn = null;        try {            Class.forName(driverName);            conn = DriverManager.getConnection(url,username,password);        } catch (SQLException | ClassNotFoundException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }        return conn;    }        //释放资源    public static void closeDB(Connection conn,PreparedStatement pstmt,ResultSet rs)    {        try {            if(rs != null)                rs.close();        } catch (SQLException e) {            // TODO Auto-generated catch block            e.printStackTrace();        } finally {            try {                if(pstmt != null)                    pstmt.close();            } catch (SQLException e) {                // TODO Auto-generated catch block                e.printStackTrace();            } finally {                try {                    if(conn != null)                        conn.close();                } catch (SQLException e) {                    // TODO Auto-generated catch block                    e.printStackTrace();                }            }        }    }            }
DBUtil.java

 

package dao;import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Timestamp;import java.util.ArrayList;import java.util.List;import beans.ShiJuan;public class ShiJuanDAO {                //插入一条试卷记录到数据库    public void insert(ShiJuan sj) throws SQLException    {                Connection conn = null;        PreparedStatement pstmt = null;        ResultSet rs = null;                conn = DBUtil.getDBConnection();    //    System.out.println(sj.getShiTiNum() + " " + sj.getUsername() + " " + sj.getDate() + " " + sj.getUserCurrectSum());        pstmt = conn.prepareStatement("insert into shiJuanKu(shiTiNum,username,date,shiJuanID) values(?,?,?,?)");        pstmt.setInt(1, sj.getShiTiNum());        pstmt.setString(2, sj.getUsername());        pstmt.setTimestamp(3, new Timestamp(sj.getDate().getTime()));        pstmt.setInt(4, sj.getShiJuanID());        pstmt.executeUpdate();                DBUtil.closeDB(conn, pstmt, rs);            }        //根据用户名查询试卷信息,返回值类型为list    public List
selectByUsername(String username) throws SQLException { Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; List
list = new ArrayList
(); conn = DBUtil.getDBConnection(); pstmt = conn.prepareStatement("select * from shiJuanKu where username=?"); pstmt.setString(1, username); rs = pstmt.executeQuery(); while(rs.next()) { ShiJuan sj = new ShiJuan(); sj.setId(rs.getInt("id")); sj.setShiTiNum(rs.getInt("shiTiNum")); sj.setUsername(rs.getString("username")); sj.setGrade(rs.getInt("grade")); sj.setDate(rs.getTimestamp("date")); sj.setShiJuanID(rs.getInt("shiJuanID")); list.add(sj); } DBUtil.closeDB(conn, pstmt, rs); return list; } //更新试卷信息,设置试卷题目,根据用户名和用户当前试卷总数 public void update(ShiJuan sj) throws SQLException { Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; conn = DBUtil.getDBConnection(); pstmt = conn.prepareStatement("update shiJuanKu set grade=? where username=? and shiJuanID=?"); pstmt.setInt(1,sj.getGrade()); pstmt.setString(2, sj.getUsername()); pstmt.setInt(3, sj.getShiJuanID()); pstmt.executeUpdate(); DBUtil.closeDB(conn, pstmt, rs); } }
ShiJuanDAO.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 beans.ShiTi;public class ShiTiDAO {        //将list中的试题插入到数据库,    public void insert(List
list) throws SQLException { Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; conn = DBUtil.getDBConnection(); pstmt = conn.prepareStatement("insert into shiTiKu(tiMu,rightAnswer,username,logicOrder,length,shiJuanID) values(?,?,?,?,?,?)"); for(ShiTi st : list) { pstmt.setString(1, st.getTiMu()); pstmt.setString(2, st.getRightAnswer()); pstmt.setString(3, st.getUsername()); pstmt.setString(4, st.getLogicOrder()); pstmt.setInt(5, st.getLength()); pstmt.setInt(6, st.getShiJuanID()); pstmt.executeUpdate(); } DBUtil.closeDB(conn, pstmt, rs); } //根据用户名和用户的试题ID查询试题,返回结果为list public List
selectByUserNameANDShiJuanID(String username,int shiJuanID) throws SQLException { Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; List
list = new ArrayList
(); conn = DBUtil.getDBConnection(); pstmt = conn.prepareStatement("select * from shiTiKu where username=? and shiJuanID=?"); pstmt.setString(1, username); pstmt.setInt(2, shiJuanID); rs = pstmt.executeQuery(); while(rs.next()) { ShiTi st = new ShiTi(); st.setId(rs.getInt("id")); st.setTiMu(rs.getString("tiMu")); st.setRightAnswer(rs.getString("rightAnswer")); st.setUserAnswer(rs.getString("userAnswer")); st.setUserScore(rs.getInt("userScore")); list.add(st); } DBUtil.closeDB(conn, pstmt, rs); return list; } //根据用户名和试题对错查询试题,返回结果为list public List
selectByUserNameANDScore(String username,int score) throws SQLException { Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; List
list = new ArrayList
(); conn = DBUtil.getDBConnection(); pstmt = conn.prepareStatement("select * from shiTiKu where username=? and userScore=?"); pstmt.setString(1, username); pstmt.setInt(2, score); rs = pstmt.executeQuery(); while(rs.next()) { ShiTi st = new ShiTi(); st.setId(rs.getInt("id")); st.setTiMu(rs.getString("tiMu")); st.setRightAnswer(rs.getString("rightAnswer")); st.setUserAnswer(rs.getString("userAnswer")); st.setUserScore(rs.getInt("userScore")); list.add(st); } DBUtil.closeDB(conn, pstmt, rs); return list; } //根据用户名查询试题 public List
selectByUsername(String username) throws SQLException { Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; List
list = new ArrayList
(); conn = DBUtil.getDBConnection(); pstmt = conn.prepareStatement("select * from shiTiKu where username=?"); pstmt.setString(1, username); rs = pstmt.executeQuery(); while(rs.next()) { ShiTi st = new ShiTi(); st.setId(rs.getInt("id")); st.setTiMu(rs.getString("tiMu")); st.setRightAnswer(rs.getString("rightAnswer")); st.setUserAnswer(rs.getString("userAnswer")); st.setUserScore(rs.getInt("userScore")); list.add(st); } DBUtil.closeDB(conn, pstmt, rs); return list; } //根据用户名/试卷id、试题得分查询试题 public List
selectByUsernameAndShiJuanIDAndScore(String username,int shiJuanID,int score) throws SQLException { Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; List
list = new ArrayList
(); conn = DBUtil.getDBConnection(); pstmt = conn.prepareStatement("select * from shiTiKu where username=? and shiJuanID=? and userScore=?"); pstmt.setString(1, username); pstmt.setInt(2, shiJuanID); pstmt.setInt(3, score); rs = pstmt.executeQuery(); while(rs.next()) { ShiTi st = new ShiTi(); st.setId(rs.getInt("id")); st.setTiMu(rs.getString("tiMu")); st.setRightAnswer(rs.getString("rightAnswer")); st.setUserAnswer(rs.getString("userAnswer")); st.setUserScore(rs.getInt("userScore")); list.add(st); } DBUtil.closeDB(conn, pstmt, rs); return list; } //更新试题,根据题目和用户名和试卷ID public void update(List
list) throws SQLException { Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; conn = DBUtil.getDBConnection(); pstmt = conn.prepareStatement("update shiTiKu set userAnswer=?,userScore=? where tiMu=? and username=? and shiJuanID=?"); for(ShiTi st : list) { pstmt.setString(1, st.getUserAnswer()); pstmt.setInt(2, st.getUserScore()); pstmt.setString(3, st.getTiMu()); pstmt.setString(4, st.getUsername()); pstmt.setInt(5, st.getShiJuanID()); pstmt.executeUpdate(); } DBUtil.closeDB(conn, pstmt, rs); } }
ShiTiDAO.java

 

package dao;import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import beans.UserInfo;public class UserInfoDAO {    //插入一条数据到用户表    public void insert(UserInfo u) throws SQLException    {        Connection conn = null;        PreparedStatement pstmt = null;        ResultSet rs = null;                conn = DBUtil.getDBConnection();        pstmt = conn.prepareStatement("insert into userInfo(username,password) values(?,?)");                pstmt.setString(1, u.getUsername());        pstmt.setString(2, u.getPassword());        pstmt.executeUpdate();                DBUtil.closeDB(conn, pstmt, rs);    }        //查询数据库,根据用户名    public UserInfo selectByUsername(UserInfo u) throws SQLException    {        Connection conn = null;        PreparedStatement pstmt = null;        ResultSet rs = null;                UserInfo n = null;        conn = DBUtil.getDBConnection();        pstmt = conn.prepareStatement("select * from userInfo where username=?");        pstmt.setString(1, u.getUsername());                rs = pstmt.executeQuery();                if(rs.next())        {            n = new UserInfo();            n.setUsername(rs.getString("username"));            n.setPassword(rs.getString("password"));            n.setShiTiNum(rs.getInt("shiTiNum"));            n.setShiJuanNum(rs.getInt("shiJuanNum"));            n.setRightNum(rs.getInt("rightNum"));                    }                DBUtil.closeDB(conn, pstmt, rs);        return n;    }        //更新用户表,根据用户名,更新做题数目,试卷数目,正确题目个数    public void update(UserInfo u) throws SQLException    {        Connection conn = null;        PreparedStatement pstmt = null;        ResultSet rs = null;                conn = DBUtil.getDBConnection();        pstmt = conn.prepareStatement("update userInfo set shiTiNum=?,shiJuanNum=?,rightNum=? where username=?");        pstmt.setInt(1, u.getShiTiNum());        pstmt.setInt(2, u.getShiJuanNum());        pstmt.setInt(3, u.getRightNum());        pstmt.setString(4, u.getUsername());        pstmt.executeUpdate();                DBUtil.closeDB(conn, pstmt, rs);    }                        }
UserInfoDAO.java

 

package func;public class FenShu {    private int denominator, numerator;    private boolean chengLi;    public int getDenominator() {        return denominator;    }    public void setDenominator(int denominator) {        this.denominator = denominator;    }    public int getNumerator() {        return numerator;    }    public void setNumerator(int numerator) {        this.numerator = numerator;    }    public boolean isChengLi() {        return chengLi;    }    public void setChengLi(boolean chengLi) {        this.chengLi = chengLi;    }    public FenShu(int numerator, int denominator) {        this.numerator = numerator;        this.denominator = denominator;        if (denominator == 0) {            this.chengLi = false;        } else {            this.chengLi = true;            yueJian();        }    }    // 根据字符串构造分数    public FenShu(String str) {        if(str == null)        {            this.chengLi = false;        }        int index = str.indexOf("/");        if (index == -1) {            this.numerator = Integer.parseInt(str);            this.denominator = 1;            this.chengLi = true;        } else {            this.denominator = Integer.parseInt(str.substring(index + 1));            if (this.denominator == 0) {                chengLi = false;            } else {                chengLi = true;                int zhengShu = str.indexOf("'");                if (zhengShu == -1) {                    // 没有整数部分                    this.numerator = Integer.parseInt(str.substring(0, index));                } else {                    // 有整数部分                    this.numerator = Integer.parseInt(str.substring(0, zhengShu)) * this.denominator                            + Integer.parseInt(str.substring(zhengShu + 1, index));                }                yueJian();            }        }    }    public FenShu() {    }    // 约简    private void yueJian() {        int y = 1;        for (int i = numerator; i > 1; i--) {            if (numerator % i == 0 && denominator % i == 0) {                y = i;                break;            }        }        // int nc = numerator,dc = denominator;        // if(nc != 0){        // while(nc != dc - nc){        // y = dc - nc;        // if(nc > y){        // dc = nc;        // nc = y;        // }else{        // dc = y;        // }        // }        // y = nc;        //        numerator /= y;        denominator /= y;    }    // 加    public FenShu add(FenShu b) {        FenShu c = null;        if (this.chengLi && b.isChengLi()) {            int nNumerator = this.numerator * b.getDenominator() + this.denominator * b.getNumerator();            int nDenominator = this.denominator * b.getDenominator();            c = new FenShu(nNumerator, nDenominator);        } else {            c = new FenShu();            c.setChengLi(false);        }        return c;    }    // 减    public FenShu subtract(FenShu b) {        FenShu c = null;        if (this.chengLi && b.isChengLi()) {            int nNumerator = this.numerator * b.getDenominator() - this.denominator * b.getNumerator();            int nDenominator = this.denominator * b.getDenominator();            c = new FenShu(nNumerator, nDenominator);        } else {            c = new FenShu();            c.setChengLi(false);        }        return c;    }    // 乘    public FenShu multiply(FenShu b) {        FenShu c = null;        if (this.chengLi && b.isChengLi()) {            int nNumerator = this.numerator * b.getNumerator();            int nDenominator = this.denominator * b.getDenominator();            c = new FenShu(nNumerator, nDenominator);        } else {            c = new FenShu();            c.setChengLi(false);        }        return c;    }    // 除    public FenShu divide(FenShu b) {        FenShu c = null;        if (this.chengLi && b.isChengLi() && (b.getNumerator() != 0)) {            int nNumerator = this.numerator * b.getDenominator();            int nDenominator = this.denominator * b.getNumerator();            c = new FenShu(nNumerator, nDenominator);        } else {            c = new FenShu();            c.setChengLi(false);        }        return c;    }    // 输出分数形式    public String toString() {        if (this.chengLi) {            if (numerator != 0) {                if (numerator % denominator == 0)                    return "" + numerator / denominator;                else if (numerator > denominator) {                    return (numerator / denominator) + "'" + (numerator % denominator) + "/" + denominator;                }                return numerator + "/" + denominator;            }            return "0";        }        return "ERROR";    }    }
FenShu.java

 

package func;public class MyException extends Exception {    public MyException(String msg)    {        super(msg);    }}
MyException.java

 

package func;import java.util.ArrayList;import java.util.List;import beans.ShiTi;public class ShiTiFuncForm {    // 生成整数计算式添加限制条件,type为运算式类型 0代表整数式,1代表真分数式    public static List
createYunSuanShi(int hasChengChu,int hasKuoHao, int maxNum, int n, int type) throws MyException { int i = 0; if(n <= 0) { throw new MyException("运算数个数设置错误,应为正数"); } List
list = new ArrayList
(); ShiTi stb = null; // ShiTiDAO std = new ShiTiDAO(); while (i < n) { stb = ShiTiOperator.getExpress(maxNum, hasKuoHao,hasChengChu, type); // 检验重复 boolean chongFu = false; for (int j = 0; j < i; j++) { ShiTi t = list.get(j); if (ShiTiOperator.calculateOrderSame(stb, t)) { chongFu = true; System.out.println("出现重复:计算式一:" + t.getTiMu() + " = " + t.getRightAnswer() + " 运算顺序:" + t.getLogicOrder() + " 运算数个数:" + t.getLength()); System.out.println("出现重复:计算式二:" + stb.getTiMu() + " = " + stb.getRightAnswer() + " 运算顺序:" + stb.getLogicOrder() + " 运算数个数:" + stb.getLength()); System.out.println("\n\n"); break; } } if (chongFu == false) { list.add(stb); i++; } } return list; }}
ShiTiFuncForm.java

 

package func;import java.util.Random;import beans.ShiTi;//试题类,/* * 方法有:生成一个试题,计算试题答案, *  *  */public class ShiTiOperator {        // 获取一个运算式    public static ShiTi getExpress(int maxNum, int hasKuoHao, int hasChengChu,int type) throws MyException {        if(maxNum <= 0)        {            throw new MyException("最大数值应为正数");        }                ShiTi stb = new ShiTi();        Random rd = new Random();        char[] fuHao = { '+', '-', '*', '/' };        int symbolNum = 2 + hasChengChu * 2;        while (true) {            int[] bracket = null;// 存储括号位置            int expressLength = rd.nextInt(3) + 2;// 随机生成一个2~4之间的整数作为该运算式的运算数的个数            stb.setLength(expressLength);            String[] number = new String[expressLength];// 存储运算数的数组            String[] symbol = new String[expressLength - 1];// 存储运算符的数组            String express = "";            number[0] = getOperatorNumber(type, maxNum);            for (int i = 0; i < expressLength - 1; i++) {                symbol[i] = fuHao[rd.nextInt(symbolNum)] + "";// 生成运算符                number[i + 1] = getOperatorNumber(type, maxNum);            }            if (hasKuoHao == 1) {                // 需要加括号                bracket = randomAddBracket(expressLength);            }            // 构建表达式            for (int i = 0; i < expressLength; i++) {                // 添加左括号                if (hasKuoHao == 1) {                    for (int j = 0; j < bracket[i]; j++) {                        express += "(";                    }                }                express += number[i];// 加上运算数                // 添加右括号                if (hasKuoHao == 1) {                    for (int j = 0; j > bracket[i]; j--) {                        express += ")";                    }                }                if (i != expressLength - 1) {                    express += " " + symbol[i] + " ";// 加运算符,并在两侧加空格来与运算数分隔                }            }            stb.setTiMu(express);            if (!(stb.getRightAnswer().equals("ERROR"))) {                // System.out.println("生成的运算式为:" + express + "=" + result[0]);                return stb;            }        }    }    // 随机生成括号,参数为运算式的运算数的个数    private static int[] randomAddBracket(int length) throws MyException {        if(length <= 1)        {            throw new MyException("运算式长度不能小于2");        }        int[] brackets = new int[length];        for (int i = 0; i < brackets.length; i++)            brackets[i] = 0;        Random rd = new Random();        for (int i = 2; i < length; i++) {
// 添加的括号长度(括号包围的运算数的个数) for (int j = 0; j < length - i + 1; j++) { int t = rd.nextInt(2);// 随机生成0或1,0代表不加括号,1代表加括号 if (t == 1) { if (brackets[j] >= 0 && brackets[j + i - 1] <= 0) {
// 要加的括号的第一个运算数周围没有右括号,且 // 最后一个运算数周围没有左括号 int counteract1 = 0,counteract2 = 0,counteract3 = 0; for (int k = j; k < j + i; k++) {
// 将要加的括号之间的所有运算数对应的brackets相加, // 如果和为0说明这个括号之间的括号是匹配的,不会出现括号交叉现象 counteract1 += brackets[k]; } for (int k = 0; k < j - 1; k++) {
// 将要加的括号之前的所有运算数对应的brackets相加, // 如果和为0说明这个括号之间的括号是匹配的,不会出现括号交叉现象 counteract2 += brackets[k]; } for (int k = j + i; k < length; k++) {
// 将要加的括号之后的所有运算数对应的brackets相加, // 如果和为0说明这个括号之间的括号是匹配的,不会出现括号交叉现象 counteract3 += brackets[k]; } if (counteract1 == 0 && counteract2 == 0 && counteract3 == 0) { brackets[j]++; brackets[j + i - 1]--; j += i; } } } } } return brackets; } // 随机生成一个运算数( type==0代表生成整数,type==1代表生成真分数,maxNum代表数值范围 0~(maxNum-1) ) private static String getOperatorNumber(int type, int maxNum) throws MyException { if(maxNum <= 0) { throw new MyException("最大数值应为正数"); } Random rd = new Random(); int a; while (true) { a = rd.nextInt(maxNum); if (type == 0) {
// 随机生成一个整数 return "" + a; } else {
// 随机生成一个真分数 if (a == 0) { continue; } int b = rd.nextInt(a); FenShu c = new FenShu(b, a); return c.toString(); } } } //-------------------------------------------------- public static boolean calculateOrderSame(ShiTi a, ShiTi b) throws MyException { if(a == null || b == null) { throw new MyException("试题无效!"); } //比较两个运算式的运算数个数 if(a.getLength() != b.getLength()) { return false; } //比较两运算式的答案是否相同 if(!a.getRightAnswer().equals(b.getRightAnswer())) { return false; } // 取出运算式的运算顺序字符串, String aorder = a.getLogicOrder(); String border = b.getLogicOrder(); // 将a,b运算式的运算顺序字符串进行分割,按序取出每一个运算数和运算符 String[] asplit = aorder.split(","); String[] bsplit = border.split(","); int n = a.getLength() - 1;//共有n组子表达式 for(int i = 0;i < n;i++) { //取a运算式该子表达式的两个运算数a1,a2,运算符af,运算结果ar String a1 = asplit[0 + i * 3]; String af = asplit[1 + i * 3]; String a2 = asplit[2 + i * 3]; //取b运算式该子表达式的两个运算数b1,b2,运算符bf,运算结果br String b1 = bsplit[0 + i * 3]; String bf = bsplit[1 + i * 3]; String b2 = bsplit[2 + i * 3]; if(af.equals(bf)) { //两子表达式符号相同 if(a1.equals(b1) && a2.equals(b2)) { continue;//该子表达式相同,继续判断下一个子表达式 } else if( (af.equals("+") || af.equals("*")) && a1.equals(b2) && a2.equals(b1) ) { continue;//该子表达式相同,继续判断下一个子表达式 } else { return false; } } else { return false; } } return true; } //-------------------------------------------------- }
ShiTiOperator.java

 

package servlets;import java.io.IOException;import java.io.PrintWriter;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;import beans.UserInfo;/** * Servlet implementation class CheckHasLoginSL */@WebServlet("/CheckHasLoginSL")public class CheckHasLoginSL extends HttpServlet {    private static final long serialVersionUID = 1L;           /**     * @see HttpServlet#HttpServlet()     */    public CheckHasLoginSL() {        super();        // TODO Auto-generated constructor stub    }    /**     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)     */    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {        // TODO Auto-generated method stub//        response.getWriter().append("Served at: ").append(request.getContextPath());        System.out.println("开始执行获取用户是否登录的servlet");        response.setContentType("text/html;charset=UTF-8");        //获取session        HttpSession session = request.getSession();        UserInfo u = null;        u = (UserInfo)session.getAttribute("userInfo");        //获取out对象,用于向响应中输出信息        String msg;        if(u == null)        {            //session中没有用户名信息            msg = "no";            System.out.println("用户未登录");        }        else        {            msg = u.getUsername() + " " + u.getPassword();            System.out.println("用户已登录,登录用户名为: " + u.getUsername());        }        PrintWriter out = response.getWriter();        out.print(msg);        out.flush();        out.close();        System.out.println("获取用户是否登录的servlet执行结束,返回信息为:" + msg);    }    /**     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)     */    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {        // TODO Auto-generated method stub        doGet(request, response);    }}
CheckHasLoginSL.java

 

package servlets;import java.io.IOException;import java.io.PrintWriter;import java.sql.SQLException;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import beans.UserInfo;import dao.UserInfoDAO;/** * Servlet implementation class CheckUsernameHasSL */@WebServlet("/CheckUsernameHasSL")public class CheckUsernameHasSL extends HttpServlet {    private static final long serialVersionUID = 1L;           /**     * @see HttpServlet#HttpServlet()     */    public CheckUsernameHasSL() {        super();        // TODO Auto-generated constructor stub    }    /**     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)     */    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {        // TODO Auto-generated method stub//        response.getWriter().append("Served at: ").append(request.getContextPath());        response.setContentType("text/html;charSet=UTF-8");        request.setCharacterEncoding("UTF-8");        String username = request.getParameter("username");        String result = "用户名已存在";        if(username != null)        {            UserInfo u = new UserInfo();            u.setUsername(username);            UserInfoDAO uidao = new UserInfoDAO();            UserInfo n = null;            try {                n = uidao.selectByUsername(u);            } catch (SQLException e) {                // TODO Auto-generated catch block                e.printStackTrace();            }            if(n == null)            {                result = "用户名可用";            }        }                PrintWriter out = response.getWriter();        out.print(result);        out.flush();        out.close();    }    /**     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)     */    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {        // TODO Auto-generated method stub        doGet(request, response);    }}
CheckUsernameHasSL.java

 

 

package servlets;import java.io.IOException;import java.io.PrintWriter;import java.sql.SQLException;import java.util.List;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;import beans.ShiJuan;import beans.UserInfo;import dao.ShiJuanDAO;/** * Servlet implementation class GetShiJuanList */@WebServlet("/GetShiJuanListSL")public class GetShiJuanListSL extends HttpServlet {    private static final long serialVersionUID = 1L;           /**     * @see HttpServlet#HttpServlet()     */    public GetShiJuanListSL() {        super();        // TODO Auto-generated constructor stub    }    /**     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)     */    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {        // TODO Auto-generated method stub//        response.getWriter().append("Served at: ").append(request.getContextPath());        response.setContentType("text/html;charSet=UTF-8");        request.setCharacterEncoding("UTF-8");                System.out.println("获取试卷列表servlet开始执行");                //获取session对象        HttpSession session = request.getSession();        //从session对象获取用户信息        UserInfo u = (UserInfo) session.getAttribute("userInfo");        //System.out.println("参数:username=" + username);        List
shiJuanList = null; //构建试卷数据库操作对象 ShiJuanDAO sjdao = new ShiJuanDAO(); try { shiJuanList = sjdao.selectByUsername(u.getUsername()); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } String result = ""; if(shiJuanList != null) { for(int i = 0;i < shiJuanList.size();i++) { ShiJuan sj = shiJuanList.get(i); result += "日期:" + sj.getDate() + " 试题数:" + sj.getShiTiNum() + " 正确个数:" + sj.getGrade() + "," + sj.getShiJuanID() + "#"; } } //获取out输出对象 PrintWriter out = response.getWriter(); out.print(result); out.flush(); out.close(); System.out.println("获取试卷信息servlet执行结束,返回的信息:" + result); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); }}
GetShiJuanListSL.java

 

package servlets;import java.io.IOException;import java.io.PrintWriter;import java.sql.SQLException;import java.util.List;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;import beans.ShiTi;import beans.UserInfo;import dao.ShiTiDAO;/** * Servlet implementation class GetShiJuanSL */@WebServlet("/GetShiJuanSL")public class GetShiJuanSL extends HttpServlet {    private static final long serialVersionUID = 1L;           /**     * @see HttpServlet#HttpServlet()     */    public GetShiJuanSL() {        super();        // TODO Auto-generated constructor stub    }    /**     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)     */    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {        // TODO Auto-generated method stub//        response.getWriter().append("Served at: ").append(request.getContextPath());        System.out.println("获取试卷中的试题servlet开始执行");        response.setContentType("text/html;charSet=UTF-8");        request.setCharacterEncoding("UTF-8");                //获取参数值        String shiJuanID = request.getParameter("shiJuanID");        String shiTiType = request.getParameter("shiTiType");        System.out.println("获取到的参数:试题信息" + shiJuanID + "   试题类型: " + shiTiType);                        //获取用户名        HttpSession session = request.getSession();        UserInfo u = (UserInfo)session.getAttribute("userInfo");        String username = u.getUsername();                System.out.println("用户名:" + username);                List
shiTiList = null; ShiTiDAO stdao = new ShiTiDAO(); try { if(shiJuanID.equals("all")) { if(shiTiType.equals("all")) { //查询用户所有试卷的所有试题 shiTiList = stdao.selectByUsername(username); } else { int type = 0; if(shiTiType.equals("right")) { type = 1; } shiTiList = stdao.selectByUserNameANDScore(username, type); } } else { int shijuanid = Integer.parseInt(shiJuanID); if(shiTiType.equals("all")) { //查询用户所有试卷的所有试题 shiTiList = stdao.selectByUserNameANDShiJuanID(username, shijuanid); } else { int type = 0; if(shiTiType.equals("right")) { type = 1; } shiTiList = stdao.selectByUsernameAndShiJuanIDAndScore(username, shijuanid, type); } } }catch (NumberFormatException | SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } if(shiTiList == null) { System.out.println("试题list为空"); } else { System.out.println("试题list不为空,长度为:" + shiTiList.size()); for(int i = 0;i < shiTiList.size();i++) { System.out.println(shiTiList.get(i).getTiMu()); } } String result = ""; for(int i = 0;i < shiTiList.size();i++) { ShiTi st = shiTiList.get(i); result += st.getTiMu() + "," + st.getUserAnswer() + "," + st.getRightAnswer() + "," + st.getUserScore() + "#"; } PrintWriter out = response.getWriter(); out.print(result); out.flush(); out.close(); System.out.println("获取试卷中的试题servlet执行结束,返回的信息为: " + result); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); }}
GetShiJuanSL.java

 

package servlets;import java.io.IOException;import java.io.PrintWriter;import java.sql.SQLException;import java.util.ArrayList;import java.util.Date;import java.util.List;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;import beans.ShiJuan;import beans.ShiTi;import beans.UserInfo;import dao.ShiJuanDAO;import dao.ShiTiDAO;import func.MyException;import func.ShiTiFuncForm;/** * Servlet implementation class GetShiTiSL */@WebServlet("/GetShiTiSL")public class GetShiTiSL extends HttpServlet {    private static final long serialVersionUID = 1L;           /**     * @see HttpServlet#HttpServlet()     */    public GetShiTiSL() {        super();        // TODO Auto-generated constructor stub    }    /**     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)     */    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {        // TODO Auto-generated method stub//        response.getWriter().append("Served at: ").append(request.getContextPath());        System.out.println("开始获取试题servlet开始执行");        request.setCharacterEncoding("UTF-8");        //获取参数        int type = Integer.parseInt(request.getParameter("type"));        int hasChengChu = Integer.parseInt(request.getParameter("hasChengChu"));        int hasKuoHao = Integer.parseInt(request.getParameter("hasKuoHao"));        int maxNum = Integer.parseInt(request.getParameter("maxNum"));        int num = Integer.parseInt(request.getParameter("num"));        System.out.println("获取的参数值:type=" + type + "    hasChengChu=" + hasChengChu + "    hasKuoHao=" + hasKuoHao + "     maxNum=" + maxNum + "     num=" + num);        //num = 5;//测试用,删除        //获取试题        List
shiTiList = null; try { shiTiList = ShiTiFuncForm.createYunSuanShi(hasChengChu,hasKuoHao, maxNum, num, type);// shiTiList = ShiTiFuncForm.createYunSuanShi(1,1, 10, 5, 0); } catch (MyException e) { // TODO Auto-generated catch block e.printStackTrace(); } for(int i = 0;i < num;i++) { System.out.println(shiTiList.get(i).getTiMu()); } //获取session对象 HttpSession session = request.getSession(); //从session获取用户信息 UserInfo u = (UserInfo)session.getAttribute("userInfo"); //将试题信息shiTiList构建成一个字符串(每个试题用‘#’号分隔)保存到session属性 String shiTiResult = ""; int shiJuanID = u.getShiJuanNum() + 1; String username = u.getUsername(); List
shiTiList2 = new ArrayList
(); for(int i = 0;i < shiTiList.size();i++) { ShiTi st = shiTiList.get(i); shiTiResult += st.getTiMu() + "#"; st.setShiJuanID(shiJuanID); st.setUsername(username); shiTiList2.add(st); } shiTiResult += shiJuanID + "";//用户试卷id //获取out对象,将试题信息输出到响应 PrintWriter out = response.getWriter(); out.print(shiTiResult); out.flush(); out.close(); //将试题信息shiTiList保存到session中 session.setAttribute("shiTiList", shiTiList); //将试题个数保存到session中 session.setAttribute("num", num); //构建一个试卷对象 ShiJuan sj = new ShiJuan(); sj.setShiTiNum(num); sj.setUsername(username); sj.setShiJuanID(shiJuanID); sj.setDate(new Date()); //将试卷对象存储到session对象中 session.setAttribute("shiJuan", sj); //构建一个试卷数据库操作对象 ShiJuanDAO sjdao = new ShiJuanDAO(); try { //将生成的试卷对象插入到试卷数据库 sjdao.insert(sj); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } //构建一个试题数据库操作对象 ShiTiDAO stdao = new ShiTiDAO(); try { //将shiTiList插入试题数据库 stdao.insert(shiTiList2); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("获取试题servlet执行完成"); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); }}
GetShiTiSL.java

 

 

package servlets;import java.io.IOException;import java.io.PrintWriter;import java.sql.SQLException;import java.util.ArrayList;import java.util.List;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;import beans.ShiJuan;import beans.ShiTi;import beans.UserInfo;import dao.ShiJuanDAO;import dao.ShiTiDAO;import dao.UserInfoDAO;/** * Servlet implementation class JiaoJuanSL */@WebServlet("/JiaoJuanSL")public class JiaoJuanSL extends HttpServlet {    private static final long serialVersionUID = 1L;           /**     * @see HttpServlet#HttpServlet()     */    public JiaoJuanSL() {        super();        // TODO Auto-generated constructor stub    }    /**     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)     */    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {        // TODO Auto-generated method stub//        response.getWriter().append("Served at: ").append(request.getContextPath());                System.out.println("交卷servlet开始执行");        response.setContentType("text/html;charSet=UTF-8");                request.setCharacterEncoding("UTF-8");                //        Enumeration
enumer = request.getParameterNames();// for(int i = 0;i < 5;i++)// {// System.out.println(enumer.nextElement());// } //获取session对象 HttpSession session = request.getSession(); //从session中获取试题总数 int n = (int)session.getAttribute("num"); //将试题总数从session中删除 session.removeAttribute("num"); //从session中获取试题list List
shiTiList = (List
) session.getAttribute("shiTiList"); //将shitiList从session中删除 session.removeAttribute("shiTiList"); //从session中获取用户信息 UserInfo u = (UserInfo)session.getAttribute("userInfo"); //从session中获取试卷对象 ShiJuan sj = (ShiJuan)session.getAttribute("shiJuan"); //将试卷对象从session中删除 session.removeAttribute("shiJuan"); String result = ""; List
shiTiList2 = new ArrayList
(); int rightSum = 0; int wrongSum = 0; String rightTiHao = ""; String wrongTiHao = ""; //从request对象中获取用户答案与正确答案比较,并将结果添加到result字符串 for(int i = 0;i < n;i++) { ShiTi st = new ShiTi(); st = shiTiList.get(i); String userAnswer = request.getParameter((i + 1) + ""); System.out.println("正确答案:" + st.getRightAnswer()); System.out.println("获取到的用户答案,题号:" + (i + 1) + ", 答案:" + userAnswer); if(userAnswer.equals(st.getRightAnswer())) { //正确 rightSum++; st.setUserScore(1); result += "正确#"; rightTiHao += (i + 1) + ","; } else { wrongSum++; st.setUserScore(0); result += "错误,正确答案为:" + st.getRightAnswer() + "#"; wrongTiHao += (i + 1) + ","; } st.setUserAnswer(userAnswer); shiTiList2.add(st); } if(!rightTiHao.equals("")) { rightTiHao = rightTiHao.substring(0, rightTiHao.length() - 1); } if(!wrongTiHao.equals("")) { wrongTiHao = wrongTiHao.substring(0, wrongTiHao.length() - 1); } result += "正确个数:" + rightSum + "; 题号: ( " + rightTiHao + " )#错误个数:" + wrongSum + "; 题号: ( " + wrongTiHao + " )"; // result += "正确个数:" + rightSum + ",错误个数:" + wrongSum; //获取out对象 PrintWriter out = response.getWriter(); out.print(result); out.flush(); out.close(); System.out.println("返回结果,结果为:" + result); //设置试卷分数 sj.setGrade(rightSum); //更新用户信息 u.setShiJuanNum(u.getShiJuanNum() + 1); u.setShiTiNum(u.getShiTiNum() + n); u.setRightNum(u.getRightNum() + rightSum); //更新数据库 //更新试题数据库 ShiTiDAO stdao = new ShiTiDAO(); try { stdao.update(shiTiList2); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } //更新试卷数据库 ShiJuanDAO sjdao = new ShiJuanDAO(); try { sjdao.update(sj); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } //更新用户数据库 UserInfoDAO uidao = new UserInfoDAO(); try { uidao.update(u); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("交卷servlet执行结束"); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); }}
JiaoJuanSL.java

 

package servlets;import java.io.IOException;import java.io.PrintWriter;import java.sql.SQLException;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;import beans.UserInfo;import dao.UserInfoDAO;/** * Servlet implementation class LoginSL */@WebServlet("/LoginSL")public class LoginSL extends HttpServlet {    private static final long serialVersionUID = 1L;           /**     * @see HttpServlet#HttpServlet()     */    public LoginSL() {        super();        // TODO Auto-generated constructor stub    }    /**     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)     */    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {        // TODO Auto-generated method stub//        response.getWriter().append("Served at: ").append(request.getContextPath());        System.out.println("登录servlet开始执行");        response.setContentType("text/html;charSet=UTF-8");        request.setCharacterEncoding("UTF-8");        String username = request.getParameter("username");        String password = request.getParameter("password");                UserInfo u = new UserInfo();        u.setUsername(username);                UserInfo n = null;                UserInfoDAO uidao = new UserInfoDAO();        try {            n = uidao.selectByUsername(u);        } catch (SQLException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }                PrintWriter out = response.getWriter();                        if(n == null)        {            //没有此用户            out.print("用户名不存在");            System.out.println("用户名不存在");        }        else if(n.getPassword().equals(password))        {            //登录成功            //将用户信息存入session            //获取session对象            HttpSession session = request.getSession();            session.setAttribute("userInfo", n);            out.print(username);            System.out.println("用户: " + username + " 登录成功");        }        else        {            //密码错误            out.print("密码错误");            System.out.println("密码错误");        }        out.flush();        out.close();        System.out.println("登录servlet执行结束");    }    /**     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)     */    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {        // TODO Auto-generated method stub        doGet(request, response);    }}
LoginSL.java

 

package servlets;import java.io.IOException;import java.io.PrintWriter;import java.sql.SQLException;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import beans.UserInfo;import dao.UserInfoDAO;/** * Servlet implementation class LogonSL */@WebServlet("/LogonSL")public class LogonSL extends HttpServlet {    private static final long serialVersionUID = 1L;           /**     * @see HttpServlet#HttpServlet()     */    public LogonSL() {        super();        // TODO Auto-generated constructor stub    }    /**     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)     */    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {        // TODO Auto-generated method stub//        response.getWriter().append("Served at: ").append(request.getContextPath());        response.setContentType("text/html;charSet=UTF-8");        request.setCharacterEncoding("UTF-8");        String username = request.getParameter("username");        String password = request.getParameter("password");        UserInfo u = new UserInfo();        u.setUsername(username);        u.setPassword(password);        UserInfoDAO uidao = new UserInfoDAO();        try {            uidao.insert(u);        } catch (SQLException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }        PrintWriter out = response.getWriter();        out.print("success");        out.flush();        out.close();    }    /**     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)     */    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {        // TODO Auto-generated method stub        doGet(request, response);    }}
LogonSL.java

 

package servlets;import java.io.IOException;import javax.servlet.RequestDispatcher;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;/** * Servlet implementation class LogoutSL */@WebServlet("/LogoutSL")public class LogoutSL extends HttpServlet {    private static final long serialVersionUID = 1L;           /**     * @see HttpServlet#HttpServlet()     */    public LogoutSL() {        super();        // TODO Auto-generated constructor stub    }    /**     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)     */    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {        // TODO Auto-generated method stub//        response.getWriter().append("Served at: ").append(request.getContextPath());        HttpSession session = request.getSession();        session.removeAttribute("userInfo");        RequestDispatcher rd = request.getRequestDispatcher("logout.html");        rd.forward(request, response);    }    /**     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)     */    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {        // TODO Auto-generated method stub        doGet(request, response);    }}
LogoutSL.java

 

driverName=com.mysql.jdbc.Driverurl=jdbc\:mysql\://localhost:3306/siZeWeb?useSSL=false&useUnicode=true&characterEncoding=UTF-8username=rootpassword=490272
db.properties

 

var alltime = 0;      function daoJiShi()    {                var num = $("input:text[name='num']").val();        var numInt = parseInt(num);                alltime = numInt * 30;        jian();    }    function jian()    {        //alert(alltime);        if(alltime < 0)        {            return;        }        else if(alltime == 0)        {            window.alert("时间到,已自动交卷,点击确定查看答题结果");            // document.getElementById('jiaoJuanBT').click();            $("#jiaoJuanBT").click();        }        else        {        //    alert("jinlaile");            // document.getElementById('shengYuTime').innerHTML = "剩余时间:" + Math.floor(alltime / 60) + " : " + (alltime % 60);                        alltime--;            $("#shengYuTime").text("剩余时间:" + Math.floor(alltime / 60) + " : " + (alltime % 60));            setTimeout("jian()",1000);        }    }    $(document).ready(function(){            //页面加载完成即执行,利用ajax获取用户是否已登录,若返回值为no,则说明没有登录,显示登录div,否则在登录信息div显示已登录,2秒后跳转至主页        $.ajax({            url: 'CheckHasLoginSL',            type: 'GET',            //dataType: 'default: Intelligent Guess (Other values: xml, json, script, or html)',            //data: {param1: 'value1'},        })        .done(function(data) {            if(data != "no"){                $("#userInfo").show();                $("#menu").show();            }            else            {                $("#loginMessage").text("用户未登录,2秒后跳转至登录页面");                setTimeout("location='login.html'",2000);            }            console.log("success");        })        .fail(function() {            console.log("error");        })        .always(function() {            console.log("complete");        });        $("#zuoTi").click(function() {            /* Act on the event */            $("#selectInput").hide();            $("#show").hide();            $("#zuoTiInput").css('text-align', 'center');            $("#zuoTiInput").show();        });                $("#zuoTiInputTiJiao").click(function() {            /* Act on the event */                        //alert("做题alert");            $("#maxNumInfo").text("");            $("#numInfo").text("");            var pattern = /^[1-9]\d*$/;            if(!(pattern.test($("input:text[name='maxNum']").val())))            {                $("#maxNumInfo").text("请输入正整数");                return;            }            if(!(pattern.test($("input:text[name='num']").val())))            {                $("#numInfo").text("请输入正整数");                return;            }                        var canshu = "type: " + $("input[name='type']:checked").val() + ",hasChengChu: " + $("input[name='hasChengChu']:checked").val() + ",hasKuoHao: " + $("input[name='hasKuoHao']:checked").val() + ",maxNum: " + $("input:text[name='maxNum']").val() + ",num: " + $("input:text[name='num']").val() + ";";        //    alert(canshu);            $.ajax({                url: 'GetShiTiSL',                type: 'POST',                //dataType: 'default: Intelligent Guess (Other values: xml, json, script, or html)',                //data: {param1: 'value1'},                data: {type: $("input[name='type']:checked").val(),hasChengChu:$("input[name='hasChengChu']:checked").val(),hasKuoHao:$("input[name='hasKuoHao']:checked").val(),maxNum:$("input:text[name='maxNum']").val(),num:$("input:text[name='num']").val()},            })            .done(function(data) {                                var shiTiShuZu = data.split("#");                var tableTag = $("#showShiTiTable");                $("#showShiTiTable").html("");                $("#rightResult").html("");                $("#wrongResult").html("");                var tr1 = document.createElement('tr');                var th1 = document.createElement('th');                var textNode1 = document.createTextNode("题号");                th1.appendChild(textNode1);                tr1.appendChild(th1);                var th2 = document.createElement('th');                var textNode2 = document.createTextNode("题目");                th2.appendChild(textNode2);                tr1.appendChild(th2);                var th3 = document.createElement('th');                var textNode3 = document.createTextNode("答案");                th3.appendChild(textNode3);                tr1.appendChild(th3);                // var th4 = document.createElement('th');                // var textNode4 = document.createTextNode("结果");                // th4.appendChild(textNode4);                // tr.appendChild(th4);                tableTag.append(tr1);                for(var i = 0;i < shiTiShuZu.length - 1;i++)                {                    var tr2 = document.createElement('tr');                    var td1 = document.createElement('td');                    var textNode1 = document.createTextNode((i + 1) + " : ");                    td1.appendChild(textNode1);                    tr2.appendChild(td1);                    var td2 = document.createElement('td');                    var textNode2 = document.createTextNode(shiTiShuZu[i] + " = ");                    td2.appendChild(textNode2);                    tr2.appendChild(td2);                    var td3 = document.createElement('td');                    var inputTag = document.createElement('input');                    inputTag.type='text';                    inputTag.name=(i + 1) + "";                    inputTag.class="tiMu";                    td3.appendChild(inputTag);                                        var span = document.createElement('span');                    span.id=(i + 1) + "";                    td3.appendChild(span);                    tr2.appendChild(td3);                    tableTag.append(tr2);                }                            $("#menu").hide();                $("#selectInput").hide();                $("#zuoTiInput").hide();                $("#show").show();                $("#zuoTiFuZhu").show();                //开始计时                daoJiShi();                console.log("success");            })            .fail(function() {                console.log("error");            })            .always(function() {                console.log("complete");            });                    });        $("#jiaoJuanBT").click(function() {            //alert(alltime);            alltime = -1;            var userAnswer = "";            var n = $("input:text[name='num']").val();            for(var i = 0;i < n;i++)            {                userAnswer += (i + 1) + "=" + $("input:text[name='" + (i + 1) + "']").val() + "&";            }            $.ajax({                url: 'JiaoJuanSL',                type: 'POST',            //    dataType: 'default: Intelligent Guess (Other values: xml, json, script, or html)',                data: userAnswer,            })            .done(function(data) {                var result = data.split("#");                for(var i = 0;i < result.length - 2;i++)                {                    if(result[i] != "正确")                    {                        $("#"+ (i + 1)).css('color', 'red');                    }                    $("#"+ (i + 1)).text(result[i]);                }                                $("#zuoTiFuZhu").hide();                $("#menu").show();                $("#wrongResult").css('color', 'red');                $("#rightResult").text(result[result.length - 2]);                $("#wrongResult").text(result[result.length - 1]);                                console.log("success");            })            .fail(function() {                console.log("error");            })            .always(function() {                console.log("complete");            });                    });            //点击查询历史试题按钮,利用ajax获取试卷列表        $("#selectLiShiShiTi").click(function() {                        $.ajax({                url: 'GetShiJuanListSL',                type: 'POST',                //dataType: 'default: Intelligent Guess (Other values: xml, json, script, or html)',                //data: {username: username},            })            .done(function(data) {                                var shiJuanShuZu = data.split("#");                var selectTag = $("#shiJuanList");                $("#shiJuanList").html("");                var optionTag1 = document.createElement('option');                var textNode1 = document.createTextNode("全部");                optionTag1.appendChild(textNode1);                optionTag1.value="all";                optionTag1.selected = "selected";                selectTag.append(optionTag1);                            for(var i = 0;i < shiJuanShuZu.length - 1;i++)                {                                    var shiJuanVar = shiJuanShuZu[i].split(",");                    var optionTag = document.createElement('option');                    var textNode = document.createTextNode((i + 1) + "、" + shiJuanVar[0]);                    optionTag.appendChild(textNode);                    optionTag.value=shiJuanVar[1];                    selectTag.append(optionTag);                                }                $("#zuoTiInput").hide();                $("#show").hide();                $("#selectInput").show();                            console.log("success");            })            .fail(function() {                console.log("error");            })            .always(function() {                console.log("complete");            });         });        $("#selectShiJuan").click(function() {            var selectShiJuanID = $("#shiJuanList").val();            var selectType = $("#typeSelect").val();            $.ajax({                url: 'GetShiJuanSL',                type: 'POST',                //dataType: 'default: Intelligent Guess (Other values: xml, json, script, or html)',                data: {shiJuanID: selectShiJuanID,shiTiType:selectType},            })            .done(function(data) {                var shiTiShuZu = data.split("#");                var tableTag = $("#showShiTiTable");                $("#showShiTiTable").html("");                $("#result").html("");                var tr1 = document.createElement('tr');                var th1 = document.createElement('th');                var textNode1 = document.createTextNode("题号");                th1.appendChild(textNode1);                tr1.appendChild(th1);                var th2 = document.createElement('th');                var textNode2 = document.createTextNode("题目");                th2.appendChild(textNode2);                tr1.appendChild(th2);                var th3 = document.createElement('th');                var textNode3 = document.createTextNode("用户答案");                th3.appendChild(textNode3);                tr1.appendChild(th3);                var th4 = document.createElement('th');                var textNode4 = document.createTextNode("正确结果");                th4.appendChild(textNode4);                tr1.appendChild(th4);                var th5 = document.createElement('th');                var textNode5 = document.createTextNode("备注");                th5.appendChild(textNode5);                tr1.appendChild(th5);                tableTag.append(tr1);                for(var i = 0;i < shiTiShuZu.length - 1;i++)                {                    var shiTiS = shiTiShuZu[i].split(",");                    var tr2 = document.createElement('tr');                    var td1 = document.createElement('td');                    var textNode1 = document.createTextNode((i + 1) + " : ");                    td1.appendChild(textNode1);                    tr2.appendChild(td1);                    var td2 = document.createElement('td');                    var textNode2 = document.createTextNode(shiTiS[0]);                    td2.appendChild(textNode2);                    tr2.appendChild(td2);                    var td3 = document.createElement('td');                    var textNode3 = document.createTextNode(shiTiS[1]);                    td3.appendChild(textNode3);                    tr2.appendChild(td3);                    var td4 = document.createElement('td');                    var textNode4 = document.createTextNode(shiTiS[2]);                    td4.appendChild(textNode4);                    tr2.appendChild(td4);                    var td5 = document.createElement('td');                                        if(shiTiS[3] == "0")                    {                                            var textNode5 = document.createTextNode("错误");                        td5.appendChild(textNode5);                    }                    else                    {                        var textNode5 = document.createTextNode("正确");                        td5.appendChild(textNode5);                    }                                                            tr2.appendChild(td5);                    tableTag.append(tr2);                }                                            //    $("#selectInput").hide();                $("#zuoTiInput").hide();                $("#zuoTiFuZhu").hide();                $("#show").show();                console.log("success");            })            .fail(function() {                console.log("error");            })            .always(function() {                console.log("complete");            });                    });        $("input").keyup(function(event) {            /* Act on the event */            var keynode = event.which;            if(keynode == 13)            {                //alert("enter");                if($("#zuoTiInput").is(":visible"))                {                    $("#zuoTiInputTiJiao").click();                }                                            }        });             });
index.js

 

$(document).ready(function(){        //页面加载完成即执行,利用ajax获取用户是否已登录,若返回值为no,则说明没有登录,显示登录div,否则在登录信息div显示已登录,2秒后跳转至主页        $.get('CheckHasLoginSL',function(data){            if(data != "no"){                var userInfo = data.split(" ");                $("input:text(name='username')").val(userInfo[0]);                $("input:password(name='password')").val(userInfo[0]);                                    }                                                    $("#input").show();            $("input:text[name='username']").focus();                                });        //点击登录按钮时间,验证表单不能为空,不空则提交,空则给出警告信息        $("#bt2").click(function(){            $("#userInfo").text("");            $("#pwdInfo").text("");                        if($("input:text[name='username']").val() == "")            {                $("#userInfo").text("用户名不能为空");                $("input:text[name='username']").focus();            }            else if($("input:password[name='pwd']").val() == "")            {                $("#pwdInfo").text("密码不能为空");                $("input:password[name='pwd']").focus();            }            else            {                $.ajax({                    url: 'LoginSL',                    type: 'POST',                    //dataType: 'default: Intelligent Guess (Other values: xml, json, script, or html)',                    data: {username: $("input:text[name='username']").val(),password:$("input:password[name='pwd']").val()},                })                .done(function(data) {                    if(data == "用户名不存在" || data == "密码错误"){                        $("#loginResult").text(data);                    }                    else{                        location.href="index.jsp";                    }                    console.log("success");                })                .fail(function() {                    console.log("error");                })                .always(function() {                    console.log("complete");                });                                            }        });        $("input").keyup(function(event) {            /* Act on the event */            var keynode = event.which;            if(keynode == 13)            {                if($("#input").is(":visible"))                {                    $("#bt2").click();                }            }        });    });
login.js

 

$(document).ready(function() {        $("input:text[name='username']").focus();            $("#zhuCe").click(function() {            if($("#userInfo").text() == "用户名已存在")            {                $("input:text[name='username']").focus();                    return;            }            else if($("#userInfo").text() == "用户名可用")            {                $("#pwd1Info").text("");                $("#pwd2Info").text("");            }            else            {                $("#userInfo").text("");                $("#pwd1Info").text("");                $("#pwd2Info").text("");            }            var usernamePattern = /^[0-9a-zA-Z]+$/;            if($("input:text[name='username']").val() == "")            {                $("#userInfo").text("请输入用户名");                $("input:text[name='username']").focus();                }            else if(!(usernamePattern.test($("input:text[name='username']").val())))            {                $("#userInfo").text("用户名应为字母或数字");                $("input:text[name='username']").focus();                }            else if($("input:text[name='username']").val() == "no")            {                $("#userInfo").text("用户名不能为no");                $("input:text[name='username']").focus();            }            else if($("input:password[name='pwd1']").val() == "")            {                $("#pwd1Info").text("请输入密码");                $("input:password[name='pwd1']").focus();            }            else if($("input:password[name='pwd2']").val() == "")            {                $("#pwd2Info").text("请再次输入密码");                $("input:password[name='pwd2']").focus();            }            else if($("input:password[name='pwd1']").val() != $("input:password[name='pwd2']").val())            {                $("#pwd2Info").text("两次输入的密码不一致");                $("input:password[name='pwd2']").focus();            }            else            {                $.ajax({                    url: 'LogonSL',                    type: 'POST',                    //dataType: 'default: Intelligent Guess (Other values: xml, json, script, or html)',                    data: {username: $("input:text[name='username']").val(),password:$("input:password[name='pwd1']").val()},                })                .done(function(data) {                    if(data == "success")                    {                        $("#logonResult").text("注册成功,2秒后跳转至登录页面");                        setTimeout("location.href='login.html'",2000);                    }                    else                    {                        $("#logonResult").text("注册失败!");                    }                    console.log("success");                })                .fail(function() {                    console.log("error");                })                .always(function() {                    console.log("complete");                });                            }                });        $("input:text[name='username']").change(function() {            if($("input:text[name='username']").val() != "")            {                $.ajax({                    url: 'CheckUsernameHasSL',                    type: 'POST',                    //dataType: 'default: Intelligent Guess (Other values: xml, json, script, or html)',                    data: {username: $("input:text[name='username']").val()},                })                .done(function(data) {                    if(data == "用户名已存在")                    {                        $("#userInfo").text("用户名已存在");                        $("input:text[name='username']").focus();                    }                    else                    {                        $("#userInfo").text("用户名可用");                    }                    console.log("success");                })                .fail(function() {                    console.log("error");                })                .always(function() {                    console.log("complete");                });                            }        });        $("input").keyup(function(event) {            /* Act on the event */            var keynode = event.which;            if(keynode == 13)            {                $("#zhuCe").click();            }        });    });
logoutFunc.js

 

<%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%> 
主页
用户名:${userInfo.username}
试题类型:
有无乘除:
有无括号:
最大值:
试题个数:
试卷:
类型:
index.jsp

 

 

登录
用户名:
密码:
login.html

 

注册
用户名:
密码:
请再次输入密码:
已有账号,点次登录
logon.html

 

注销

注销成功,2秒后跳转至登录页面

logout.html

 

转载于:https://www.cnblogs.com/liuxining/p/6679526.html

你可能感兴趣的文章
iOS开发-NSOperation与GCD区别
查看>>
EF-InvalidOperation系列
查看>>
apache-storm-0.9.6.tar.gz的集群搭建(3节点)(图文详解)
查看>>
AngularJS 课程
查看>>
mysql处理特殊字符
查看>>
大叔也说Xamarin~Android篇~环境部署与破解
查看>>
SQL Server 索引设计指南
查看>>
naotu.baidu.com 非常棒的脑图在线工具
查看>>
MOSS中创建自定义内容类型
查看>>
将不确定变为确定~Razor视图中是否可以嵌套JS代码
查看>>
[LeetCode] Shortest Word Distance 最短单词距离
查看>>
配置Tomcat以Debug模式启动了,但却只能本地用localhost连接调试
查看>>
“HTTP Status 404 - No result defined for action ****** and result result”错误解决方法
查看>>
PostgreSQL参数学习:wal_keep_segments
查看>>
[自己动手玩黑科技] 1、小黑科技——如何将普通的家电改造成可以与手机App联动的“智能硬件”...
查看>>
Phonegap 通知 Notification
查看>>
3.2. 用户认证
查看>>
ORACLE 9i卸载并重新安装
查看>>
[Python]Hamming distance 问题
查看>>
详解游标
查看>>