• No results found

Figure 5-4: Output screen of Test WML.java

Call.java (Listing 5-4) is called from TestWML.java. Further output depends on the choice entered by the user. If the choice entered is “1” it displays the list of cities for Weather Forecast, or if the choice entered is “2” the user is asked a question with multiple-choice answers.

Listing 5-4: Call.java

//© 2001 Dreamtech Software India Inc. //All Rights Reserved

1. import java.io.*;

2. import javax.servlet.http.*; 3. import java.util.*;

4) import java.sql.*;

5) public class Call extends HttpServlet

// declaration of the main class which extends the httpservlet 6. {

7) PrintWriter out; 8. String value; 9) Connection con; 10. ResultSet rs;

11. Vector name = new Vector(); 12. Statement s;

// Start of the servlet request

13. public void doGet(HttpServletRequest req, HttpServletResponse res) // start of the action class

14. { 15. try

// declaration of a block to catch exception 16. {

17. Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

18. con = DriverManager.getConnection ("jdbc:odbc:testservlet","",""); 19. s = con.createStatement();

20. }

21. catch(Exception se)

// catching the exception 22. {

23. System.out.println(se); 24. }

25. try

// definition of a new block for catching another exception 26. {

27. res.setContentType("text/vnd.wap.wml"); // Setting MIME type as WAP Document. 28. out = res.getWriter();

29. value = req.getParameter("choice");

// getting the value entered by the user in the field of the name // choice and storing the result in a string variable of the type value 30. out.println("<?xml version=\"1.0\"?>");

31._out.println("<!DOCTYPE wml PUBLIC\"" + "-//WAPFORUM//DTD WML 1.1//EN\" " + "\"http://www.wapforum.org/DTD/wml_1.1.xml\">");

// WML Prolog defination 32. out.println("<wml>");

// WML deck declaration 33. out.println("<head>");

34. out.println("<meta http-equiv=\"Cache-Control\" content=\"max-age=time\" forua=\"true\"/>");

// WML meta tag declaration 35. out.println("</head>"); 36. if (value.equals("1"))

//checking the value of variable passed from TestWML, // for Choice 1 i.e. Weather Report

