JSP User Hit Counter - java

I am trying to count how many times each user enters the website, but my problem is that even though I change the user name, the hit count doesn't restart. Also, once I reload the webpage, the the name of the user becomes "null".
<HTML>
<BODY>
<FORM METHOD=POST ACTION="SaveName.jsp">
Who are You ? <INPUT TYPE=TEXT NAME=username SIZE=20>
<P><INPUT TYPE=SUBMIT>
</FORM>
</BODY>
</HTML>
<%# page import="java.io.*,java.util.*" %>
<html>
<head>
<title>Applcation object in JSP</title>
</head>
<body>
<%
String name = request.getParameter( "username" );
session.setAttribute( "theName", name );
Integer hitsCount =
(Integer)application.getAttribute("hitCounter");
if( hitsCount ==null || hitsCount == 0){
/* First visit */
out.println("Welcome to my website! ");
hitsCount = 1;
}else{
/* return visit */
out.println("Welcome back to my website!");
hitsCount += 1;
}
application.setAttribute("hitCounter", hitsCount);
%>
<%= session.getAttribute( "theName" ) %>
<br>Total number of visits: <%= hitsCount%></br>
</body>
</html>

In Your JSP
<%!
Map<String,Integer> userCountMap = new HashMap<String,Integer>();
Integer hitsCount=0;
String key;
%>
<%
String name = request.getParameter( "username" );
if(name!=null && !"".equals(name)){
key=name.toLowerCase();
if(userCountMap.get(key)!=null){
/* return visit */
out.println("<h3>"+name+"</h3> Welcome back to my website!");
hitsCount = userCountMap.get(key);
hitsCount+=1;
}else{
out.println("<h3>"+name+"</h3> Welcome to my website!");
hitsCount=1;
}
userCountMap.put(key, hitsCount);
}
%>

Are you storing the hit counts per user or you are storing just the hit counts?
In the former case, you can use a map that will check whether there is an entry for a specific user in the map. If entry is found, increase the counter by 1, if entry is not found, then create a new entry and set corresponding counter to 1.
In the later case, all you need to do is increase the counter every time the website is hit.

Related

Exception Occured java.lang.NumberFormatException: null

