the application has a button and starts with the number 0, and each time the button is clicked on, the integer is increased by 1.
the problem is I have to incorporate it with this code and covert string "0" to integer 0
<%
int x = 0;
try { x = Integer.parseInt("0"); }
catch (Exception e) { x = 0; }
%>
also how would I continue to stay on the same page to click on the button to add one (do I put the code within the html?)
this is what I have so far:
<html>
<body>
<form method="post" action="index.jsp" />
<%
String integer = request.getParameter("0");
%>
<%
int x = 0;
try { x = Integer.parseInt("0"); }
catch (Exception e) { x = 0; }
%>
<input type="text" name="integer" value="<%=integer%>"/>
<input type="submit" value="submit" />
</form>
</body>
</html>
This is the code that would work for that situation.
<%! int clicks = 0; %>
<%
String param = request.getParameter("integer");
try
{
int i = Integer.parseInt(param);
clicks ++;
}
catch (NumberFormatException e)
{
}
%>
<p>Number of clicks untill now: <%= clicks %> </p>
<form action="">
<input type="text" name="integer" value="1"/>
<input type="submit" value="submit" />
</form>
You had some mistakes:
You are not using a form tag
You name your parameter "integer" but you are trying to recover it using the name of "0"
Some guidelines for you:
If you want to increase the value without reloading the page you need javascript/ajax.
You shouldn't be adding scriptlets to your JSP pages. Insted you should code a Servlet which handles the click increase and uses a RequestDispatcher to send to a JSP page where you are showing it (and not doing any calculations).
EDIT: I should warn you that this code would show the click value for every user on the page. If you don't want that, you should remove de JSP declaration and work with the param request instead. From my code it should be easy for you.
Related
I have dropdown with options and the values. I can get the option value by the dropdown name in servlet but how can i get the dropdown "value" in servlet. In screenshot, temporarily i concatenated the with options but i want to store value in variable in servlet.
Please help:
HTML:
<input type="text" name="taxiDropdown" id= "taxiDropdown" placeholder="Search taxi...">
</div>
<div class="scrolling menu">
<%
List eList = (ArrayList) session.getAttribute("taxiInfo");
%>
<%
for (int i = 0; i < eList.size(); i++) {
%>
<div class="item" data-value="<%=((TaxiInfo) eList.get(i)).getID()%>">
<div class="ui green empty circular label"></div>
<%=((TaxiInfo) eList.get(i)).getTaxiPlate() +" "+ ((TaxiInfo) eList.get(i)).getID() %>
</div>
<%
}
%>
</div>
</div>
Servlet:
String val = request.getParameter("taxiDropdown");
(in "val", I want to store the value of the dropdown not the option text)
In JSP you should have something like that:
<form method="post">
<select name="taxiDropdown" id="taxiDropdown">
<%
List<TaxiInfo> eList = (List<TaxiInfo>) request.getAttribute("taxiInfo");
for (TaxiInfo taxiInfo : eList) {
%>
<option name="<%=taxiInfo.getTaxiPlate()%>" value="<%=taxiInfo.getID()%>"><%=taxiInfo.getTaxiPlate()%></option>
<%
}
%>
</select>
<input type="submit" />
</form>
Then in controller/servlet you will receive the id of TaxiInfo:
String val = request.getParameter("taxiDropdown");
System.out.println(val);
Or in your case you should set a hidden input with javascript with desired value.
added this code in html:
Move value of the dropdown selection to hidden textbox
<script type='text/javascript'>
$(function() {
$('#driverdp').change(function() { <-- this is my dropdown -->
var x = $(this).val();
$('#driverid').val(x); <-- this is my textbox -->
});
});
</script>
Servlet:
get the value of hidden text in servlet
String text= request.getParameter("driverId");
hope it will help someone
Currently getting an error that the bankOffer property in my bean cannot be found..
It is from my game.jsp file shown below:
<%#page import="game.Briefcase"%>
<jsp:useBean id="game" class="game.Game" scope="session" />
<%
// If the 'open' parameter is received, it is converted to
// an integer and passed to the method setOpen. The value given
// is the corresponding index for the ArrayList Object.
if (request.getParameter("open") != null) {
game.caseOpen(Integer.parseInt(request.getParameter("open")));
}
// If the 'restart' parameter is given, then the restart method
// is invoked on the game bean.
if (request.getParameter("restart") != null) {
game.newgame();
}
// If the deal parameter is given, then it converts it to a Boolean
// value and performs a conditional test. If the parameter is true,
// then the deal has been made so the page is forwarded to the deal.jsp.
// Otherwise, the gameRound() is incremented cause it is NO DEAL!.
if (request.getParameter("deal") != null) {
if (Boolean.parseBoolean(request.getParameter("deal"))) {
game.setDeal(true);
} else {
game.nextround();
}
}
// If there is a Bank Offer, it will display the amount offered with
// two buttons to either accept or refuse.
if (!game.getDeal()) {
if (game.offerTime()) {%>
<div id="bank_offer">
<div id="bank_offer_title"></div>
<div id="deal_button" onclick="deal(true)"></div>
<div id="bank_offer_text">
<div id="bank_offer_amount">$<jsp:getProperty name="game" property="bankOffer" /></div>
<div id="bank_offer_message">Highest amount left: $<jsp:getProperty name="game" property="highestAmount" /></div>
</div>
<div id="nodeal_button" onclick="deal(false)"></div>
</div>
<%
// Otherwise, the Briefcases will be displayed along with a game message
// above the cases.
} else {
%>
<div id="game_message">
<div id="game_round">
<% if (game.getRound() > 0) { %>
Round: <jsp:getProperty name="game" property="round" />
<% } %>
</div>
<div id="game_text">
<jsp:getProperty name="game" property="message" />
</div>
</div>
<div id="cases">
<%
int index = 0;
// Iterates For Each Briefcase
for (Briefcase briefcase : game.getcases()) {
// If the Briefcase is not opened, then it is displayed as closed with the
// number assigned. Otherwise, if the Briefcase is opened then it is displayed
// as open with the amount value inside.
if (!briefcase.isOpened()) {
// If the Briefcase is the chosen case, then it will be displayed with
// 'Your Briefcase' on the image. The Briefcase's once pressed invokes
// a JavaScript function called openBriefcase() which passes the
// index. The function then invokes an Ajax call to the same .jsp which the
// html is then placed into the game container on the main index.jsp.
%>
<div onclick="openBriefcase(<%=index%>)" class="<%=(((game.getChosen() != null)
&& game.getChosen().equals(briefcase)) ? "briefcase_chosen" : "briefcase_closed")%>">
<div class="briefcase_number"><%=briefcase.getNumber()%></div></div>
<%} else {
// Once the case is opened it gets displayed with an open background
// with the case amount centered.
%>
<div class="briefcase_open">
<div class="briefcase_amount">$<%=briefcase.getValue()%></div>
</div>
<%}
index++;
}%>
</div>
<%
}
} else { %>
<div id="deal_message">
Deal $<jsp:getProperty name="game" property="bankOffer" />
</div>
<%
}
%>
Hmu to link any other files required. The previous file is index jsp, that loads fine with my other dynamic content, but it isnt loading game.jsp.
Help would be greatly appreciated, this is the first time I've had to use jsp in any extensive way so I'm at a loss right now..
Make sure that the class game.Game has a bean property (not just a field) named bankOffer. A java bean property is defined by its getters and setters, so for bankOffer to be a property, the class game.Game must include the public methods getBankOffer (or isBankOffer if a boolean property) and setBankOffer.
I am performing add to cart in java script which should call servlet addtocart.jlc as shown below.
<%#page import = "java.util.*" %>
<html>
<body>
<center>
<h1>JLC book store</h1>
<h2>JLC book search</h2>
<font color = "green" size = '6'> ${ADDED}</font>
</center>
<br/>
<%Object obj = request.getAttribute("MSG");
if(obj != null) { // if condtion
%>
<br/> <center>
<font color = "red" size = "6">
<%=obj%>
</font>
<br/><a href = "index.jsp">
<h2> GO TO SEARCH PAGE1 </h2></a>
</center>
<%} else { // if condition end and else condition open
obj = session.getAttribute("BOOKS");
ArrayList<String> blist = (ArrayList<String>)obj;
for(String bnm:blist) {
%>
<form action="addtocart.jlc" method="post">
<input type = "hidden" name = "bname"
value = "<%=bnm%>" />
<font size = '5'> <%=bnm%> <input type = "submit"
value = "ADD TO CART" />
</font>
</form>
<% } %>
<form action = "showcart.jlc">
<input type = "submit" value = "SHOW CART" />
</form>
<% } %>
</body>
</html>
when I ran above program I am getting output as shown below which is in if condition. I am not getting what is error. I am new to jsp and this is print out given by my lecture. I am working on but not able to get what is bug. I am using eclipse EE and tom cat server.
JLC book store
JLC book search
No books found with categorynull
GO TO SEARCH PAGE1
From your output I can see that at some point during this request, "No books found with categorynull" has been set to the "MSG" attribute of your request. Try to follow back before the request reaches this file.
I don't know what the .jlc extension is but from the looks of it this is a .jsp file, so your request might have gone through a HttpServlet before reaching this point where
request.setAttribute("MSG", "No books found with categorynull");
was called.
Also the error message suggests that this request was required to be called with a ?category=xxx query, and the same servlet was supposed to get the list of books for that category and call
request.setAttribute("BOOKS", ...);
If I were you I would perform a text search in the entire source code for the string .setAttribute("BOOKS"
I have used setTimeout method to do this and passed a variable which contains time but my settimeout method takes only the initialized value of that variable and not the value that is fetched from database.
Here is my code:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Givetest</title>
<script type = "text/javascript">
function submitForm() {
document.forms[0].submit();
}
</script>
<script language="JavaScript" src="http://scripts.hashemian.com/js/countdown.js"></script>
</head>
<%
String ts=request.getParameter("testname");
session.setAttribute("tname", ts);
Connection con=null;
Statement s1=null;
Statement s=null;
ResultSet r1=null;
ResultSet r=null;
int t=120000;
String time=null;
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc:odbc:online_testing");
s=con.createStatement();
s1=con.createStatement();
r=s.executeQuery("select * from "+ts+"");
r1=s1.executeQuery("select duration from tests where testname="+ts+"");
if(r1.next())
{
time=r1.getString("duration");
t=Integer.parseInt(time)*60000;
logger.info(time);
}
else {
logger.info("No row found in db for test " + ts);
System.out.println("No row found in db for test " + ts);
out.println("<br>!! <b>No row found in db </b>for test " + ts + "<br><br><br>");
}
r1.close();
}
catch(Exception e1)
{
response.setContentType("text/html");
out.println(e1.toString());
}
%>
<body onload="setTimeout('submitForm()',<%=t%>)">
<div class="header"></div>
<div class="view" style="color: #050505">
<form action="Givetest" method="post">
<h1 align="center" style="color: #050505"><%=ts%></h1>
<%
int i=1;
while(r.next()){
String a = r.getString("question");
String b = r.getString("option1");
String c = r.getString("option2");
String d = r.getString("option3");
String e = r.getString("option4");
%>
Question <%=i%>:- <label> <%=a%></label><br>
<input type="radio" name="r<%=i%>" value="<%=b%>" checked><label><%=b%></label><br>
<input type="radio" name="r<%=i%>" value="<%=c%>"><label><%=c%></label><br>
<input type="radio" name="r<%=i%>" value="<%=d%>"><label><%=d%></label><br>
<input type="radio" name="r<%=i%>" value="<%=e%>"><label><%=e%></label><br>
<br>
<input type="hidden" name="h" value="<%=ts%>">
<%
i++;
}
r.close();
s.close();
con.close();
%>
<input type="submit" class="button">
</form>
</div>
<div class="copyright" align="center"> © SAUMYARAJ ZALA</div>
</body>
</html>
The mistake is in the where clause which should be like:-
r1=s1.executeQuery("select duration from tests where testname="+ts+"");
Moreover this code should be executed in servlets before it is passed to jsp
<body onload="setTimeout('submitForm()',<%=t%>)">
You are giving the value only once. DO you mean it gets value
int t=120000;
and not what is in data base? If so are you sure no error is being thrown?
By the way this is not the best way to write a web app - all in jsp - though it works, better is to make servlets and POJOs/ helper .java files for data base etc. Make sure your tomcat/ app server's temp folder are cleaned every time you restart - to make sure its taking latest jsp.
In jsp can have a text like 'Version 001' and increase that manually so your sure correct code version is running.
Use loggers or system.out.println if you do not have logger
r1=s1.executeQuery("select duration from tests where testname="+ts+"");
//if should be enough as you will only have 0 or 1 row per test?
if(r1.next())
{
time=r1.getString("duration");
t=Integer.parseInt(time)*60000;
} else{
logger.warn("No row found in db for test " + ts);
//okay for debug
out.println("<br>!! <b>No row found in db </b>for test " + ts + "<br><br><br>");
}
r1.close();
}
catch(Exception e1)
{
response.setContentType("text/html");
out.println("<br><br> <b> ERROR</b>" + e1.toString());
}
sql
testname="+ts+""
is very bad should use a prepared statement or you are asking for a SQL injection attack. look at owasp https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet
How can I have a SQL statement that updates data when a button is clicked, not execute when the page loads?
I have a very simple table that has a player name, a player score, and player id attributes and only one row. When I am on this page, I want the button to execute the update query to increase player score, but it's happening every time the page loads.
Is there a boolean or something I can set to prevent it from adding 1 to the player score on every load?
Please don't ask why I'm using a JSP in this context. It's bad to do, I know, but these are my requirements.
Here is my code:
<%# page contentType="text/html" %>
<%# page import="java.text.DecimalFormat" %>
<%# page import="java.sql.Connection" %>
<%# page import="java.sql.DriverManager" %>
<%# page import="java.sql.ResultSet" %>
<%# page import="java.sql.Statement" %>
<%# page import="java.lang*" %>
<!DOCTYPE html>
<html>
<head>
<title>Player scores</title>
<script>
function reloadPage() {
location.reload();
}
</script>
</head>
<body>
<%!
String name = "";
Integer score = 0;
Integer pID = 0;
%>
<form name="form1" method="POST" onsubmit="return false">
<p align="center">
<input type="BUTTON" value="+" onclick="reloadPage();"/>
</p>
<%
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "admin");
Statement stmnt = conn.createStatement();
stmnt.executeUpdate("update players set playerScore=playerScore+1 where playerID=1");
} catch (Exception e) {
}
%>
</form>
<%
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "admin");
Statement stmnt = conn.createStatement();
ResultSet rs = stmnt.executeQuery("select playerID, playerName, playerScore from players where playerID=1");
if (rs.next()) {
name = rs.getString("playerName");
score = rs.getInt("playerScore");
pID = rs.getInt("playerID");
} else {
name = "-";
score = 0;
pID = 404;
}
} catch(Exception e) {
}
%>
<table align="center">
<tr>
<th>Player name:</th>
<td id="pID"><%=name%></td>
</tr>
<tr>
<th>Player score:</th>
<td id="pN"><%=score%></td>
</tr>
<tr>
<th>Player id:</th>
<td id="pi"><%=pID%></td>
</tr>
<p class="center">
Go back
</p>
</table>
</body>
</html>
The update code always gets executed because you have your code written that way.
This code:
<form name="form1" method="POST" onsubmit="return false">
<p align="center">
<input type="BUTTON" value="+" onclick="reloadPage();"/>
</p>
that calls:
<script>
function reloadPage() {
location.reload();
}
</script>
is just a refresh with no extra parameters. You always perform a GET.
You need to tell the JSP to do something different when you click the + button. You might try something like this (please have a look at this tutorial first):
<form name="form1" method="POST" action="yourJSPWhateverIsCalled.jsp">
<p align="center">
<input type="submit" value="+" name="increaseScore" />
</p>
Then guard your update code with an if:
<%
if (request.getParameter("increaseScore") != null) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "admin");
Statement stmnt = conn.createStatement();
stmnt.executeUpdate("update players set playerScore=playerScore+1 where playerID=1");
} catch (Exception e) {
}
}
%>
Class.forName is needed only once and you could reuse the connection to create the statements but that's another story. Also, a JSP isn't the place to postprocess a form submit (use a plain vanilla servlet).
One other problem with your code is that the JSP is thread UNsafe because of this definition:
<%!
String name = "";
Integer score = 0;
Integer pID = 0;
%>
If you use <%! the code is placed at servlet class level when your JSP gets translated to a servlet and not inside the _jspService method where it belongs. You are basically adding state to your JSP which is thread unsafe because the servlet container can reuse the same servlet instance to handle multiple requests.
Finally, I would strongly suggest you to read a JSP tutorial before continuing. An official tutorial is here.