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.
Related
i have written a program to select a particular column from mysql database in java and i want to display it on my server side using jsp.
In my jsp page , i have a select tag and some options which when selected will display the values of that options from my database
eg : airport will display the values of only airport which i have inserted in my database
When i debug my code on server, i can see the values like this [abc , xyz] but when i run it on server i can see only see the option(airport) which i selected as my output instead of the values.
So i guess i need to iterate the list , i did some research on how to iterate the list in jsp page 2 , but i guess its not the way how i should use it
code for the above :
java side , java code to select the column from database (working fine)
public List readCategoryMsg(String gcm_msg_type) {
List msgList = new ArrayList<String>();
try {
Class.forName("com.mysql.jdbc.Driver");
connection = (Connection)
DriverManager.getConnection("jdbc:mysql://localhost:3306/gcm",
"root", "root");
state = (Statement) connection.createStatement();
prep = (PreparedStatement) connection
.prepareStatement("Select gcm_message from gcm_msg where
gcm_msg_type = ?");
prep.setString(1, gcm_msg_type);
rSet = prep.executeQuery();
while (rSet.next()) {
String msg_type = rSet.getString("gcm_message");
msgList.add(msg_type);
}
connection.close();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return msgList;
}
jsp page 1: (which has options to select and submit it to the action page to display the output)
<form action="category_type_results.jsp" method="get">
<div align="left">
<br><select name="category_type">
<option value="airport">Airport</option>
<option value="art gallery">Art Gallery</option>
<option value="atm">ATM</option>
<option value="bank">Bank</option>
<option value="book store">Book Store</option>
<option value="bus station">Bus Station</option>
<option value="cafe">Cafe</option>
</div>
<div>
<input type="submit" value="Show Category Message " />
</div>
</form>
jsp page 2 : category_type_results.jsp
I have commented out the things i tried but not proper , need some help on how to show the list of values of a selected option from my database
<%
ServiceSql serviceSql = new ServiceSql();
String gcm_msg_type = request.getParameter("category_type");
serviceSql.readCategoryMsg(gcm_msg_type);
//List<String> msgList = serviceSql.readCategoryMsg("gcm_msg_type");
//for (int i = 0; i < msgList.size(); i++) {
// msgList.get(i);
}
%>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
</head>
<body>
<h3>
<%=gcm_type_msg%>
//<%=msgList%>
</h3>
</body>
how my database column looks , the same list i want to display on my server side
gcm_message(column name)
hello gcm (values)
hello gcm ..
hello gcm ..
hello gcm ..
hello gcm ..
hello gcm (values)
any sugestions would be of great help
Thanking You
Use JSTL to iterate through your list:
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
</head>
<body>
<%
ServiceSql serviceSql = new ServiceSql();
String gcm_msg_type = request.getParameter("category_type");
List msgList= serviceSql.readCategoryMsg(gcm_msg_type);
request.setAttribute("msgList", msgList);
%>
<h3>
<c:forEach items="${msgList}" var="msg">
${msg}
</c:forEach>
</h3>
I tried looking for help on the web to solve my problem but to no avail. I wish to convert verify[] to int, so it can be processed in the query.
verified column has a data type of string
staff_id column has a data type of autonumber
I'm getting an error of
java.sql.SQLException: [Microsoft][ODBC Microsoft Access Driver] Data type mismatch in criteria expression.
VerifyStaff.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=utf-8">
<title>Verification of Staff Accounts</title>
</head>
<body>
<div align="center">
<%-- Imports --%>
<%# page import="java.sql.*"%>
<%# page import="java.util.*"%>
<%-- HTTP header --%>
<%response.addHeader("Cache-Control","no-cache");
response.addHeader("Pragma","no-cache");
response.addHeader("Expires","0");
%>
<%-- Retrieving Staff Accounts - Reading --%>
<%
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String conURL= "jdbc:odbc:HOD_DATA";
Connection con = DriverManager.getConnection(conURL);
Statement st = con.createStatement();
String query = "select staff_id, username, password, user_group, verified from Staff";
ResultSet rs = st.executeQuery(query);
%>
<form action="VerifyStaffAuth.jsp">
<table width="200" border="1">
<tr>
<td>Staff_ID</td>
<td>Username</td>
<td>Password</td>
<td>User Group</td>
<td>Verified?</td>
<td>Verify/Un-verify</td>
</tr>
<%
while(rs.next()){
int staff = rs.getInt("staff_id");
%>
<tr>
<td><%= staff %></td>
<td><%= rs.getString("username") %></td>
<td><%= rs.getString("password") %></td>
<td><%= rs.getString("user_group") %></td>
<td><%= rs.getString("verified") %></td>
<td><label>
<input type="checkbox" name="CheckboxGroup" value="<%= staff %>">
</label></td>
</tr>
<%
}
rs.close();
st.close();
con.close();
}
catch(Exception e){
out.println(e);
}
%>
</table>
<input type="submit" VALUE="submit">
</form>
</div>
</body>
</html>
VerifyStaffAuth.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=utf-8">
<title></title>
</head>
<body>
<%-- Imports --%>
<%# page import="java.sql.*"%>
<%# page import="java.util.*"%>
<%-- HTTP header --%>
<%response.addHeader("Cache-Control","no-cache");
response.addHeader("Pragma","no-cache");
response.addHeader("Expires","0"); %>
<% String[] verify = request.getParameterValues("CheckboxGroup");
int[] verify2 = new int[verify.length];
for(int i=0;i<verify.length;i++){
verify2[i]=Integer.parseInt(verify[i]);
}
if(verify != null){
for(int i=0; i<verify.length; i++){
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String conURL= "jdbc:odbc:HOD_DATA";
Connection con = DriverManager.getConnection(conURL);
Statement st = con.createStatement();
int status = st.executeUpdate("update Staff set verified = 'yes' where Staff_id = '"+verify[i]+"'");
if(status>0){
//response.sendRedirect("SuccessfulReg1.html");
}
else{
//out.println("Update unsuccessful");
}
st.close();
con.close();
}
catch(Exception e){
out.println(e);
}
}
}
%>
</body>
</html>
Change your UPDATE query to
st.executeUpdate("update Staff set verified = 'yes' where Staff_id = " + verify[i]);
Since, staff_id column has a data type of autonumber, its value should not be specified in quotes since it's numeric in nature.
I would also suggest you to use the SQL IN clause and fire just one single UPDATE instead of firing it multiple times, one for each staff_id value.
Your UPDATE query with IN clause should look something like
UPDATE staff SET verified = 'yes' WHERE staff_id IN (1, 2, 3)
Use Arrays.toString() to get the comma-delimited string as
String inValues = Arrays.toString(verify); // "[1, 2, 3]"
inValues = inValues.substring(1, inValues.length() - 1)); // "1, 2, 3"
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
My requirement is to display userName and FirstName first then try logic next....but here after some time in try block(few secs for try logic loading/execution) then userName and password displaying in page...How can i display userName/Firstanme then try logic next.
<html>
<head>
</head>
<body>
<%
String lastname= request.getParameter("lastname");
String firstname= request.getParameter("firstname");
%>
<tbody>
<tr>
<td>Firstname</td>
<td>:</td>
<td><%=firstname %></td>
</tr>
<tr>
<td>Lastname</td>
<td>:</td>
<td><%=lastname %></td>
</tr>
</tbody>
<%
try
{
System.out.println("Inside Thread");
Thread.currentThread().sleep(10000);
}
catch(Exception ex1)
{
System.out.println(ex1.getMessage());
}
%>
</body>
</html>
JSP is serverside language, the whole page is rendered, then send back to browser/client.
So with JSP you cannot do this.
You can include javascript in your jsp page, which talks to a webservice that does the logic you want it to do. The webservice can also return data that you can use to update your page...
I suggest you lookup AJAx on the web, a good place to start is:
http://www.w3schools.com/ajax/
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
I want to enter data in database entered from jsp file and dont know how to connect them. Can any one suggest me to connect both files and to add the data entered in jsp form ?
This is my jsp and java files...
test1.java
package P1;
import java.sql.*;
class test1 {
public static void main(String[] args) throws SQLException, ClassNotFoundException {
Connection con = null;
try {
Class.forName("oracle.jdbc.odbc.JdbcOdbcDriver");
}
catch(ClassNotFoundException ex) {
System.out.println("Error: unable to load driver class!");
System.exit(1);
}
con = DriverManager.getConnection("jdbc:oracle:thin:#192.168.106.87:1521:ORA11G","fuel_db","foel");
Statement statement = con.createStatement();
String command = "INSERT INTO student (name, rollno, class, mobileno) VALUES (?, ?, ?, ?);";
statement.executeUpdate(command);
con.close();
}
}
test1.html
**
<%# 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">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>FORM</title>
<script type="text/javascript">
<%
String name = request.getParameter("name");
String roll = document.getElementById("rollno");
String clas = document.getElementById("class");
String mobile = document.getElementById("mobileno");
test1 myTest = new test1();
myTest.submitData();
%>
function getvalues()
{
var name = document.getElementById("name");
var roll = document.getElementById("rollno");
var clas = document.getElementById("class");
var mobile = document.getElementById("mobileno");
}
function num(e)
{
var k;
document.all ? k = e.keyCode : k = e.which;
return (!((k > 64 && k < 91) || (k > 96 && k < 123) || k == 8));
}
</script>
</head>
<body>
<form action="test1.java" method="post" >
<table>
<tr>
<td>First Name: </td>
<td><input type="text" name="name" maxlength="10"></td>
</tr>
<tr>
<td>roll:</td>
<td><input type="text" name="rollno" maxlength="5" onkeypress="return num(event)"></td>
</tr>
<tr>
<td>class:</td>
<td><input type="text" name="class" maxlength="10"></td>
</tr>
<tr>
<td>Mobile:</td>
<td><input type="text" name="mobileno" maxlength="10" onkeypress="return num(event)"></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Submit" onclick="getvalues()"></td>
</tr>
</table>
</form>
</body>
</html>
**
I won't go by your code. But the example here will be enough.
The standard way of passing/submitting data to the server in the pure Servlets/JSP world is by using HTML form, i.e. the same way as when use other server side languages for example php. And it doesn't matter whether it is a pure HTML page or JSP page. The recommended/most used method of submitting data from the form to the server is POST or GET.
Its standard way to submit data using POST method and respectively to process the submitted data using the doPost() method in your servlet.
for example:
<form name="something" method="post" action="<servlet-name>"> //if u want to change the action to something else then u need to modify your xml file.
<input type="text" name="username"/>
<input type="submit" name="submitit" value="submited"/>
</form>
now in the servlet under the doPost(...) write
if(request.getParameter("submitit").equals("submitted")){
String username=request.getParameter("username");
//now u can run a query and insert ito to database;
}
in the end you can redirect it another page with
`response.sendRedirect();`
or any other way
may i assume that you are using eclipse Java EE ide for development. then u need not worry about integrating them, eclipse would prepare the xml files for you once you create a new Java EE project. and if not then u have to do it manually, i once tried to do it, but I couldn't succeed.
here is a link: that would interset you, i hope: http://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/
this is bad thing, but i will edit the code for you. by the way, i am removing the javascript. KISS (keeping it simple silly).. :)
ur jsp page would be:
<%# 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">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>FORM</title>
</head>
<body>
<form action="test1" method="post" >
<table>
<tr>
<td>First Name: </td>
<td><input type="text" name="name" maxlength="10"></td>
</tr>
<tr>
<td>roll:</td>
<td><input type="text" name="rollno" maxlength="5"></td>
</tr>
<tr>
<td>class:</td>
<td><input type="text" name="class" maxlength="10"></td>
</tr>
<tr>
<td>Mobile:</td>
<td><input type="text" name="mobileno" maxlength="10"></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Submit"></td>
</tr>
</table>
</form>
</body>
</html>
and the servlet will be:
import java.sql.*;
class test1 {
public static void main(String[] args) throws SQLException, ClassNotFoundException {
Connection con = null;
PreparedStatement pstmt = null;
try {
Class.forName("oracle.jdbc.odbc.JdbcOdbcDriver");
}
catch(ClassNotFoundException ex) {
System.out.println("Error: unable to load driver class!");
System.exit(1);
}
con = DriverManager.getConnection("jdbc:oracle:thin:#192.168.106.87:1521:ORA11G","fuel_db","foel");
String name = request.getParameter("name");
String roll = document.getElementById("rollno");// idk why roll no is string
String clas_s = document.getElementById("class");
String mobile = document.getElementById("mobileno");
try {
String query= "INSERT INTO student (name, rollno, class, mobileno) VALUES (?, ?, ?, ?);";
pstmt = con.prepareStatement(query);
pstmt.setString(1,name);
pstmt.setString(2,roll);
pstmt.setString(3,clas_s);
pstmt.setString(4,mobile);
pstmt.executeUpdate();
con.close();
}
catch(Exception e) {
e.printStackTrace();}
response.sendRedirect("confirm.jsp");
}
}
donot ask me about the braces.. fix it yourself.
First create some method like submitData(data) in your Java class.
public class test1 {
public void submitData(String name,String rollno,String classData,String mobileno) throws SQLException, ClassNotFoundException {
Connection con = null;
try {
Class.forName("oracle.jdbc.odbc.JdbcOdbcDriver");
}
catch(ClassNotFoundException ex) {
System.out.println("Error: unable to load driver class!");
System.exit(1);
}
con = DriverManager.getConnection("jdbc:oracle:thin:#192.168.106.87:1521:ORA11G","fuel_db","foel");
Statement statement = con.createStatement();
String command = "INSERT INTO student (name, rollno, class, mobileno) VALUES (" + name + "," + rollno + "," + classData + "," + mobileno + ");";
statement.executeUpdate(command);
con.close();
}
}
In your HTMl page index.html or index.jsp, you need to put a form and then post it to JSP page which has the logic I have mentioned below.
<FORM NAME="form1" ACTION="ProcessData.jsp" METHOD="POST">
In your JSP page you may get data when a form is submitted using POST method. Get all those variables using request.getParameter("name")
Then in your JSP put that java code in <% %> blocks inside body tag. Remember JSP is Java in HTML!
In your ProcessData.jsp
<%
String name = request.getParameter("name");
//add null checks and all
//Similarly get all datamobileno etc
//then call your submitData() method
test1 myTest = new test1();
myTest.submitData(....)
%>
Also take care of naming conventions.
In java
Classes name start with Caps. So class name must be Test1 and not test1.
Functions, variables must be in Camel case like myTest.