I am getting following error in JSP page
SELECT * FROM books WHERE id =1001
Exception Occuredjava.lang.NumberFormatException: null
while running below code.
I doubt this is due to
input type='text' size='3' value='1' name='qty'<%=id% in JSearch.jsp is not properly linked to
int qtyOrdered = Integer.parseInt(request.getParameter("qty"+id)); in JOrder.jsp.
Can any one please help me on this.
Code: JSearch.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%# page import = "java.sql.*" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Search Page</title>
</head>
<body>
<% try {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn = DriverManager.getConnection ("jdbc:oracle:thin:#//XXXXX.XXX:1521/xe", "sai", "harisai");
Statement stmt=conn.createStatement();
// Retrieve and process request parameters: "author" and "search"
String author = request.getParameter("author");
boolean hasAuthorParam = author != null && !author.equals("Select...");
String searchWord = request.getParameter("search");
boolean hasSearchParam = searchWord != null && ((searchWord = searchWord.trim()).length() > 0);%>
<h2>Query Results</h2>
<%if (!hasAuthorParam && !hasSearchParam) { %> <%--No params present--%>
<h3>Please select an author or enter a search term!</h3>
<p><a href='Entryscreen.jsp'>Back to Select Menu</a></p>
<% }
else {
// Form a SQL command based on the param(s) present
StringBuilder sqlStr = new StringBuilder(); // more efficient than String
sqlStr.append("SELECT * FROM books WHERE qty > 0 AND (");
if (hasAuthorParam) {
sqlStr.append("author = '").append(author).append("'");
}
if (hasSearchParam) {
if (hasAuthorParam) {
sqlStr.append(" OR ");
}
sqlStr.append("author LIKE '%").append(searchWord)
.append("%' OR title LIKE '%").append(searchWord).append("%'");
sqlStr.append(") ORDER BY author, title");
}//
out.println(sqlStr); // for debugging
ResultSet rset = stmt.executeQuery(sqlStr.toString());
if (!rset.next()) { %> <%--// Check for empty ResultSet (no book found)--%>
<h3>No book found. Please try again!</h3>
<p><a href='start'>Back to Select Menu</a></p>
<%}
else {%>
<%--// Print the result in an HTML form inside a table--%>
<form method='get' action='JOrder.jsp'>
<table border='1' cellpadding='6'>
<tr>
<th> </th>
<th>AUTHOR</th>
<th>TITLE</th>
<th>PRICE</th>
<th>QTY</th>
</tr>
<%-- // ResultSet's cursor now pointing at first row--%>
<% do {
// Print each row with a checkbox identified by book's id
String id = rset.getString("id");%>
<tr>
<td><input type='checkbox' name='id' value='<%=id%>' /></td>
<td><%=rset.getString("author")%></td>
<td><%=rset.getString("title")%></td>
<td>$<%=rset.getString("price")%></td>
<td><input type='text' size='3' value='1' name='qty'<%=id%>/></td>
</tr>
<%} while (rset.next()); %>
</table><br/>
<%--// Ask for name, email and phone using text fields (arranged in a table)--%>
<table>
<tr><td>Enter your Name:</td>
<td><input type='text' name='cust_name'/></td></tr>
<tr><td>Enter your Email (user#host):</td>
<td><input type='text' name='cust_email' /></td></tr>
<tr><td>Enter your Phone Number (8-digit):</td>
<td><input type='text' name='cust_phone' /></td></tr></table><br />
<%-- // Submit and reset buttons--%>
<input type='submit' value='ORDER' />
<input type='reset' value='CLEAR' /></form>
<%
}
}
}
catch (Exception e){
out.println("Exception Occured:" +e);
} %>
</body>
</html>
Code:
JOrder.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%# page import = "java.sql.*" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Order Confirmation</title>
</head>
<body>
<h1>Order Confirmation</h1>
<% try {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn = DriverManager.getConnection ("jdbc:oracle:thin:#//XXXXX.XXX.LOCAL:1521/xe", "sai", "harisai");
Statement stmt=conn.createStatement();
// Retrieve and process request parameters: id(s), cust_name, cust_email, cust_phone
String[] ids = request.getParameterValues("id"); // Possibly more than one values
String custName = request.getParameter("cust_name");
boolean hasCustName = custName != null && ((custName = custName.trim()).length() > 0);
String custEmail = request.getParameter("cust_email").trim();
boolean hasCustEmail = custEmail != null && ((custEmail = custEmail.trim()).length() > 0);
String custPhone = request.getParameter("cust_phone").trim();
boolean hasCustPhone = custPhone != null && ((custPhone = custPhone.trim()).length() > 0);
// Validate inputs
if (ids == null || ids.length == 0) {%>
<h3>Please Select a Book!</h3>
<% } else if (!hasCustName) {%>
<h3>Please Enter Your Name!</h3>
<% } else if (!hasCustEmail || (custEmail.indexOf('#') == -1)) {%>
<h3>Please Enter Your e-mail (user#host)!</h3>
<%} else if (!hasCustPhone || (custPhone.length() != 8)) {%>
<h3>Please Enter an 8-digit Phone Number!</h3>
<%} else {%>
<%--// Display the name, email and phone (arranged in a table)--%>
<table>
<tr><td>Customer Name:</td><td><%=custName%></td></tr>
<tr><td>Customer Email:</td><td><%=custEmail%></td></tr>
<tr><td>Customer Phone Number:</td><td><%=custPhone%></td></tr></table>
<%--// Print the book(s) ordered in a table--%>
<br/>
<table border='1' cellpadding='6'>
<tr><th>AUTHOR</th><th>TITLE</th><th>PRICE</th><th>QTY</th></tr>
<% float totalPrice = 0f;
for(String id : ids) {
String sqlStr = "SELECT * FROM books WHERE id ="+ id;
out.println(sqlStr);
// for debugging
ResultSet rset = stmt.executeQuery(sqlStr);
rset.next();
int qtyAvailable = rset.getInt("qty");
String title = rset.getString("title");
String author = rset.getString("author");
float price = rset.getFloat("price");
int qtyOrdered = Integer.parseInt(request.getParameter("qty"+id));
sqlStr = "UPDATE books SET qty = qty -"+ qtyOrdered +" WHERE id =" + id;
out.println(sqlStr); // for debugging
stmt.executeUpdate(sqlStr);
sqlStr = "INSERT INTO ORDER_RECORDS VALUES ("+ id + ", " + qtyOrdered + ", '" + custName + "', '"
+ custEmail + "', '" + custPhone + "')";
out.println(sqlStr); // for debugging
stmt.executeUpdate(sqlStr);%>
<%-- // Display this book ordered--%>
<tr>
<td><%=author%></td>
<td><%=title%></td>
<td><%=price%></td>
<td><%=qtyOrdered%></td></tr>
<% totalPrice += price * qtyOrdered;
}%>
<tr><td colspan='4' align='right'>Total Price: $
</td> <%out.println(totalPrice);%> </tr>
</table>
<h3>Thank you.</h3>
<%out.println("<p><a href='JEntryScreen.jsp'>Back to Select Menu</a></p>");
}
}
catch (Exception e) {
out.println("Exception Occured" +e);
}
finally {
}%>
</body>
</html>
What is a NumberFormatException?
Thrown to indicate that the application has attempted to convert a string to one of the numeric types, but that the string does not have the appropriate format.
-[Documentation][2]
NumberFormatException extends IllegalArgumentException. It tells us that it's more specialized IllegalArgumentException. Indeed, it's used for highlighting that although, the argument type was correct (String) the content of the String wasn't numeric (a,b,c,d,e,f are considered digits in HEX and are legal when needed).
Ad. 2.
When you see, that instead of "For input string:" and the input, there is a null (not "null") it means, that you tried to pass the null reference to a number. If you actually want to treat is as 0 or any other number, you might be interested in my another post on StackOverflow. It's available [here][3].
The description of solving unexpected nulls is well described in a topic [What is a NullPointerException and how can I fix it?][4].
The answer is taken from this topic - I couldn't mark it as a duplicate because I have raised another flag before the question was edited.

Calling a JSP Function from another jsp file

I have create a simple application on jsp..
In my global function jsp file, I have created functions as follows:
<%! public double calcB(double w, double h){
double B = 0;
return B = (w / (h * h));
}
public String calcClassif(double B){
String classifi = null;
if(B >= 30)
classif = "Obese";
else if(B >= 25)
classif = "Overweight";
else if(B >= 18.5)
classif = "Normal";
else
classif = "Underweight";
return classif;
}
%>
Now in my my index.jsp file, I have written the following:
<%#include file = "globalFunctions.jsp" %>
<% Boolean submitted = Boolean.parseBoolean(request.getParameter("isSubmitted"));
double we = 0, he = 0;
if(submitted){
weight = Double.parseDouble(request.getParameter("w"));
height = Double.parseDouble(request.getParameter("h"));
}
%>
<h3>BMI Calculator</h3>
<form action = "index.jsp" method = "post">
<input type ="hidden" name = "isSubmitted" value = "true">
Weight: <input type = "text" name = "w"> <br> <br>
Height: <input type = "text" name = "h"> <br> <br>
<input type = "submit" value = "Compute"> <br> <br>
BMI: <%= calcBMI(we, he) %> <br> <br>
Classification: <%= classification %>
</form>
When I execute the application, the classification is not working.. How do I call the method to display me the correct classification ?
Please help.. Thanks
You are never assign a value into classification. You may try this:
<%#include file = "globalFunctions.jsp" %>
<% Boolean submitted = Boolean.parseBoolean(request.getParameter("isSubmitted"));
double we = 0, he = 0;
if(submitted){
weight = Double.parseDouble(request.getParameter("w"));
height = Double.parseDouble(request.getParameter("h"));
bmi = calcBMI(we, he);
classification = calcClassif(bmi);
}
%>
<h3>BMI Calculator</h3>
<form action = "index.jsp" method = "post">
<input type ="hidden" name = "isSubmitted" value = "true">
Weight: <input type = "text" name = "w"> <br> <br>
Height: <input type = "text" name = "h"> <br> <br>
<input type = "submit" value = "Compute"> <br> <br>
BMI: <%= bmi %> <br> <br>
Classification: <%= classification %>
</form>
Whenever your JSP is compiled by your servlet container, it is compiled under different names every time. This makes it hard to use a JSP page function in another JSP page. I would recommend you to start using servlets and POJOs for your data processing needs.
Anyway, you don't have any variable named classification (index.jsp:21), therefore it is not displayed and the server logs an error to the console, and not to the client like PHP.

Table width is too much

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.

Java Login JSP Page (Uses Access Database)

I have a Java login application that works and uses a microsoft access database to validate login details. I'm currently in the process of building a java web application and I'm just trying to implement code from my working example.
My problem is that I have 2 input fields here for username and password, (called "name" and "password") But my SQL code which works in the previous example cannot detect the fields on this page called name and password, where the user would input their details respectively.
Any help would be much appreciated!
<%#page import="javax.swing.JOptionPane"%>
<%#page import="java.sql.Connection"%>
<%#page import="java.sql.Statement"%>
<%#page import="java.sql.ResultSet"%>
<%#page import="java.sql.DriverManager"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Angels & Demons</title>
Home Page
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<h1><center>Login</center></h1>
<center><form action="login.jsp">
<h2>Please make sure to fill all fields! </h2>
<table>
<tr><td>User:<input name="name" type="text" size="10"></td></tr>
<tr><td>Password:<input name="password" size="10"></td></tr>
<td><input type="submit" value="Submit"></input></td>
</table>
</center>
<%
if ((request.getParameter("name") != null )
&& (request.getParameter("password") != null )
)
{
Connection conn = null;
Statement st = null;
ResultSet rs;
try{
String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
Class.forName(driver);
String db = "jdbc:odbc:AngelsAndDemons";
conn = DriverManager.getConnection(db);
st = conn.createStatement();
String sql = "select user,pass from AngelsAndDemons where user = '"+name+"'and pass = '"+password+"'";
rs = st.executeQuery(sql);
int count = 0;
while(rs.next())
{
count = count + 1;
}
if(count == 1)
{
JOptionPane.showMessageDialog(null,"User found, Access Granted!");
}
else if(count > 1){
JOptionPane.showMessageDialog(null,"Duplicte User, Access Denied");
}
else{
JOptionPane.showMessageDialog(null,"User not found");
}
}
catch(Exception ex)
{
}
}
%>
There was Problem in Login.
<%
%>
}
</form>
</body>
</html>
There are two problems in your code..
1) You want your java code to be executed on button click..so you should check for button click and then write code within it as:
<input type="submit" value="Submit" name="bt"></input></td> //Define a name for button
<%
if(request.getParameter("bt")!=null)
{
if ((request.getParameter("name") != null )
&& (request.getParameter("password") != null ))
{
//your code
}
}
%>
2) You have not stored your username and password in any variable and still accessing them in your query by using the name of your text field which is wrong..Save them in a variable and use that variable in the query as :
String name= request.getParameter("name");
String pass= request.getParameter("password");
String sql = "select user,pass from AngelsAndDemons where user = '"+name+"'and pass = '"+pass+"'";
Do not concatenate Strings. Used PreparedStatements to avoid SQL injection.
Also avoid storing passwords on String variables. Use char[] when possible, and wipe it after using it, to avoid leaving a cleartext password on memory.
Congrats on trying web server development.
First a corrected version.
<%#page contentType="text/html" pageEncoding="UTF-8"
import="java.sql.*"
import="javax.sql.*"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Angels & Demons</title>
Home Page
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<h1><center>Login</center></h1>
<%
String name = request.getParameter("name");
String password = request.getParameter("password");
if (name == null || password == null) {
%>
<center>
<form action="login.jsp" method="POST">
<h2>Please make sure to fill all fields! </h2>
<table>
<tr><td>User:<input name="name" type="text" size="10"></td></tr>
<tr><td>Password:<input name="password" size="10"></td></tr>
<td><input type="submit" value="Submit"></input></td>
</table>
</center>
</form>
<%
} else {
String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
Class.forName(driver);
String db = "jdbc:odbc:AngelsAndDemons";
try (Connection conn = DriverManager.getConnection(db)) {
String sql = "select count(*) from AngelsAndDemons where user = ? and pass = ?";
try (PreparedStatement st = conn.prepareStatement(sql)) {
st.setString(1, user);
st.setString(2, password);
try (ResultSet rs = st.executeQuery()) {
int count = 0;
if (rs.next()) {
count = rs.getInt(1);
}
if(count == 1) {
%><h2>User found, Access Granted!</2><&
} else if(count > 1) {
%><h2>Duplicate User, Access Denied</2><&
} else {
%><h2>Duplicate User, Access Denied</2><&
}
}
}
} catch (Exception ex) {
%><h2>There was Problem in Login.</2>
<p><%= ex.getMessage() %></p>
<&
}
}
%>
</body>
</html>
With the imports I was a bit lazy and used * - which is bad style.
The page is delivered on a browser request (HTTP GET) back to the browser, the client.
No parameters were in the request, so the form is output.
After the form is submitted by the browser, here as HTTP POST request,
there are parameters.
Now a database query can be done.
Try-with-resources ensure that all is closed (connection, prepared statement and result set). Even on return/break/exception.
A PreparedStatement takes care of escaping (say a Name with an apostrophe in it). And most important prevents hacking, SQL injection (=creating evil SQL). Like a name admin and password xxx' OR 1=1.
Access was in my time not a multiuser database. You might use a Derby or H2 database.
JOptionPane does not work in an HTML page delivered, or even on creating the page on the server. The alternatives is writing on the result page.
You picked a hard topic with many features. Good luck.
As JSPs get soon ugly, unreadable, try servlets, maybe in combinations, pure servlet for coding and delivering results in a JSP page.

Number guesser game generates a different numbers each guess

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.

Categories