Quiz report

1,283 views

Published on

University project report to document a Java program which uses JSP pages to display and mark quiz questions stored in XML.

Published in: Technology, News & Politics
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
1,283
On SlideShare
0
From Embeds
0
Number of Embeds
3
Actions
Shares
0
Downloads
28
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Quiz report

  1. 1. UNIVERSITY OF MANCHESTER COMP27010 Coursework 3 Carrie Louise Hall 7179881 April 24th 2009The aim of this report is to document a Java program which uses JSP to display and mark quizquestions.These quizzes are stored in XML format.
  2. 2. Table of ContentsDescription of Design................................................................................................................................................................................. - 2 - Loading the program............................................................................................................................................................................. - 2 - Reading in the XML document .......................................................................................................................................................... - 2 - Displaying the Quiz ................................................................................................................................................................................- 3 - Marking the Quiz..................................................................................................................................................................................... - 3 - Completing the Quiz .............................................................................................................................................................................. - 3 - Session Variables .................................................................................................................................................................................... - 3 -Class Diagram................................................................................................................................................................................................ - 4 - Introduction ......................................................................................................................................................................................... - 4 - Diagram ................................................................................................................................................................................................. - 4 -Hierarchical Task Analysis ......................................................................................................................................................................- 5 - Introduction ......................................................................................................................................................................................... - 5 - Diagram ................................................................................................................................................................................................. - 5 -Sequence Diagram ...................................................................................................................................................................................... - 5 - Introduction ......................................................................................................................................................................................... - 5 - Diagram ................................................................................................................................................................................................. - 5 -Screenshots .................................................................................................................................................................................................... - 6 - Step one ................................................................................................................................................................................................. - 6 - Step two ................................................................................................................................................................................................. - 6 - Step three .............................................................................................................................................................................................. - 7 - Step four ................................................................................................................................................................................................ - 7 - Step five .................................................................................................................................................................................................- 9 - Step six ................................................................................................................................................................................................ - 10 -Works Cited ................................................................................................................................................................................................ - 11 -Appendix ...................................................................................................................................................................................................... - 12 - XML Original Quiz – Quiz 1 (People.xml)................................................................................................................................... - 12 - XML Result.............................................................................................................................................................................................. - 13 - XMLWriter.java .................................................................................................................................................................................... - 14 - XMLReader.java ................................................................................................................................................................................... - 15 - Quiz.java .................................................................................................................................................................................................. - 19 - Question.java ......................................................................................................................................................................................... - 23 - Answer.java............................................................................................................................................................................................ - 24 - Index.html............................................................................................................................................................................................... - 26 - Error.jsp................................................................................................................................................................................................... - 27 - Success.jsp .............................................................................................................................................................................................. - 28 - ShowQuiz.jsp ......................................................................................................................................................................................... - 29 - MarkTest.jsp .......................................................................................................................................................................................... - 33 - Carrie Hall 7179881 -1-
  3. 3. Description of DesignThe initial page of the program is index.jsp. This file contains an input box for the user to enter their name. Loading the programThis name is used to store session variables in the program and also it is used in the creation of the XMLdocuments to store the users’ answers. The index page also contains a drop down box which contains somepredefined quizzes that the user can take. The value in the dropdown box is the filename of the XML documentwhich contains that quiz. The title of the quiz is what is displayed to the user. The input box and drop downmenu are part of a form element which redirects to the file showQuiz.jsp on submission.As previously mentioned, the filename of the required quiz is passed in to showQuiz.jsp. Validation is done toensure that the user entered a valid name (with valid being a non-empty string). If the name is invalid then thepage redirects to the error.jsp page where it displays the error to the user. Once validation is complete thefilename is sent to the XMLReader class.The XMLReader class uses the Java built-in function newDocumentBuilder() in the DocumentBuilderFactory Reading in the XML documentclass. According to Sun Microsystems, this method “defines a factory API that enables applications to obtain aparser that produces DOM object trees from XML documents” (Sun Microsystems, 2004). Once this instance hasbeen created, a recursive 1 function is run to create the Quiz object. Firstly the method checks that the currentelement node is one of the following: test, question, answer. These are the only elements which should be inthe XML document therefore if the method encounters an incorrect node the error count is increased and thefile will not convert (a message will be displayed to the user on such an event). If the method encounters a testnode it validates that the text node has an attribute called ‘name’ which must not be empty. A Quiz object isthen created by passing in the quiz name. The test node should look like the XML snipped shown in Figure 1. <test name=“General Knowledge”>If a question node is encountered then the method validates that it has a ‘number’ attribute indicating the Figure 1number of the question. A Question object is created and added to the Quiz object provided that the questionnumber does not already exist in the Quiz. The question node should look like the XML snipped shown in Figure2. <question number=“1”> What is the capital of Italy? </question>If an answer node is encountered then the method also validates that it has a ‘number’ attribute indicating the Figure 2number of the answer, but also that it has a ‘type’ attribute. Validation is used to ensure that this attribute mustbe either ‘correct’ or ‘incorrect’ and a question can have only one ‘correct’ answer. The answer is linked to thequestion by storing the value of the current question, i.e. a question is found and every answer that is foundafter it is considered to be an answer of that question (until another question is reached). Again an Answerobject is created and added to the test, passing in the answer, its number and type and the question number.This too is subject to validation to guarantee that each answer number is unique. Further validation is done onanswers to make certain that a Question has one and only one correct answer. The answer node should looklike the XML snipped shown in Figure 3. 1Recursion: The ability of a program to call itself which also enables a program to define itself in terms of itself (Terry, 2001) Carrie Hall 7179881 -2-
  4. 4. <answer number=“1” type=“correct”> Rome </answer> Figure 3The Quiz object is returned to the showQuiz.jsp page where the function prints all questions and answer sets Displaying the Quizby using a loop. Each question is shown on the screen and radio buttons are used for the answers. Radiobuttons enforce the user to select a correct answer. A common difficulty when using radio buttons is that a usercan sometimes not select one which leads to null values. To overcome this, the method automatically selects thefirst item in each answer set. Hidden variables are used in the form to store important information about thequiz, namely the filename, quiz name, the total number of questions and the number of answers for eachquestion. Once the user has selected all answers and press the submit button the page is redirected toThe Quiz uses CSS 2to style the page into an easy-to-read page.MarkTest.jsp.At the MarkTest.jsp page the aforementioned hidden variables are used to loop through the questions and Marking the Quizanswers and get the items that the user selected. Each of these question and single answer sets are stored as anXML file named in the format shown in Figure 4 where quizname is the name of the quiz, person is the personsname, date is a timestamp to uniquely identify each quiz attempt and attempts is the number of attempts. quizname_person_date_attempts.xmlIf the correct answer was not selected then it all questions except the one that they selected are added to a new Figure 4Quiz which will be shown to the user. If this Quiz has any questions then the page will be redirected back toshowQuiz.jsp.Once the user has selected all the correct answers they are taken to the success.jsp page which informs them of Completing the Quizhow many attempts they took at the quiz which will be explained momentarily. The number of attempts affectsthe message that they receive on the success page.Session variables are used to store information that will be passed through each of the .jsp pages. A Quiz Session Variablessession holds the current Quiz which is how the quiz gets progressively smaller as the user selects incorrectanswers. A session is also used to store the amount of times a user submits a quiz as previously discussed.These variables are reset once the user is redirected back to the homepage to choose another quiz to take. 2 CSS: Cascading Style Sheet. They are used to style HTML tags on a webpage. Carrie Hall 7179881 -3-
  5. 5. Class DiagramClass diagrams are widely used in software development and “describes the types of objects in the system andIntroductionthe various kinds of static relationships that exist among them” (Fowler, 2004).Key: Class NameAttributesMethodsDiagram Carrie Hall 7179881 -4-
  6. 6. Hierarchical Task AnalysisHierarchical task diagrams describe “how tasks are split into sub-tasks, their ordering and when they areIntroductionperformed” (Stevens, 2008). The structure of a hierarchical task diagrams usually consists of “a goal at the top,followed by sub-goals, unit tasks and artefacts. Sub-goals may be further sub-divided as required” (ACM, 2005).These goals are normally written from the perspective of the user.DiagramSequence DiagramThis diagram shows the classes that will be called when the system is run.IntroductionDiagram Carrie Hall 7179881 -5-
  7. 7. ScreenshotsThe page is loaded and a text field is shown to the userStep oneThe user does not enter a name in the text fieldStep two Carrie Hall 7179881 -6-
  8. 8. There is a problem with the XML file. In this example, there is no correct answer for one of the questions.Step threeThe user has entered a correct name and the XML file is valid so the quiz is shown (image on following page)Step four Carrie Hall 7179881 -7-
  9. 9. Carrie Hall 7179881 -8-
  10. 10. The user has entered some correct and some incorrect answers so the quiz is redisplayed with the incorrectStep fiveanswers. Their original answer has been removed Carrie Hall 7179881 -9-
  11. 11. After a few more attempts the quiz has been successfully completed. A different message is shown if the userStep sixhad got more or less answers. Carrie Hall 7179881 - 10 -
  12. 12. ACM. (2005, January/February). A Tale of Two Tutorials: A Cognitive Approach to Interactive System DesignWorks Citedand Interaction Design Meets Agility. Interactions Magazine , pp. 49-51.Fowler, M. (2004). UML Distilled. Addison-Wesley.Stevens, R. (2008). Task Analysis. CS2341 Lecture Notes . Manchester: University Of Manchester.Sun Microsystems. (2004, January 8). Class DocumentBuilderFactory. Retrieved April 01, 2009, fromhttp://java.sun.com/j2se/1.5.0/docs/api/javax/xml/parsers/DocumentBuilderFactory.htmlTerry, H. (2001, April 30). Glossary of Terms. Retrieved April 1, 2009, from PC AI Online:http://www.pcai.com/web/glossary/pcai_j_l_glossary.html Carrie Hall 7179881 - 11 -
  13. 13. This appendix contains the code for the program and the XML files that are produced.AppendixThis is an example of one (out of 3) of the original XML quizzes used in this program. XML Original Quiz – Quiz 1 (People.xml)<?xml version="1.0" ?><test name=People> <question number=1>Siddartha Gautama is </question> <answer number=1 type="correct">Founder of Buddhism</answer> <answer number=2 type="incorrect">Founder of Hinduism</answer> <answer number=3 type="incorrect">Founder of Islam</answer> <question number=2>Socrates is </question> <answer number=1 type="incorrect">Egyptian Pharoah</answer> <answer number=2 type="incorrect">Enlightened Master</answer> <answer number=3 type="correct">Greek Philosopher</answer> <question number=3>Herodotus is </question> <answer number=1 type="correct">"Father of History" wrote about Persianwars</answer> <answer number=2 type="incorrect">"Father of History" wrote about Punicwars</answer> <answer number=3 type="incorrect">"Father of History" wrote aboutPeloponesian</answer> <question number=4>Emperor Xerxes is </question> <answer number=1 type="correct">Led battle of Thermopoleyes in the PersianWars</answer> <answer number=2 type="incorrect">Led battle of Thermopoleyes in thePeloponesian War</answer> <answer number=3 type="incorrect"> Led battle of Thermopoleyes in the PunicWars</answer> <question number=5>Homer is </question> <answer number=1 type="incorrect">Wrote Medea</answer> <answer number=2 type="correct">Wrote the Illiad and the Odyssey</answer> <answer number=3 type="incorrect">Wrote poems about love andfriendship</answer></test> Carrie Hall 7179881 - 12 -
  14. 14. This is an example of the XML files that are produced when the user submits a quiz several times XML Result Filename: General_Knowledge_Carrie L Hall_1240941105812 attempt1.xml<?xml version="1.0"?><test name=General_Knowledge> <question number=1>What is the most common Element on Earth?</question> <answer number=1 type=incorrect>Oxygen</answer> <question number=2>How many miles high is Mount Everest (to nearestmile)?</question> <answer number=1 type=correct>9 Miles</answer> <question number=3>Which country features a maple leaf on its flag?</question> <answer number=1 type=incorrect>France</answer> <question number=4>What is the worlds most spoken language?</question> <answer number=1 type=correct>Chinese (Mandarin)</answer> <question number=5>What year did the Berlin Wall come down?</question> <answer number=1 type=incorrect>1986</answer></test> Filename: General_Knowledge_Carrie L Hall_1240941105812 attempt2.xml<?xml version="1.0"?><test name=General_Knowledge> <question number=1>What is the most common Element on Earth?</question> <answer number=2 type=correct>Hydrogen</answer> <question number=3>Which country features a maple leaf on its flag?</question> <answer number=2 type=incorrect>Russia</answer> <question number=5>What year did the Berlin Wall come down?</question> <answer number=2 type=incorrect>1992</answer></test> Filename: General_Knowledge_Carrie L Hall_1240941105812 attempt3.xml<?xml version="1.0"?><test name=General_Knowledge> <question number=3>Which country features a maple leaf on its flag?</question> <answer number=3 type=correct>Canada</answer> <question number=5>What year did the Berlin Wall come down?</question> <answer number=3 type=incorrect>1979</answer></test> Carrie Hall 7179881 - 13 -
  15. 15. XMLWriter.javapackage xmlquizpackage;import java.io.*;public class XMLWriter{ public XMLWriter(String outputFile, Quiz UserQuiz) { try { //open the file to write PrintStream os = new PrintStream(new FileOutputStream(new File(outputFile))); //header information os.println("<?xml version="1.0"?>"); //test is the root element os.println("<test name="+UserQuiz.getQuizName()+" " + "attempts="+UserQuiz.getQuizAttempts()+">"); //print the quiz os.print(UserQuiz.toXML()); //end root element os.println("</test>"); os.flush(); os.close(); } catch(Exception e) { System.out.println(e); } }}Carrie Hall 7179881 - 14 -
  16. 16. XMLReader.javapackage xmlquizpackage;//importsimport javax.xml.parsers.*;import java.io.IOException;import org.w3c.dom.*;import org.xml.sax.SAXException;public class XMLReader{ Document dom; //structure of document Quiz q; //the Quiz to create from the XML document int questionNum; //question number int errors; //error count public XMLReader(String quizIn) { errors = 0; dom = parseXMLFile(quizIn); //makes DocumentBuilderFactory analyseElements(dom, ""); //recursive method /*one final check that the XML document is valid is made to ensure that all questions have a correct answer. It has already been validated that they dont have more than one*/ if (!q.checkCorrectAnswers()) { errors++; } } /** * * @return Quiz that has been created */ public Quiz getQuiz() { return q; } /** * Used to check if there were any errors with the XML document * @return int */ public int getErrors() { return errors; } /** * Private method to create a DocumentBuilderFactory * @param xmlfile * @return Document (stored as variable dom */ private Document parseXMLFile(String xmlfile)Carrie Hall 7179881 - 15 -
  17. 17. { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); try { DocumentBuilder db = dbf.newDocumentBuilder(); dom = db.parse(xmlfile); return dom; } catch (ParserConfigurationException pce) { errors++; } catch (SAXException se) { errors++; } catch (IOException ioe) { errors++; } return null; } /** * recursive method which creates Quiz object * @param node at which element is on * @param indent */ void analyseElements(Node node, String indent) { String name = node.getNodeName(); //gets name NodeList children = node.getChildNodes(); //gets children NamedNodeMap attributes = node.getAttributes(); //gets attributes switch (node.getNodeType()) { case Node.DOCUMENT_NODE: analyse(children, indent + " "); break; case Node.ELEMENT_NODE: if (name.equals("test")) //root element { //checks if it is missing attribute name if (attributes.getNamedItem("name") != null) { try { //gets value of name attribute q = new Quiz(attributes.getNamedItem("name") .getNodeValue().toString()); //recursion analyse(children, indent + " "); } catch (DOMException e) //no value for name attribute {Carrie Hall 7179881 - 16 -
  18. 18. errors++; } } else //no attribute for name { errors++; } } else if (name.equals("question")) //question node { if (children.item(0) != null) //must have a text node { try { //get question info String question= children.item(0).getNodeValue().trim(); String number = attributes.getNamedItem("number") .getNodeValue(); //stores the question number so whatever answer nodes //follow this get added to this question questionNum = Integer.parseInt(number); //if question number is unique if (!q.addQuestion(questionNum, question)) { errors++; } analyse(children, indent + " "); } catch (DOMException e) { errors++; } catch (NumberFormatException n) { errors++; } } else //missing value for question { errors++; } } else if (name.equals("answer")) //answer node { if (children.item(0) != null) //must have a text node { try { //get answer details String answer = children.item(0).getNodeValue().trim(); String ansNum = attributes.getNamedItem("number").getNodeValue(); int answerNum = Integer.parseInt(ansNum); String type = attributes.getNamedItem("type").getNodeValue(); /*checks if answer number has not already been written and that only one correct answer is found*/ if (!q.addAnswer(questionNum, answerNum, answer, type))Carrie Hall 7179881 - 17 -
  19. 19. { errors++; } } catch (DOMException e) { errors++; } catch (NumberFormatException n) { errors++; } analyse(children, indent + " "); } else //incorrect xml { errors++; } } else //incorrect xml { errors++; } break; default: break; } } /* Recursive method to read the XML file */ public void analyse(NodeList children, String indent) { for (int i = 0; i < children.getLength(); i++) { analyseElements(children.item(i), indent); } }}Carrie Hall 7179881 - 18 -
  20. 20. package xmlquizpackage;Quiz.java//importsimport java.util.ArrayList;import java.util.Collections;import java.util.Iterator;public class Quiz{ String name; //stores the name of the quiz ArrayList<Question> questions; //stores the questions ArrayList<Answer> answers; //stores all answers /** MAIN METHOD. This class instantiates the ArrayLists and names the quiz according to the name of the file specified in the XML e.g. <test name="Java Quiz"> would call the quiz "Java Quiz" */ public Quiz(String nameIn) { questions = new ArrayList<Question>(); answers = new ArrayList<Answer>(); name = nameIn; } /** * Adds a question to the quiz * @param: question number * question */ public boolean addQuestion(int questionNoIn,String questionIn) { //loops through all questions Iterator i = questions.iterator(); while (i.hasNext()) { Question q = (Question) i.next(); //typecasts //if the question number is already in the list if(q.getQuestionNo()==questionNoIn) { return false; } } return questions.add(new Question(questionNoIn, questionIn)); } /** * Adds an answer to the quiz * @param: question number * answer number * answer * type (correct || incorrect) */ public boolean addAnswer(int questionNoIn,int answerNoIn,String answerIn, String typeIn) { //checks that it is of correct type if (!typeIn.equals("correct")) { if (!typeIn.equals("incorrect")) {Carrie Hall 7179881 - 19 -
  21. 21. return false; } } //loops through all answers Iterator i = getAnswers(questionNoIn).iterator(); while (i.hasNext()) { Answer a = (Answer) i.next(); //typecasts //if the answer number is already in the list if(a.getAnswerNo()==answerNoIn) { return false; } /*If the XML file has two answers which it has labelled correct then an error should be shown*/ if (typeIn.equals("correct")) { if (a.getType().equals(typeIn)) { return false; } } } return answers.add(new Answer(questionNoIn,answerNoIn,answerIn,typeIn)); } /** * * @return ArrayList of questions belonging to this quiz */ public ArrayList<Question> getQuestions() { return questions; } /** * returns the quiz name * @return String (quiz name) */ public String getQuizName() { return name; } /** * Returns all answers belonging to a particular question * @param questionNo * @return ArrayList of questions belonging to this quiz */ public ArrayList<Answer> getAnswers(int questionNo) { //temp array to store certain variables from the "answers" ArrayList ArrayList<Answer> temp = new ArrayList<Answer>(); Iterator i = answers.iterator(); while (i.hasNext()) { Answer a = (Answer) i.next(); //converts object to Answer if (a.getQuestionNo()==questionNo) //if it belongs to required q { temp.add(a); //adds to temp arrayListCarrie Hall 7179881 - 20 -
  22. 22. } } /*The list is then sorted using the Answer class method "compareTo()" * It sorts them based on their unique answer ID. This is so that the * order that the answers appear can be changed by changing the XML file * thus ensuring that correct answers can appear in "random" places. */ Collections.sort(temp); return temp; } /** * Returns the correct answer of a particular question * @param questionNo * @return String answer */ public int getCorrectAnswer(int questionNo) { Iterator i = answers.iterator(); while (i.hasNext()) { Answer a = (Answer) i.next(); //converts object to Answer if (a.getQuestionNo()==questionNo) //if it belongs to required q { if (a.getType().equals("correct")) { return a.getAnswerNo(); } } } return -1; //will never be returned due to validation ensuring that //all questions have an answer } /** * Returns the correct answer of a particular question * @param questionNo * @return String answer */ public Answer getAnswerByNumber(int ansNum) { Iterator i = answers.iterator(); while (i.hasNext()) { Answer a = (Answer) i.next(); //converts object to Answer if (a.getAnswerNo()==ansNum) //if it belongs to required q { if (a.getType().equals("correct")) { return a; } } } return null; } /*** Similiar to toString() method. * @return XML String */Carrie Hall 7179881 - 21 -
  23. 23. public String toXML() { String xml = ""; for (int i=0;i<getQuestions().size();i++) { Question q = getQuestions().get(i); //the XML question wrapper xml+="t<question number=" + q.getQuestionNo() + ">"; //the question itself xml+= q.getQuestion(); //end of question xml+="</question>r"; //loops through answers for (int j=0;j<getAnswers(q.getQuestionNo()).size();j++) { Answer a = getAnswers(q.getQuestionNo()).get(j); //print answer xml+="tt<answer number="+a.getAnswerNo()+" type="+a.getType()+">"; xml+= a.getAnswer(); xml+="</answer>r"; } } return xml; //return full string } /** * Checks that at a correct answer is given for each question. Further * validation has been done to ensure that no more than 1 correct answer * can be given * @return boolean */ public boolean checkCorrectAnswers() { Iterator i = questions.iterator(); //loops through questions while (i.hasNext()) { boolean found = false; Question q = (Question) i.next(); //converts object to Answer Iterator j = this.getAnswers(q.getQuestionNo()).iterator(); while (j.hasNext()) { Answer a = (Answer) j.next(); //converts object to Answer if (a.getType().equals("correct")) { found = true; } } if (!found) { return false; //no correct answer } } return true; //not returned false so must be true }}Carrie Hall 7179881 - 22 -
  24. 24. Question.javapackage xmlquizpackage; /** * Question class */public class Question{ int questionNo; String question; public Question(int questionNoIn,String questionIn) { questionNo = questionNoIn; question = questionIn; } public void editQuestion(String questionIn) { question = questionIn; } public void editQuestionNo(int questionNoIn) { questionNo = questionNoIn; } public int getQuestionNo() { return questionNo; } public String getQuestion() { return question; }}Carrie Hall 7179881 - 23 -
  25. 25. Answer.javapackage xmlquizpackage;/*This class implements comparable because the answers are ordered by their answer number*/public class Answer implements Comparable<Answer>{ int questionNo; //question to which the answer belongs int answerNo; //orders the answers String answer; String type; //either "correct" OR "incorrect" public Answer(int questionIn,int answerNoIn,String answerIn,String typeIn) { questionNo = questionIn; answer = answerIn; answerNo = answerNoIn; type = typeIn; } public int getQuestionNo() { return questionNo; } public int getAnswerNo() { return answerNo; } public String getAnswer() { return answer; } public String getType() { return type; } public void editAnswer(String answerIn) { answer = answerIn; } public void changeAnswerNumber(int answerNoIn) { answerNo = answerNoIn; }Carrie Hall 7179881 - 24 -
  26. 26. public void changeType(String typeIn) { type = typeIn; } /*The method which allows two answers to be compared*/ public int compareTo(Answer ans) { final int BEFORE = -1; final int EQUAL = 0; final int AFTER = 1; if (this.getAnswerNo() == ans.getAnswerNo()) { return EQUAL; } if (this.getAnswerNo() < ans.getAnswerNo()) { return BEFORE; } if (this.getAnswerNo() > ans.getAnswerNo()) { return AFTER; } assert this.equals(ans) : "compareTo inconsistent with equals."; return EQUAL; } }Carrie Hall 7179881 - 25 -
  27. 27. Index.html<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN""http://www.w3.org/TR/html4/loose.dtd"><link href="http://www.carriehall.co.uk/java/style.css" rel="stylesheet" type="text/css" /><title>XML Quiz</title><body> <h1>XML Quiz</h1> <form id="mainform" name="doForm" action="showQuiz.jsp" method="POST"> <table> <tr><td><input type="hidden" name="Action" value="Page" /> Please enter your name:</td> <td> <input type="text" name="person" value="" size="20" /></td> </tr> <tr><td>Please choose a quiz:</td><td> <select name="quiz"> <option value="generalknowledge.xml" selected>General Knowledge 1</option> <option value="generalknowledge2.xml" >General Knowledge 2</option> <option value="people.xml" >People</option> </select></td></tr> <tr><td colspan="2" align="right"><input type="submit" value="Go!" name="do" /></td></tr> </table> </form></body></html> Carrie Hall 7179881 - 26 -
  28. 28. <%@page contentType="text/html" pageEncoding="UTF-8"%> Error.jsp<%/* * This page gets displayed when an error occurs.*/ //gets the session parameter containing the error message(s) String error = (String) session.getAttribute("error");%><!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"> <title>XML Quiz</title> </head> <body> <h1>Error</h1> <p>The following error occured:</p> <%= error %> <p><a href="index.html">Click here</a> to go to the main page</p> </body></html> Carrie Hall 7179881 - 27 -
  29. 29. <!-- page imports ---> Success.jsp<%@page import="xmlquizpackage.*" %><%@page contentType="text/html" pageEncoding="UTF-8"%><%/*This page gets called when the user has completed the quiz*/String person = "";String message = "";int attempts = 0;if (session.getAttribute("person")!=null){ person = (String) session.getAttribute("person");}if (session.getAttribute("attempts")!=null){ attempts = (Integer.parseInt(session.getAttribute("attempts").toString()));}if (attempts==1){ message+= " attempt. Well done!";}else if (attempts>1 && attempts<4){ message+= " attempts. Nearly there!";}else if (attempts<=4 && attempts<10){ message+= " attempts. Try a little harder next time!";}else if (attempts>=10){ message+= " attempts. You have made history with this abysmal test!";}%><!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"> <title>XML Quiz</title> </head> <body> <h1>Congratulations <%= person %>!</h1> <p>You completed the test in <%= attempts + message %> </p> <p><a href="index.html">Click here</a> to go back to the home page to attempt another quiz</p> </body></html> Carrie Hall 7179881 - 28 -
  30. 30. <!‐‐ page imports ‐‐> ShowQuiz.jsp<%@page import="java.util.Iterator" %><%@page import="java.util.Iterator" %><%@page import="xmlquizpackage.*" %> <!‐‐ imports the classes ‐‐><%@page contentType="text/html" pageEncoding="UTF‐8"%><%!/* method to redirect to the error page*/public void doError(HttpServletResponse res,HttpSession sess,String errorMsg){ try { sess.setAttribute("error", errorMsg); res.sendRedirect("error.jsp"); } catch (Exception e) { }}%><%/* Main method. This is the page that displays quizzes to the user. It can be* called from index.html where it passes in the persons name and the quiz they* choose to take. It can also be called from the MarkTest.jsp page to redisplay* tests that have incorrect answers. *///variablesint errors = 0; //error countString errorMsg = ""; //error messageString quiz = ""; //quiz filename (from dropdown)String person = ""; //persons nameint attempts = 0; //number of attempts at testQuiz uQuiz = null; //Quiz objectint qcount = 0; //to store the count of questionsint maxNoOfAnswers = 0; //to store the maximum number of answers/* If request.getParameter("person") returns a result then it* must be a request from the 1st page.* Need to get the name of the person and the quiz, read in that quiz from XML* and turn it into a Quiz object to display. Only the first page has an*/if (request.getParameter("person")!=null){ /*In case the person has done a test before and is choosing to do a second, the session attributes must be reset*/ session.setAttribute("attempts", 1); session.setAttribute("Quiz", null); session.setAttribute("person", null); //gets the persons name and removes whitespace person = request.getParameter("person").toString().trim(); if (person.equals(""))//if the person didnt enter a name { errorMsg+="Please enter a valid name<br />"; //writes error message errors++; //increases error count } else //correct name entered Carrie Hall 7179881 - 29 -
  31. 31. { //gets the information sent from the initial form quiz = request.getParameter("quiz"); //dropdown box of quizzes person = request.getParameter("person"); //persons name attempts = 1; XMLReader x = new XMLReader(quiz); //reads the xml file if (x.getErrors()==0) //no errors occured with reading the xml file { uQuiz = x.getQuiz(); //saves the xml quiz } else //errors occurred { errorMsg+="Incorrect XML file<br />"; //writes error message errors++; //increases error count } }}/*If there is no request.getParameter for "person" then the page will have been* called from the marktest page (ie its a resubmission of the quiz. This* Quiz is saved as a session variable and must be retrieved in order to show it* to the user */else{ //gets the current number of attempts attempts = Integer.parseInt(session.getAttribute("attempts").toString()); //saves the session Quiz as uQuiz //this is the quiz that has reduced values uQuiz = (Quiz) session.getAttribute("Quiz"); //gets the persons name from the session person = (String) session.getAttribute("person"); //gets the filename quiz = (String) session.getAttribute("filename");}if (errors>0) //errors occured{ doError(response,session,errorMsg); //call method to redirect}else //no errors so print the html{ //makes an iterator to loop through the questions in the quiz Iterator i = uQuiz.getQuestions().iterator();%><html><head><title>XML Quiz</title></head><body><h1><%= uQuiz.getQuizName()%></h1> <!‐‐Prints the name of the quiz ‐‐><!‐‐Prints the number of attempts ‐‐><p>This is attempt number <%= attempts %> </p><!‐‐ begin form ‐‐><form name=quiz action=MarkTest.jsp><!‐‐ hidden values to store important information ‐‐><input type=hidden name=person value=<%= person%> /><input type=hidden name=quizname value=<%= uQuiz.getQuizName()%>/> Carrie Hall 7179881 - 30 -
  32. 32. <input type=hidden name=filename value=<%= quiz %> /><%while (i.hasNext()) //while there are questions{ Question question = (Question) i.next(); //get question int QuestionNumber = question.getQuestionNo(); //get question no %> <!‐‐ hidden question details ‐‐> <input type=hidden name=questionNo<%=qcount%> value=<%= QuestionNumber%>/> <input type=hidden name=questionVal<%=qcount%> value=<%= question.getQuestion()%> /> <!‐‐ prints question ‐‐> <h5><%= QuestionNumber + ". " + question.getQuestion()%></h5> <% //iterates through answers of that question Iterator j = uQuiz.getAnswers(question.getQuestionNo()).iterator(); /*tempcount is used to find the maximum number of answers that a question can have*/ int tempcount = 0; while (j.hasNext())//while there are answers { Answer answer = (Answer) j.next(); //get answer int AnswerNumber = answer.getAnswerNo(); //get answer number String answerString = answer.getAnswer();//get answer String %> <!‐‐ shows answers as radio buttons ‐‐> <input name=a<%=qcount%> id=a<%= qcount%> type=radio value=<%= AnswerNumber%> <% /*In order to ensure that the user does not forget to select an answer, the first item in each select box will be selected. */ if (tempcount==0) { %> checked <% } %> ></input><!‐‐ end of input ‐‐> <!‐‐ label for the answer ‐‐> <label for=a<%= qcount%>> <%= answerString%> </label> <br /> <% tempcount++; //increase tempcount } //end of while j.hasnext() //if tempcount > current maxNoOfAnswers then store as maxNoOfAnswers if (tempcount > maxNoOfAnswers) { maxNoOfAnswers = tempcount; } qcount++; //increase number of questions} //end while i.hasnext() loop%><!‐‐hidden values to store max num of answers and # of questions‐‐><input type=hidden name=anscount value=<%= maxNoOfAnswers%>/><input type=hidden name=qcount value=<%= qcount%> /> Carrie Hall 7179881 - 31 -
  33. 33. <br /><!‐‐ submit button ‐‐><input type=submit name=submit value=Submit /></form> <!‐‐ end form ‐‐></body></html> <% } //end if statement %> Carrie Hall 7179881 - 32 -
  34. 34. <!‐‐ page imports ‐‐> MarkTest.jsp<%@page import="java.util.Iterator" %><%@page import="java.util.Enumeration" %><%@page import="java.util.Date" %><%@page import="java.util.Calendar" %><%@page import="xmlquizpackage.*" %><%!/* method to redirect to the error page*/public void doError(HttpServletResponse res,HttpSession sess,String errorMsg){ try { sess.setAttribute("error", errorMsg); res.sendRedirect("error.jsp"); } catch (Exception e) { }}%><%//variablesint qcount = 0; //stores the number of questionsQuiz realQuiz = null; //stores the full quizQuiz temp = null; //stores the resubmitted quizQuiz userQuizToSave = null; //stores the users answersString errorMsg = ""; //stores an error messageString date; //stores a date//gets the filename and person name passed in through hidden variablesString person = request.getParameter("person"); //persons nameString filename = request.getParameter("filename"); //file nameif (session.getAttribute("attempts")==null) //if this is the first attempt{ session.setAttribute("attempts", 1); //increase to two attempts}if (session.getAttribute("person")==null) //if its not been set already{ session.setAttribute("person", person); //sets person session}if (session.getAttribute("date")==null) //if this is the first attempt{ date = "" + Calendar.getInstance().getTimeInMillis(); session.setAttribute("date", date); //increase to two attempts}else //increase by one{ date = session.getAttribute("date").toString();}String quiz = request.getParameter("quizname");/*The system tries to read an XML file which is created when a usersubmits a test and it is incorrect. If a file exists then realQuiz isoverwritten with the other quiz. This allows the test to getprogressively smaller as the quiz is resubmitted*/if (session.getAttribute("Quiz")!=null){ realQuiz = (Quiz) session.getAttribute("Quiz");}else Carrie Hall 7179881 - 33 -
  35. 35. { XMLReader x = new XMLReader(filename); realQuiz = x.getQuiz();}try{ //gets the total number of questions. qcount = Integer.parseInt(request.getParameter("qcount"));}catch (NumberFormatException e){ errorMsg += "Problem finding the number of questions<br />"; doError(response,session,errorMsg); //call method to redirect}if (!quiz.equals("")){ //makes a new quiz to store the incorrect answers temp = new Quiz(quiz); //makes a new quiz to store the answers that the user chose userQuizToSave = new Quiz(quiz);}else{ errorMsg += "Problem finding the number of questions<br />"; doError(response,session,errorMsg); //call method to redirect}for (int i = 0; i < qcount; i++) //loop through all questions{ //get question details int questionNo = Integer.parseInt(request.getParameter("questionNo" + i)); String question = request.getParameter("questionVal" + i); //stores a boolean to determine if answer is correct or not boolean correctAns = true; //get answer number selected by the user int answerNo = Integer.parseInt(request.getParameter("a" + i)); //the user entered the wrong answer so need to redisplay if (realQuiz.getCorrectAnswer(questionNo) != answerNo) { correctAns = false; } if (!correctAns) //the user entered the wrong answer { //save question to new test to redisplay temp.addQuestion(questionNo, question); //loop through answers for this question for (int k = 0; k < realQuiz.getAnswers(questionNo).size(); k++) { //get answer details int tempAnsNum = realQuiz.getAnswers(questionNo).get(k).getAnswerNo(); String tempAns = realQuiz.getAnswers(questionNo).get(k).getAnswer(); String tempType = realQuiz.getAnswers(questionNo).get(k).getType(); /* The user will not be shown their incorrect answer and so it should not be added to the new Quiz */ if (tempAnsNum != answerNo) { //adds the rest of the answers temp.addAnswer(questionNo, tempAnsNum, tempAns, tempType); } } Carrie Hall 7179881 - 34 -
  36. 36. } /*The answers to every question will be stored as an XML file*/ userQuizToSave.addQuestion(questionNo, question); //Only the answer number that the user submitted is known, so a loop through //all answers for the question is needed to find the rest of the details for (int k = 0; k < realQuiz.getAnswers(questionNo).size(); k++) { //get answer details int tempAnsNum = realQuiz.getAnswers(questionNo).get(k).getAnswerNo(); String tempAns = realQuiz.getAnswers(questionNo).get(k).getAnswer(); String tempType = realQuiz.getAnswers(questionNo).get(k).getType(); /* adds to user test */ if (tempAnsNum == answerNo) { //adds the answer userQuizToSave.addAnswer(questionNo, tempAnsNum, tempAns, tempType); } }}/*The quiz has been marked and two tests have been made, one contains all theincorrect questions with all answers other than the submitted answer, and theother contains each question and answer the user gave.*/if (temp.getQuestions().size() > 0) //the user has made mistakes{ if (session.getAttribute("attempts")==null) //if this is the first attempt { session.setAttribute("attempts", 2); //increase to two attempts } else //increase by one { session.setAttribute("attempts", 1+(Integer.parseInt(session.getAttribute("attempts").toString()))); } //writes an XML file with the users results. the file name is the quizname //and the persons name. To ensure uniqueness, a timestamp is also saved new XMLWriter(quiz + "_" + person + "_" + date + ".xml", userQuizToSave); session.setAttribute("Quiz", temp); session.setAttribute("filename", filename); //redirects to display the quiz again response.sendRedirect("showQuiz.jsp");}else //successful test{ //redirects to display a success message response.sendRedirect("success.jsp");} %> Carrie Hall 7179881 - 35 -

×