Hi I'm creating a quiz application in jsp and am using different jsp pages for every question. I'd like to keep a score after each question is answered. My problem is that I'm picking random answers from a database, within which lies the correct answer too. Since I can't guess which letter the correct answer will appear on, could you suggest what I should do? I am posting the first and second question jsp's to give you an idea of how I'm doing it:
q1.jsp
<%#page import="java.util.Random"%>
<%#page import="java.util.ArrayList"%>
<%#page import="org.me.jsp.beans.WordBean"%>
<%#page import="java.util.List"%>
<!--This JSP acts as the first question in a multiple choice quiz, with the user
asked to submit their answer to the question-->
<?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<jsp:useBean id = "wordData" scope = "request"
class = "org.me.jsp.beans.WordDataBean" />
<html>
<head>
<title>Big Java Quiz, question 1</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<%if (request.getParameter("choice").equals("N")) {
out.print("<meta http-equiv='refresh' content='0;url=options.jsp'/>");
}
//Redirects user back to index if they did not want to take quiz%>
<form action="q2.jsp" method="POST">
<%
List<WordBean> wordList = wordData.getWordList();
List<String> answersList = new ArrayList<String>();
Random random = new Random();
Random forAnswers = new Random();
WordBean goodOne = wordList.get(random.nextInt(wordList.size()));
//take it out from the list
wordList.remove(goodOne);
//add it to the answers list
answersList.add(goodOne.getGermanName());
WordBean fakeOne = wordList.get(random.nextInt(wordList.size()));
//take it out from the list
wordList.remove(fakeOne);
//add it to the answers list
answersList.add(fakeOne.getGermanName());
WordBean fakeTwo = wordList.get(random.nextInt(wordList.size()));
//take it out from the list
wordList.remove(fakeTwo);
//add it to the answers list
answersList.add(fakeTwo.getGermanName());
%>What is the English word for the German word <%=goodOne.getEnglishName()%>?<br>
<%
char letter = 'A';
for (String answer : answersList) {
%>
<input type="radio" name="q1Answer" value=""/><label for="<%=letter%>"><%=letter%>)<%=answersList.get(forAnswers.nextInt(3))%> />
<% //point to the next letter
letter++;
}
%>
<input type="submit" value="Submit"/>
</form>
</body>
</html>
q2.jsp
<%--
Document : q2
Created on : 06-May-2012, 18:54:32
Author : encore
--%>
<!--This JSP acts as the second question in a multiple choice quiz, with the user
asked to submit their answer to the question-->
<?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Big Java Quiz, question 2</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<%int score = 0;
if(request.getParameter("q1Answer").equals("C"))
score++; //Increments score if answer submitted was correct%>
<form action="q3.jsp" method="POST">
Your current score is: <%out.print(score);%>/20
<input type="hidden" name="q2Score" value="<%out.print(score);%>"/>
<!--Hidden button allows score to be accessed by next JSP-->
<b>Question 2.</b> When an exception is generated it is said to have been _________?<br/><br/>
<input type="radio" name="q2Answer" value="A"/><label for="A">A) Built</label><br/>
<input type="radio" name="q2Answer" value="B"/><label for="B">B) Thrown</label><br/>
<input type="radio" name="q2Answer" value="C"/><label for="C">C) Caught</label><br/>
<input type="radio" name="q2Answer" value="D"/><label for="D">D) Detected</label><br/><br/>
<input type="submit" value="Submit"/>
</form>
</body>
</html>
Note: the form of the second question will obviously be changed to something else, currently I'm concentrating on getting the score .
In the page for Q1, where you should know the correct answer, put it in the session and then retrieve it in the next page.
Related
I want to passing a java String variable to the javascript function parameter using jsp expression tag.Below is my jsp page.
First.jsp
<!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=ISO-8859-1">
<title>Insert title here</title>
<script>
function stringGenerate(str){
var x = document.getElementsByTagName("input");
x[0].value = str;
}
function numberGenerate(num){
var x = document.getElementsByTagName("input");
x[1].value = num;
}
</script>
</head>
<body>
<%
String num ="1234567890";
String str = "abcdefghij";
%>
<input type="text" name="string" readonly="readonly"/>
<input type="text" name="number" readonly="readonly"/><br/><br/>
<input type="button" value="String Generate" onclick= "stringGenerate(<%=str %>)" />
<input type="button" value="Number Generate" onclick= "numberGenerate(<%=num %>)" />
</body>
</html>
When I click on the button with value "Number Generate",then the num variable value(1234567890) will display on the textbox(name="number") but when I click on the button with value "String Generate",then there is nothing display on the corresponding text box(name="string").Here both num and str are string type varible but why only num variable value is displayed on textbox and why not str variable value is displayed?
Try using single quote ' when using string in HTML:
onclick= "stringGenerate('<%=str %>')"
^ ^
Full Code:
<input type="button" value="String Generate" onclick= "stringGenerate('<%=str %>')" />
The reason is that when the page is rendered by the browser, it puts the str and num values directly in the code, so it looks like:
<input type="button" value="String Generate" onclick="stringGenerate(abcdefghij)"/>
The browser basically thinks you're trying to reference a Javascript variable called 'abcdefghij'.
You should add the ' chars before and after your string text to let javascript know it should use the value of that text and not search for a variable with that name.
The declaration of str should look like this to make it work:
String str = "\'abcdefghij\'";
Please note, you can't use \" to escape as this would break your code.
This is my JSP page:
<%--
Document : new jsp1
Created on : Nov 24, 2014, 12:38:07 PM
Author : Java
--%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<%
String msg="206_John_help i m in trouble,delhi,อินเดีย_30.64741430_76.817313799";
String result = java.net.URLEncoder.encode(msg, "UTF-8");
System.out.println("The msg is "+result);
String result1=java.net.URLDecoder.decode(result, "UTF-8");
System.out.println("The decoded msg is "+result1);
%>
</body>
</html>
The output is 206_John_help i m in trouble,delhi,???????_30.64741430_76.817313799
I am always getting ?????? instead of thai alphabets. How can I get the Thai alphabets while decoding?
The problem is not on encoding and decoding the messages but in the server container. Seems that server cant display properly the special characters, so it can not treat them from request.
If you display the values in the JSP page itself, everything is working fine.
Example:
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<%
String msg="206_John_help i m in trouble,delhi,อินเดีย_30.64741430_76.817313799";
System.out.println("The original message "+msg);
String result = java.net.URLEncoder.encode(msg, "UTF-8");
System.out.println("The msg is "+result);
String result1=java.net.URLDecoder.decode(result, "UTF-8");
System.out.println("The decoded msg is "+result1);
%>
Original message <%=msg %><br />
Encrypted message <%=result %> <br />
Decrypted message <%=result1 %>
</body>
</html>
I get an String array from session and I want to show the String from the array.
I know javascript can't get data from session directly. Is there any method I can get the data from session and transfer it to javascrip?
My code as follows:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%String[] sele = (String[])session.getAttribute("selections");%>;
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<meta http-equiv="Expires" content="0">
<meta http-equiv="kiben" content="no-cache">
<title>Check List</title>
<script language="javascript" type="text/JavaScript" src="cookie.js">
</script>
<script text="text/javascript">
{
var selections = //String array form session
for(var v=0;v<selections.length;v++){
fillForm(selections[v]);
}
}
function fillForm(name){
var checkbox= document.createElement("input");
checkbox.type="checkbox";
checkbox.name=name;
checkbox.value=name;
checkbox.id=name;
var label = document.createElement("label");
label.htmlFor="id";
label.appendChild(document.createTextNode(name));
var container = document.getElementById("checklist");
container.appendChild(checkbox);
container.appendChild(label);
container.appendChild(document.createElement("br"));
}
function submitAction(){
addUserName(document.getElementById("checklist"));
var elem = document.getElementById("checklist").elements;
for(i =0;i<elem.length;i++){
elem[i].checked = true;
}
var form = document.getElementById("checklist");
form.submit();
}
</script>
</head>
<body>
<form id="checklist" action="selection">
</form>
<Button type="button" onclick="submitAction()" name="submit">Submit</button>
</body>
</html>
Simply use JSP Expression Language and JSP JSTL
<script>
alert("value: ${selections}");
</script>
Here selections is an attribute that is set in any scope page, request, session or application.
You can directly access an attribute form session scope:
{sessionScope.selections}
Note: I don't know that Java ArrayList does work in JavaScript as well. If it doesn't work then simply set a comma separated string as session attribute and split it in JavaScript as shown below.
Sample code:
<script>
var selections = "${sessionScope.csv}".split(",");
for ( var v = 0; v < selections.length; v++) {
alert(selections[v]);
}
</script>
Here csv is a comma separated string value that is set in session scope.
Use JSP JSTL and EL instead of Scriplet that is more easy to use and less error prone.
You can achieve it in JSTL without using JavaScript. Simply iterate the list using <c:forEach> tag and add that much of check boxes and labels.
Sample code:
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
...
<body>
...
<c:forEach items="${selections }" var="name">
<input type="checkbox" name="${name}" value="${name}" id="${name}">
...
</c:forEach>
</body>
Please have a look at the below code
<%--
Document : index
Created on : Feb 7, 2014, 1:03:15 PM
--%>
<%#page import="java.util.Map"%>
<%#page import="java.util.Iterator"%>
<%#page import="analyzer.DataHolder"%>
<%#page import="java.util.ArrayList"%>
<%#page import="java.util.List"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1><center>Web Site Analizer</center></h1>
<br/>
<form action=http://localhost:8080/WebSiteAnalizer/SiteAnalizer method=post>
Enter the Percentage (0-100): <input type="Text" name="percentage">
<br/><br/><br/>
Enter the Words (Separated from New Line (/n)): <br/>
<textarea name='wordList' value='wordList'></textarea>
<br/><br/>
<input type="submit" value="Submit">
</form>
<%#page import="java.util.List" %>
<%#page import="java.util.ArrayList" %>
<%#page import="java.util.HashMap" %>
<%
List<DataHolder> dataHolder = (ArrayList)request.getAttribute("list");
HashMap hashMap = (HashMap)request.getAttribute("wordMap");
if(hashMap==null)
{
out.println("Hashmap null");
}
if(dataHolder!=null && dataHolder.size()>0)
{
out.println("</br>");
out.println("<table border='1'><th>Primary Key</th><th>Original Hash</th><th>Matching Words</th><th>Non Matching words</th>");
for(int i=0;i<dataHolder.size();i++)
{
DataHolder d = dataHolder.get(i);
int primaryKey = d.getPrimaryKey();
String originalHash = d.getOriginalHash();
ArrayList matchingWords = d.getMatchingWords();
ArrayList unMatchingWords = d.getUnmatchingWords();
StringBuffer matchingWordsStr = new StringBuffer("");
StringBuffer unMatchingWordsStr = new StringBuffer("");
//Populating Strings
for(int m=0;m<matchingWords.size();m++)
{
Iterator iter = hashMap.entrySet().iterator();
while(iter.hasNext())
{
Map.Entry mEntry = (Map.Entry)iter.next();
if(mEntry.getValue().equals(matchingWords.get(m)))
{
//out.println(matchingWords.get(m)+" : "+true);
matchingWordsStr.append(mEntry.getKey());
matchingWordsStr.append(",");
}
}
}
for(int u=0;u<unMatchingWords.size();u++)
{
Iterator iter = hashMap.entrySet().iterator();
while(iter.hasNext())
{
Map.Entry mEntry = (Map.Entry)iter.next();
if(mEntry.getValue().equals(unMatchingWords.get(u)))
{
//out.println(matchingWords.get(m)+" : "+true);
unMatchingWordsStr.append(mEntry.getKey());
unMatchingWordsStr.append(",");
}
}
}
out.println("<tr>");
out.println("<td>");
out.println(String.valueOf(primaryKey));
out.println("</td>");
out.println("<td>");
out.println(originalHash);
out.println("</td>");
out.println("<td>");
out.println(matchingWordsStr);
out.println("</td>");
out.println("<td>");
out.println(unMatchingWordsStr);
out.println("</td>");
out.println("</tr>");
}
out.println("</table>");
}
%>
</body>
</html>
This code generates a table, but it is really huge, which means the width is too much to fit to the screen. The reason for that is, the String values this code enters into the columns are very lengthy. May be 5000 to 10000 words and everything in one column is being displayed in one line. For an example, if "Original Hash" is 10000 characters, then the entire thing is displayed in one line. So is there anyway that I can make the length of this make suit for the screen?
Also please note that I am a developer and not a designer. I very rarely work on scripting languages.
use this css to break the really long word-
td{
word-wrap:break-word;
}
You may need to also set the table-layout to fixed see Set the table column width constant regardless of the amount of text in its cells?. Also for performance you probably want to change it from individual printlns to single a println that takes a string of all your html.
I have a Java Server Page that lets the user pick a number of their choice from 1-1000. The page then uses the number entered and finds out if the number matches the number that is generated. -- Pictures below if ^ is unclear. Currently, the program generates a different number each time the user guesses a number -- whether it is correct or not. How do I make it so that the program only generates a number when the user either refreshes the page or guesses correctly?
JSP code:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%# page import = "Chapter12.RandomGuess" %>
<jsp:useBean id = "randomGuessId" class = "Chapter12.RandomGuess" scope = "page" >
</jsp:useBean>
<jsp:setProperty name = "randomGuessId" property = "*" />
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Guess Random Number</title>
</head>
<body>
<h3>Guess a number from 1 to 1000</h3>
<form method = "post">
Enter guess: <input name = "guess" /><br /><br />
<input type = "submit" name = "Submit" value = "Take Guess" />
<input type = "reset" value = "Reset" /><br /><br />
Your guess of <jsp:getProperty name = "randomGuessId" property="guess" />
is <%= RandomGuess.guess(randomGuessId.getAnswer()) %>
</form>
</body>
</html>
Java code:
import java.util.Random;
public class RandomGuess {
private int guess;
Random r = new Random();
private int low = 1;
private int high = 1000;
int R = r.nextInt(high-low) + low;
public int getGuess() {
return guess;
}
public void setGuess(int newValue) {
guess = newValue;
}
public String getAnswer() {
String tooLow = "too low.";
String tooHigh = "too high.";
String correct = "correct!";
if(guess == R)
return correct;
else if(guess < R)
return tooLow;
else
return tooHigh;
}
public static String guess(String s) {
return s;
}
}
picture: http://i.imgur.com/dMSZ7SD.png
Every time the page refreshes, a new instance of the bean is created - with a new number.
To preserve the number across calls, use a static field in your class.
Better yet, use JavaScript!
Find complete program here:http://sickprogrammersarea.blogspot.in/2014/01/creating-number-guesser-in-jsp_8296.html
Hello friends this is a simple program of creating a number guesser in JSP....Have a look...
Number.jsp:
<html>
<head><title>Number Guesser</title></head>
<body>
<% int num=(int)(Math.random()*100); %>
<h2>Welcome To Number Guesser</h2>
<br><h3>Want To Check Your Guessing Power.....GIVE IT A TRY?????</h3>
<form name="guess" action="try.jsp?c=0" method="post">
<input type="text" name="val" value="<%=num %>" hidden>
<input type="submit" value="GO">
</form>
</body>
</html>
try.jsp :
<html>
<head><title>Number Guesser</title></head>
<body>
<% String str=request.getParameter("val");
boolean flag=true;
int num=Integer.parseInt(str);
int c=Integer.parseInt(request.getParameter("c"));
if(c!=0)
{
int guess=Integer.parseInt(request.getParameter("guess"));
if(num==guess){
flag=false;
%>
<h3>Congratulation...You Successes After <%=c%> attempts</h3>
<b>Want to Improve...try again</b>
<% }else if(num>guess) { %>
<h3>You Guessed Lower...Try Bigger Number</h3>
<% }else{ %>
<h3>You Guessed Higher...Try Smaller Number</h3>
<% }
}
if (flag) { c++; %>
<h3>I Guessed a Number between 1 to 100. Try To Guess..</h3>
<form name="guess" action="try.jsp?c=<%= c%>" method="post">
<input type="text" value="<%=num %>" name="val" hidden>
Make Your Guess : <input type="text" name="guess" size=10 maxlength=3>
<input type="submit" value="GO">
</form>
<% } %>
</body>
</html>
You could pass the user number back as a query parameter.
I'm guessing you are not too familiar with the MVC pattern or Spring, but there are plenty of resources available to get you quickly up and running. I'll try to make a strip down demo later, if I remember.