37. {

38. rs = s.executeQuery("Select * from Weather"); //Querying from the weather table

39. int i = 0; 40. while(rs.next()) 41. { 42. name.add(i, rs.getString(2)); 43. i++; 44. }

45. out.println("<card id=\"CardA\" newcontext=\"true\">"); // WML card declaration

46. out.println("<onevent type=\"onenterforward\">");

// Defining the event type for the action to take place on submit button 47. out.println("<refresh>");

// refreshing the client memory

48. out.println("<setvar name=\"WChoice\" value=\"1\"/>"); // variable declaration

49. out.println("</refresh>"); 50. out.println("</onevent>");

51. out.println("<do type=\"accept\" label=\"Ok\">"); // WML event declaration

52. out.println("<go

href=\"http://localhost:8080/examples/servlet/report?WChoice=$WChoice\"/>"); // Calling the file report with the choice accepted by the user

53. out.println("</do>"); out.println("<p> The Choices of cities are"); 54. out.println("<select name=\"WChoice\">");

// Defining pull down list to show options for the city names stored in table

55. Enumeration e = name.elements(); 56. int h = 1;

57. while(e.hasMoreElements()) 58. {

59. out.println("<option value = \""+h+"\">" + (String)e.nextElement() + "</option>");

60. h++;

// Filling the pull down list options with the values taken from recordset 61. out.println("</select>");

// end of paragraph 63. out.println("</card>"); // End of WML card 64. out.println("</wml>"); // End of WML Deck 65. } 66. else

// The else part is to check If Choice entered in TestWML is // Question of the Day

67. {

68. rs = s.executeQuery("Select * from Question"); 69. int i = 0;

70. while(rs.next())

// browsing through the recordset 71. {

72. i++; 73. }

74. java.util.Date date = new java.util.Date(); 75. long time = date.getTime();

// defining date and time variables 78. int rem = (int)time/i;

79. int ij = 0;

// For random number generation 80. ij = (int)time-rem*i;

81. if (ij == 0) 82. {

83. ij = 5; 84. }

85. rs = s.executeQuery("Select * from Question");

// Adding data to recordset with the result obtained from query 86. int ai = 0;

87. String question = ""; 88. String qid = ""; 89. while(rs.next())

// browsing through the recordset 90. {

91. ai++;

92. if (ai == ij) 93. {

94. qid = rs.getString(1);

// Store the id of the question 95. question = rs.getString(2) ;

// Stores the question 96. }

97. }

98. rs = s.executeQuery("Select * from Answer"); // getting the result

99. Vector choices = new Vector(); 100.int index = 0;

101.while(rs.next())

// searching the question in the recordset on the // index value of Question ID

102.{

103.if (((String)rs.getString(1)).equals(qid)) 104.{

// to store the choices in the recordset on the basis of the id 106. index++;

107. } 108. }

109. out.println("<card id=\"CardC\" newcontext=\"true\">"); 110. out.println("<onevent type=\"onenterforward\">");

// Defining event type in WML 111. out.println("<refresh>");

112. out.println("<setvar name=\"QChoice\" value=\"1\"/>"); // setting the variable Qchoice and initialising it to 1. 113. out.println("</refresh>");

114. out.println("</onevent>");

115. out.println("<do type=\"accept\" label=\"Ok\">"); 116. out.println("<go

href=\"http://localhost:8080/examples/servlet/solution?QChoice=$QChoice*Qid="+q id+"

\"/>");

// A Call to the solution servlet with the Qchoice as a parameter // which will contain the option entered by the user, to check //whether the answer provided by the user is correct or not 117. out.println("</do>");

118. out.println("<p>"+question);

// Displaying the question on screen 119. out.println("<select name=\"QChoice\">");

// Creating pull down list by taking options from the recordset and // Displaying it on screen

120. Enumeration e = choices.elements(); 121. int h = 1;

122. while(e.hasMoreElements()) 123. {

124. out.println("<option value = \""+h+"\">" + (String)e.nextElement() + "</option>");

// Adding options into pull down list from the values in the recordset // and displaying it on screen

125. h++; 126. }

127. out.println("</select>"); // End of pull down list in WML 128. out.println("</p>"); 129. out.println("</card>"); // End of WML card 130. out.println("</wml>"); // End of WML Deck 131. } 132. } 133. catch(Exception ex)

// catching the exception & displaying it on screen 134. {

135. System.out.println( "Exception "+ex ); 136. }

137._} 138. }

Code Description

♦ Lines 1–4: Importing various packages used for the servlets to run. These include packages for the Input/Output operations, and servlet handling operation.

♦ Lines 5–13: A class is declared. This class is inherited from the base class HttpServlet and a method doGet is called which is responsible for sending the data back to the calling client program.

♦ Lines 17–19: Initializing the database driver — make a connection with the database and initialize the record set.

♦ Lines 27–28: Setting the content type as a text/WML document, which allows execution on a WAP-enabled device. Obtaining an object of the class PrintWriter. This is used to send the response to the client program.

♦ Line 29: Getting the choice entered by the user in TestWML.java.

♦ Line 30: Writing the response on the client program in the form of various WML tags.

♦ Lines 36-38: First the program checks whether the choice entered is 1 or 2. If it is 1, the Weather Report is generated and the database is queried for the names of all the cities for which information is available. If the choice entered is 2, the Question of the Day class is generated.

♦ Line 46: Event-handling routine for the event generated by the user for determining the weather of a particular city.

♦ Lines 54–63: Defining the pull-down menu to show the cities available after querying the database.

♦ Line 66: Question of the Day option is selected.

♦ Line 79: A random question is generated.

♦ Lines 80–114: Showing the question on-screen in a proper format.

♦ Line 116: Call to the solution servlet is made, which takes as a parameter the value entered by the user and matches it with results from the database.

♦ Lines 117–138:Exception handling and closing of the database connection is complete.

Code Output

Figure 5-5 shows what happens if choice 1 in Call.java is selected; Figure 5-6 shows what happens when choice 2 in Call.java is selected.

Figure 5-6: Question of the day

The Report.java program (Listing 5-5) displays the maximum and the minimum temperature of the cities by accessing the data from the MS Access database.

Listing 5-5: Report.java

//© 2001 Dreamtech Software India Inc. //All Rights Reserved

