refreshing mysql table in jsp with a button - java

I am trying to retrieve the data from a mysql database on a jsp page, When the page loads, it loads the latest data (which is what i want), but then when i click on the refresh button i made it refreshes the table with older data and then the button doesnt work after that (wont refresh the table).
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# page import="java.sql.*, javax.sql.*, java.io.*, javax.naming.*"%>
<!DOCTYPE html>
<html>
<head>
<title>Main Page</title>
<h1>
<strong>test page</strong>
</h1>
<hr />
<canvas id="mycanvas" width="400" height="186"></canvas>
<script src="JavaScript/smoothie.js"></script>
<script src="JavaScript/chart.js"></script>
<script src="JavaScript/basic.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#refresh").click(function(){
$("#heart_rate").load("basic2.jsp")
});
});
</script>
</head>
<body>
<br>
<br>
<button id="refresh">Refresh table</button>
<br>
<br>
<form method="post" name="form">
<table id="heart_rate" border="1">
<tr>
<th>Sensor id</th>
<th>Time stamp</th>
<th>Heart rate</th>
<th>Event time</th>
</tr>
<%
Connection con = null;
String url = "jdbc:mysql://localhost:3306/";
String db = "Avantidrome";
String driver = "com.mysql.jdbc.Driver";
String un ="root";
String pw="root";
Statement st;
try{
Class.forName(driver).newInstance();
con = DriverManager.getConnection(url + db, un, pw);
String sql = "select * from avantidrome.heartratedata order by timestamp DESC limit 10";
st = con.createStatement();
ResultSet rs = st.executeQuery(sql);
%>
<%
while(rs.next())
{
%>
<tr>
<td><%=rs.getString(1)%></td>
<td><%=rs.getString(2)%></td>
<td><%=rs.getString(4)%></td>
<td><%=rs.getString(5)%></td>
</tr>
<%
}
%>
<%
} catch(Exception e){
e.printStackTrace();
}
%>
</table>
</form>
</body>
</html>
once the button is clicked it calls basic.jsp which is just:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# page import="java.sql.*, javax.sql.*, java.io.*, javax.naming.*"%>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<br>
<br>
<form method="post" name="form">
<table id="heart_rate" border="1">
<tr>
<th>Sensor id</th>
<th>Time stamp</th>
<th>Heart rate</th>
<th>Event time</th>
</tr>
<%
Connection con = null;
String url = "jdbc:mysql://localhost:3306/";
String db = "Avantidrome";
String driver = "com.mysql.jdbc.Driver";
String un ="root";
String pw="root";
Statement st;
try{
Class.forName(driver).newInstance();
con = DriverManager.getConnection(url + db, un, pw);
String sql = "select * from avantidrome.heartratedata order by timestamp DESC limit 10";
st = con.createStatement();
ResultSet rs = st.executeQuery(sql);
%>
<%
while(rs.next())
{
%>
<tr>
<td><%=rs.getString(1)%></td>
<td><%=rs.getString(2)%></td>
<td><%=rs.getString(4)%></td>
<td><%=rs.getString(5)%></td>
</tr>
<%
}
%>
<%
} catch(Exception e){
e.printStackTrace();
}
%>
</table>
</form>
</body>
</html>
all it needs to do is for the button to select the newest data from the database and return it to the table whenever it is clicked.

There are two ways to do what you want:
When the user press the refresh button, you simple refresh the page (this should be so fast that he wont notice that the page changed)
Using ajax. So, if choose this option you need to understand that to do this you only need one jsp (the one that loads the page in the begin and has the refresh button), a scrip of javascript that handles the refresh button and uses ajax to get the new data, and a servlet that receives the ajax request and returns an ajax response in json/xml containing the updates.
In my opinion, I prefer the first option, but if you choose to go for the second one, heres another SO post that may help you: How to use Servlets and Ajax?

Related

JSP search option