// importing the various java packages used by servlets 1. import javax.servlet.http.*;

2. import java.io.*; 3. import java.util.*; 4. import java.sql.*;

5. public class Report extends HttpServlet 6. {

// Declaration block defining variables and recordset 7. PrintWriter out;

8. String value; 9. Connection con; 10. ResultSet rs;

11. Vector name = new Vector(); 12. Statement s;

13. String temp_max = ""; 14. String temp_min = "";

// Declaration block for declaring string, connection and resultsets etc. 15. public void doGet(HttpServletRequest req, HttpServletResponse res)

16. { 17. try

// Begin of the try block for the exception checking 18. {

19. Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

20. con = DriverManager.getConnection("jdbc:odbc:testservlet","",""); // Setting up of the database connection

21. s = con.createStatement(); 22. }

23. catch(Exception se)

// catching the exception. If any while creating the database connection 24. { 25. System.out.println(se); 26. } 27. try 28. { 29. res.setContentType("text/vnd.wap.wml"); //setting up MIME type as WML page.

30. out = res.getWriter();

31. value = req.getParameter("WChoice");

// To store the value of variable wchoice passed from the calling program 32. int val = Integer.parseInt(value);

33. String city = "";

34. rs = s.executeQuery("Select * from Weather");

// Executing query to read all the records from table and store in recordset 35. while(rs.next()) 36. { 37. if (Integer.parseInt(rs.getString(1)) == val ) 38. { 39. city = rs.getString(2); 40. temp_min = rs.getString(3); 41. temp_max = rs.getString(4);

// Storing the city, minimum and maximum temp in local variables taken from //recordset having result passed through query from database

42. } 43. }

44. out.println("<?xml version=\"1.0\"?>");

45. out.println("<!DOCTYPE wml PUBLIC\"" + "-//WAPFORUM//DTD WML 1.1//EN\" " + "\"http://www.wapforum.org/DTD/wml_1.1.xml\">");

46. out.println("<wml>");

47. out.println("<card id=\"cardB\">"); // Declaration of card

48. out.println("<p align=\"center\">The temperatures at <b> "+city+" </b> are as follows </p>");

49. out.println("<p align=\"left\">Min. temp <b> "+temp_min+"</b></p>"); 50. out.println("<p align=\"left\">Max. temp <b> "+temp_max+"</b></p>");

// Displaying maximum and minimum temperature of various cities 51. out.println("</card>"); // End of card 52. out.println("</wml>"); // End of WML 53. } 54. catch(Exception e)

// catching the exception and displayimg it on the screen 55. {

56. System.out.println( e ); 57. }

58. }

// end of the program. 59. }

End of java code

Code Description

♦ Lines 1–4: Importing various packages used for the servlets to run. These packages include packages for the Input/Output operations and servlet handling operation.

♦ Lines 5–15: A class is declared. This class is inherited from the base class HttpServlet and a method doGet is called, which is responsible for sending the data back to the calling client program.

♦ Lines 19–21: Initializing the database driver — make a connection with the database and initialize the record set.

♦ Lines 29–30: Setting the content type as a text/WML document, which allows execution on a WAP-enabled device. Obtaining an object of the class PrintWriter. This is used to send the response to the client program.

♦ Line 31: Setting the choice entered by the user in Call.java.

♦ Line 35: Writing the response on the client program in the form of various WML tags.

♦ Line 34: When the user indicates the choice as 1, the list of all the cities for which the weather information is available is retrieved from the database and displayed.

♦ Line 50: Displaying the temperature along with the city name in a proper format to the user.

♦ Lines 51–59: Exception handling and closing the WML tags Output.

Code output

Figure 5-7 shows the output of Report.java.

Figure 5-7: Display of max and min temperature

Solution.java (Listing 5-6) compares the user’s answer to the question of the day with data from the Access database. It then displays a message indicating whether the user’s answer is correct or incorrect.

Listing 5-6: Solution.java

//© 2001 Dreamtech Software India Inc. //All Rights Reserved

1. import java.io.*;

2. import javax.servlet.http.*; 3. import java.util.*;

4. import java.sql.*;

// Importing the various java packages used by the servlets 5. public class solution extends HttpServlet