i have been trying to make it work for a long time now. but none of the reference works. so far these are my latest code regarding search. hopefully someone can help. i am new in jsp and this is final graduation project. so badly need help.
code:
index.jsp:
<div class="container">
<form class="form-inline" method="post" action="search.jsp">
<input type="text" name="roll_no" class="form-control" placeholder="Search roll no..">
<button type="submit" name="save" class="btn btn-primary">Search</button>
</form>
search.jsp:
<%#page import="java.sql.DriverManager"%>
<%#page import="java.sql.ResultSet"%>
<%#page import="java.sql.Statement"%>
<%#page import="java.sql.Connection"%>
<%
String driver = "com.mysql.jdbc.Driver";
String connectionUrl = "jdbc:mysql://localhost:3306/";
String database = "hospital";
String userid = "hospital";
String password = "hospital";
String NAME=request.getParameter("NAME");
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
%>
<!DOCTYPE html>
<html>
<body>
<h1>Search Data</h1>
<table border="1">
<tr>
<td>CODE</td>
<td>NAME</td>
<td>PRICE</td>
</tr>
<%
try{
connection = DriverManager.getConnection(connectionUrl+database, userid, password);
statement=connection.createStatement();
String sql ="select * from product where NAME="+NAME+"' ";
resultSet = statement.executeQuery(sql);
while(resultSet.next()){
%>
<tr>
<td><%=resultSet.getString("CODE") %></td>
<td><%=resultSet.getString("NAME") %></td>
<td><%=resultSet.getString("PRICE") %></td>
</tr>
<%
}
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
%>
</table>
</body>
</html>

I am trying to insert data in to a SQL database in my local computer using Java jsp

I am creating a web application in java jsp using Eclipse and Tomcat.but I am stock unable to insert the data in to my local SQL server. The Form of the page is coded in HTML then I want the Java code part to get the data entered and insert the data in to the database but when I click the submit button absolutely nothing happens, no error message, no warning so far I am only able to type and clear the form. I am very new in Java. I just pick up this codding language recently but I am determine to learn it.
Help please here is my full code.
<%# page import="java.text.*,java.util.*" session="false"%>
<%# page import="java.sql.*" %>
<%#page import="javax.swing.JOptionPane" %>
<%#page import="java.util.Date" %>
<%#page import ="java.io.IOException" %>
<%#page import ="javax.servlet.ServletException" %>
<%#page import ="javax.servlet.http.HttpServlet" %>
<%#page import ="javax.servlet.http.HttpServletRequest" %>
<%#page import ="javax.servlet.http.HttpServletResponse" %>
<% Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); %>
<%# 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>Insert Laptops Data</title>
<link rel="stylesheet" href="Style.css" type="text/css">
</head>
<body>
<%!public class Insert extends HttpServlet {
String dbURL = "jdbc:sqlserver://localhost\\SQLYRSIN";
String user = "pass";
String pass = "pass";
Connection conn = null;
PreparedStatement InsertLaptops = null;
ResultSet resultSet = null;
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String LaptopMake, LaptopModel, LaptopServicetag, LaptopDatein, LaptopNotes, LaptopType;
LaptopMake = req.getParameter("iMake");
LaptopModel = req.getParameter("iModel");
LaptopServicetag = req.getParameter("iServiceTag");
LaptopDatein = req.getParameter("iDatein");
LaptopNotes = req.getParameter("iNotes");
LaptopType = req.getParameter("iType");
try {
conn = DriverManager.getConnection(dbURL, user, pass);
Statement st = conn. createStatement();
st.executeUpdate("INSERT INTO LaptopsTable (Make, Model, [Service Tag], Datein, Notes, Type)"
+ " VALUES ('"+LaptopMake+"','"+LaptopModel+"','"+LaptopServicetag+"','"+LaptopDatein +"','"+LaptopNotes+"','"+LaptopType+"')");
JOptionPane.showConfirmDialog(null, "Your Data Has been Inserted", "Result", JOptionPane.DEFAULT_OPTION,
JOptionPane.PLAIN_MESSAGE);
st.close();
conn.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
}%>
<div id="header">
<div class="logo">
<span> Resident Screening</span> Jinventory
</div>
</div>
<div id="container">
<div class="content">
<h1>Add New Laptop</h1>
<p>Make sure all Service Tag Enter in here are Laptops</p>
<div id="box">
<form name="LaptopsForm" method="get" class="contentfonts"
action="LaptopsInsert2.jsp" method="Post">
<table>
<tbody>
<tr>
<td>Service Tag</td>
<td><input type="text" name="iServiceTag" size="40"></td>
</tr>
<tr>
<td>Make</td>
<td><input type="text" name="iMake" size="40"></td>
</tr>
<tr>
<td>Model</td>
<td><input type="text" name="iModel"></td>
</tr>
<tr>
<td>Date</td>
<td><input type="date" name="iDate"></td>
</tr>
<tr>
<td>Type</td>
<td><input type="text" name="iTyped" Value="Laptop"
disabled="disabled"></td>
</tr>
<tr>
<td>Notes</td>
<td><input Type="text" name="iNotes" size="30" height="40"></td>
</tr>
<tr>
<td><input type="reset" name="Reset"></td>
<td><input type="submit" name="submit"></td>
</tr>
</tbody>
</table>
</form>
</div>
</div>
</div>
</body>
</html>
Here's a draft which you could use as a starting point.
As mentioned before, you should seriously consider some changes to your design:
Separate View (.jsp) from Business-Logic (SQL-Statements etc.)
Don't use scriptlets ( <% and so on )
Creating a Servlet within JSP is overkill - a JSP is compiled into a servlet by the servlet container.
Don't create Connections one-by-one. Use a connection pool. This will pay off quickly.
In the code you'll see some changes to your setup:
form is submitted per POST
instead of subclass, JSP checks for methods POST and only then tries the insert.
never ever use Swing inside Webapps. If that JOptionPane was opened, your webapp would block at that point, while the Dialog was shown somewhere on your server.
Use of PreparedStatement instead of Statement this prevents SQL injection. You'll still want to check against Cross-Site-Scripting if you plan on displaying the inserted values in your webapp again.
Disclaimer: I haven't tested or even tried to compile this code. Edit was done only to point you in the right direction.
Here it goes
<%#page import="java.text.*,java.util.*" session="false"%>
<%#page import="java.sql.*" %>
<%#page import="java.util.Date" %>
<%#page import ="java.io.IOException" %>
<%#page import ="javax.servlet.ServletException" %>
<%#page import ="javax.servlet.http.HttpServlet" %>
<%#page import ="javax.servlet.http.HttpServletRequest" %>
<%#page import ="javax.servlet.http.HttpServletResponse" %>
<% Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); %>
<%# 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>Insert Laptops Data</title>
<link rel="stylesheet" href="Style.css" type="text/css">
</head>
<body>
<%
if("POST".equals(request.getMethod()) {
String dbURL = "jdbc:sqlserver://localhost\\SQLYRSIN";
String user = "pass";
String pass = "pass";
Connection conn = null;
PreparedStatement InsertLaptops = null;
ResultSet resultSet = null;
String LaptopMake, LaptopModel, LaptopServicetag, LaptopDatein, LaptopNotes, LaptopType;
LaptopMake = req.getParameter("iMake");
LaptopModel = req.getParameter("iModel");
LaptopServicetag = req.getParameter("iServiceTag");
LaptopDatein = req.getParameter("iDatein");
LaptopNotes = req.getParameter("iNotes");
LaptopType = req.getParameter("iType");
try {
conn = DriverManager.getConnection(dbURL, user, pass);
PreparedStatement st = conn.prepareStatement("INSERT INTO LaptopsTable (Make, Model, [Service Tag], Datein, Notes, Type) VALUES (?,?,?,?,?,?)");
st.setString(1, LaptopMake);
st.setString(2, LaptopModel);
st.setString(3, LaptopServicetag);
st.setString(4, LaptopDatein);
st.setString(5, LaptopNotes);
st.setString(6, LaptopType);
st.executeUpdate();
//This is SWING - and would at best popup a Dialog ON YOUR SERVER
//JOptionPane.showConfirmDialog(null, "Your Data Has been Inserted", "Result", JOptionPane.DEFAULT_OPTION,
// JOptionPane.PLAIN_MESSAGE);
//Alternative: Show some HTML.
%>
<h1>Your Data has been inserted.</h1>
<%
st.close();
conn.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
} //END of Method.equals("POST")
%>
<div id="header">
<div class="logo">
<span> Resident Screening</span> Jinventory
</div>
</div>
<div id="container">
<div class="content">
<h1>Add New Laptop</h1>
<p>Make sure all Service Tag Enter in here are Laptops</p>
<div id="box">
<form name="LaptopsForm" method="POST" class="contentfonts"
action="" method="POST">
<table>
<tbody>
<tr>
<td>Service Tag</td>
<td><input type="text" name="iServiceTag" size="40"></td>
</tr>
<tr>
<td>Make</td>
<td><input type="text" name="iMake" size="40"></td>
</tr>
<tr>
<td>Model</td>
<td><input type="text" name="iModel"></td>
</tr>
<tr>
<td>Date</td>
<td><input type="date" name="iDate"></td>
</tr>
<tr>
<td>Type</td>
<td><input type="text" name="iTyped" Value="Laptop"
disabled="disabled"></td>
</tr>
<tr>
<td>Notes</td>
<td><input Type="text" name="iNotes" size="30" height="40"></td>
</tr>
<tr>
<td><input type="reset" name="Reset"></td>
<td><input type="submit" name="submit"></td>
</tr>
</tbody>
</table>
</form>
</div>
</div>
</div>
</body>
</html>

Integrating Eclipse with MySQL

I am facing a problem while integrating a web application developed in eclipse with a mysql database (mysql workbench).
below are the jsp files I used and the database name.
database username -- root
password -- 1234
Login.jsp
<%--
Document : Login
Created on : 28 Feb, 2015, 8:50:26 AM
Author : Lahaul Seth
--%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Login Demo with JSP</title>
</head>
<body>
<form method="post" action="userdetail.jsp">
<center>
<table border="1" cellpadding="5" cellspacing="2">
<thead>
<tr>
<th colspan="2">Login Here</th>
</tr>
</thead>
<tbody>
<tr>
<td>Username</td>
<td><input type="text" name="username" required/></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="password" required/></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="Login" />
<input type="reset" value="Reset" />
</td>
</tr>
</tbody>
</table>
</center>
</form>
</body>
</html>
userdetail.jsp
<%# page language="java" %>
<%# page import="org.owasp.esapi.ESAPI" %>
<%# page import="org.owasp.esapi.codecs.Codec" %>
<%# page import="org.owasp.esapi.codecs.MySQLCodec" %>
<%# page import="java.sql.*" %>
<%# page import="java.io.*" %>
<%! Connection con= null; %>
<%! Statement stmt= null; %>
<%! ResultSet rs= null; %>
<%! MySQLCodec mc= null; %>
<html>
<head><title>List Users</title></head>
<%
String uname = request.getParameter("uname");
String pass = request.getParameter("pass");
String uid = request.getParameter("uid");
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
}catch(ClassNotFoundException ce){out.println(ce);}
try{
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root", "1234");
stmt = con.createStatement();
String sql = "select * from userdetail where id = "+Integer.parseInt(uid);
//out.println(sql);
rs = stmt.executeQuery(sql);
%>
<body>
<br>
<br>
<div align="center"><b>You have Successfully Logged In Mr/Ms<%=uname%>, Your Details are :-</b></div>
<br>
<br>
<br>
<form action="view.jsp">
<table align="center">
<% while(rs.next()) {%>
<tr><td>First Name</td><td><input type=text name="fname" value='<%=rs.getString("firstname")%>' ></td></tr>
<tr><td>Last Name</td><td><input type=text name="lname" value='<%=rs.getString("lastname")%>'></td></tr>
<tr><td>Email</td><td><input type=text name="email" value='<%=rs.getString("email")%>'></td></tr>
<tr><td>Phone</td><td><input type=text name="phone" value='<%=rs.getString("phone")%>'></td></tr>
<tr><td>Address</td><td><input type=text name="address" value='<%=rs.getString("address")%>'></td></tr>
<%
}
rs.close();
stmt.close();
con.close();
}catch(SQLException exception){
//out.println("<!--");
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
exception.printStackTrace(pw);
out.print(sw);
sw.close();
pw.close();
//out.println("-->");
}
%>
</table>
</form>
</body>
</html>
auth.jsp
<%# page language="java" %>
<%# page import="org.owasp.esapi.ESAPI" %>
<%# page import="org.owasp.esapi.codecs.Codec" %>
<%# page import="org.owasp.esapi.codecs.MySQLCodec" %>
<%# page import="java.sql.*" %>
<%# page import="java.io.*" %>
<%! Connection con=null; %>
<%! Statement stmt= null; %>
<%! ResultSet rs= null; %>
<%! MySQLCodec mc= null; %>
<html>
<head><title>This is a Jdbc Example</title></head>
<body>
<%
String uname = request.getParameter("uname");
String pass = request.getParameter("pass");
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
}catch(ClassNotFoundException ce){out.println(ce);}
try{
con = DriverManager.getConnection("jdbc:mysql://localhost/test:3306","root", "1234");
stmt = con.createStatement();
//String sql = "select * from user_detail where uname='" + uname +"' and pass='" + pass + "'";
mc = new MySQLCodec(0);
String sql = "SELECT * FROM userdetail WHERE uname = '" + ESAPI.encoder().encodeForSQL( mc, uname) + "' and pass = '" + ESAPI.encoder().encodeForSQL( mc, pass) +"'";
out.println(sql);
stmt = con.createStatement();
rs = stmt.executeQuery(sql);
if (rs.next()) {
boolean loggedIn = true;
//response.sendRedirect("userdetail.jsp?uid=1");
out.println("Successfully logged in");
} else {
//response.sendRedirect("login.jsp");
out.println("Username and/or password not recognized");
}
rs.close();
stmt.close();
con.close();
}catch(SQLException exception){
//out.println("<!--");
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
exception.printStackTrace(pw);
out.print(sw);
sw.close();
pw.close();
//out.println("-->");
}
%>
</body>
</html>
MySQL datatbase
Error page
Well, this sounds to be a class path issue. Could you please check MySQLCodec class present in WEB-INF/classes or present in any jar in WEB-INF/lib path.
You can double check the tomcat war directory. It should be in the below sample folder structure.

My record is not inserting into database?

I'm trying to insert my data into database using Textbox, Sometime it inserts the data in only using Internet Explorer but not in Mozilla firefox.
It's strange.....
My data sometime gets uploaded but only using Internet Explorer and sometimes it stops working. Please help what's that mean?
Here is my code:
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%# page import="java.sql.*"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script type="text/javascript" >
$(function() {
$(".update_button").click(function() {
var boxval = $("#content").val();
var dataString = 'content='+ boxval;
if(boxval=='')
{
alert("Please Enter Some Text");
}
else
{
$.ajax({
type: "POST",
url: "demo.jsp",
data: dataString,
cache: false
});
}
});
});
</script>
</head>
<body>
<div>
<form method="post" name="form" action="">
<h3>What are you doing?</h3>
<textarea name="content" id="content" ></textarea><br />
<input type="submit" value="Update" name="submit" class="update_button" />
</form>
</div>
<%
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/poststatus", "root", "1234");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select * from messages order by msg_id desc");
while(rs.next()){
String msg=rs.getString("msg");
%>
<ol id="update" class="timeline"><%=msg %></ol>
<%
}
}
catch(Exception e){
e.printStackTrace();
}
%>
</body>
</html>
and here is my demo.jsp:
<%# page import="java.sql.*" errorPage="" %>
<%
String content=request.getParameter("content");
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/poststatus", "root", "1234");
Statement st=con.createStatement();
int i=st.executeUpdate("insert into messages(msg) values('"+content+"')");
}
catch(Exception e){
e.printStackTrace();
}
%>
And yes, I can fetch my data from database ..as you could see my code. But i'm unable to insert data..
Surely, Help would be appreciated!
EDITED:
Here is my created table:
create database if not exists poststatus;
use poststatus;
create table messages(
msg_id INT auto_increment,
msg VARCHAR(1000) NOT NULL,
primary key(msg_id)
);
The update button that sends the AJAX request is also the form's submit button, so when you click it, it begins submitting the form, which navigates away from the current page, cutting off the code before it can run the AJAX request.
Modify the beginning of your click handler to:
$(".update_button").click(function(e) {
e.preventDefault();
Calling preventDefault() on the event will prevent the form from submitting, giving your AJAX function the chance to run.
Additionally, there is a serious problem in the Java code; because the value is inserted with string concatenation, it creates a blatant SQL injection vulnerability, and also will not work if someone innocently types an apostrophe. Change:
Statement st=con.createStatement();
int i=st.executeUpdate("insert into messages(msg) values('"+content+"')");
to:
PreparedStatement st = con.prepareStatement("insert into messages(msg) values(?)");
st.setString(1, content);
int i = st.executeUpdate();

How to increment the value of request.getParameter?

I'm trying to make an quiz and my query is ORDER BY RAND() so it means it will be random... My JSP send it to servlet to handle the flow but I'm having a problem, I have stored 4 questions with choices (answer) in the database and in my code below I retreive it. Problem is, when I retrieve the answer of the examinee the only retrieved data is the first answer... See my servlet
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#page import="java.sql.*" %>
<%#page import="database.Connect" %>
<%
Connect conn = new Connect();
Statement stmt = conn.getDataConn().createStatement();
ResultSet rs = stmt.executeQuery("SELECT * from quiz WHERE category = 'secondary' ORDER BY RAND()");
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" type="text/css" href="../../css&js/des.css">
<script src="css&js/modernizr.custom.js"></script>
<title>Question 1</title>
</head>
<body>
<img alt="" src="../../pics/bgimg2.jpg" id="bgimg" />
<div class="md-modal md-effect-1 md-show" id="modal-1">
<form action="../../Check" method="POST">
<table border="1" class="c-form md-content">
<% while(rs.next()){
%>
<tr>
<td><h1><%=rs.getString("question")%>?</h1></td>
<td><select name="answer">
<option value="<%=rs.getString("choice1")%>"><%=rs.getString("choice1")%></option>
<option value="<%=rs.getString("choice2")%>"><%=rs.getString("choice2")%></option>
<input type="hidden" name="correct" value="<%=rs.getString("correct")%>"/>
</select></td>
</tr>
<%}
%>
<tr>
<td align="center" colspan="2"><input type="submit" value="Next"/></td>
</tr>
</table>
</form>
</div>
</body>
I'm trying to make an quiz and my query is ORDER BY RAND() so it means it will be random... My JSP send it to servlet to handle the flow but I'm having a problem, I have stored 4 questions with choices (answer) in the database and in my code below I retreive it. Problem is, when I retrieve the answer of the examinee the only retrieved data is the first answer... See my servlet
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#page import="java.sql.*" %>
<%#page import="database.Connect" %>
<%
Connect conn = new Connect();
Statement stmt = conn.getDataConn().createStatement();
ResultSet rs = stmt.executeQuery("SELECT * from quiz WHERE category = 'secondary' ORDER BY RAND()");
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" type="text/css" href="../../css&js/des.css">
<script src="css&js/modernizr.custom.js"></script>
<title>Question 1</title>
</head>
<body>
<img alt="" src="../../pics/bgimg2.jpg" id="bgimg" />
<div class="md-modal md-effect-1 md-show" id="modal-1">
<form action="../../Check" method="POST">
<table border="1" class="c-form md-content">
<% while(rs.next()){
%>
<tr>
<td><h1><%=rs.getString("question")%>?</h1></td>
<td><select name="answer">
<option value="<%=rs.getString("choice1")%>"><%=rs.getString("choice1")%></option>
<option value="<%=rs.getString("choice2")%>"><%=rs.getString("choice2")%></option>
<input type="hidden" name="correct" value="<%=rs.getString("correct")%>"/>
</select></td>
</tr>
<%}
%>
<tr>
<td align="center" colspan="2"><input type="submit" value="Next"/></td>
</tr>
</table>
</form>
</div>
</body>
Servlet... Im just trying to experiment here but I really need help.. The output is null for the for and past code are also fail because the 1st answer is the olnly retrieve and I need to increment it. Please help
package Servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Check extends HttpServlet {
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
for(int i=0;i<10;i++) {
String Answer = request.getParameter("answer" + i);
System.out.println(Answer);
}
String Answer = request.getParameter("answer");
String Correct = request.getParameter("correct");
int score = 0;
if (Answer.equals(Correct)) {
score++;
}
System.out.println(score);
}
}
It is may be because you select tags has the same name for every question:
<select name="answer">
I think it should unique

Categories

Resources