6. {

// Defining a servlet class based on HttpServlet. This class checks the //solution on the basis of the choices entered by the user.

// Variable declarations block 7. PrintWriter out;

8. String value; 9. String id; 10. Connection con; 11. ResultSet rs;

12. Vector name = new Vector(); 13. Statement s;

14. String temp_max = ""; 15. String temp_min = "";

// variable declarations

// The doGet() method of the servlet having request and response objects 17. {

18. try

// Begin of the try block for exception checking 19. {

20. Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

// Setting up the data base connection to access the data from the database 21. con = DriverManager.getConnection("jdbc:odbc:testservlet","",""); 22. s = con.createStatement(); 23. } 24. catch(Exception se) 25. { 26. System.out.println(se); 27. }

// End of the try block for the exception checking and displaying the name //of the exception

28. try

// Begin of the try block for the exception checking 29. {

30. res.setContentType("text/vnd.wap.wml"); // Setting up content MIME type as WML Page 31. out = res.getWriter();

32. value = req.getParameter("QChoice");

// Setting up variable value with the data of the variable Qchoice, received //from the calling program

33. id = value.substring(value.indexOf("=")+1); 34. value = value.substring(0,value.indexOf("*")); 35. System.out.println( value +" "+ id );

// Breaking the variable value into id and value where the delimiters are ‘=’ &

‘*’

36. boolean right = false;

37. rs = s.executeQuery("Select * from Answer");

// Matches the choices on the basis of question_id and answer supplied by //the user 38. while(rs.next()) 39. { 40. if (rs.getString(1).equals(id)) 41. { 42. if (rs.getString(2).equals(value)) 43. { 44. if (rs.getString(4).equals("r")) 45. { 46. right = true; 47. }

// Checking for the displayed question in the recordset and on finding the //question,

// the result entered by user is matched with the answer in the recordset, // if the answer matches, then the variable right is set to true else false, // which is later used for condition checking

48. } 49. } 50. }

51. out.println("<?xml version=\"1.0\"?>");

52. out.println("<!DOCTYPE wml PUBLIC\"" + "-//WAPFORUM//DTD WML 1.1//EN\" " + "\"http://www.wapforum.org/DTD/wml_1.1.xml\">");

// WML Prolog

53. out.println("<wml>"); 54. out.println("<head>");

55. out.println("<meta http-equiv=\"Cache-Control\" content=\"max-age=time\" forua=\"true\"/>");

// Definition of meta tag in WML 56. out.println("</head>");

//Generates a Card to show option entered by the users is correct or not 57. out.println("<card id=\"cardB\">");

58. if (right)

// Checking for Right or wrong answer in wml 59. {

60. out.println("<p align=\"left\">Your answer is right</p>"); // Displaying Right answer in wml

61. } 62. else

63. out.println("<p align=\"left\">Your answer is wrong</p>"); // Displaying wrong answer in wml

64. out.println("</card>"); // end of WML card 65. out.println("</wml>"); // end of WML Deck 66. } 67. catch(Exception e) 68. { 69. System.out.println( e ); 70. }

// End of the try block for the exception checking and displaying the name of //exception executed

71. } 72. }

Code Description

♦ Lines 1–4: Importing various packages used for the servlets to run. These packages include packages for the Input/Output operations, and servlet handling operation.

♦ Lines 5–15: A class is declared. This class is inherited from the base class HttpServlet and a method doGet is called, which is responsible for sending the data back to the calling client program.

♦ Lines 20–22: Initializing the database driver — make a connection with the database and initialize the record set.

♦ Lines 30–31: Setting the content type as a text/WML document, which allows the execution on a WAP-enabled device. Obtaining an object of the class PrintWriter. This is used to send the response to the client program.

♦ Line 32: Getting the choice entered by the user in Call.java.

♦ Line 35: Writing the response on the client program in the form of various WML tags.

♦ Lines 38–47: Checking for the displayed question in the recordset, and on finding the question, the answer entered by the user is matched with the answer in the recordset. If the answer matches, then the variable ‘right’ is set to true.

♦ Lines 51–60: Displaying to the user whether the answer is right or wrong.

Output

Figure 5-8 shows the output of Solution.java.

Figure 5-8: Display of the correct option