JSP table disappears after user deletes some info in that table - java

In this code, when user adds delete button, raw is being deleted from database, but user is being redirected to empty home page, unless he logs out and logs in again. how can I fix the code, so that when he deletes something, whole layout is not disappearing, but only the line that he deleted.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<script type="text/javascript">
function del() {
if (confirm("Do You Want to Delete this Menu?")) {
} else {
return false;
}
}
</script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<link rel="stylesheet" href="images/style.css" type="text/css"
charset="utf-8" />
</head>
<body>
<%
menu_slno1 = request.getParameter("menu_slno");
if (menu_slno1 != null)
menu_slno = Integer.parseInt(menu_slno1);
delete_menu = request.getParameter("delete_menu");
if ("yes".equals(delete_menu)) {
MenuId = request.getParameter("MenuId");
x = stmt1
.executeUpdate("Delete from menu where MenuId="
+ MenuId);
}
%>
<center><h2>VIEW MENU</h2></center>
<center><table width="736" height="97" border="1"></center>
<%
if (x == 1) {
%>
<tr bgcolor="gray">
<th height="35" colspan="9"><div align="center">
Menu deleted successfully!
</div></th>
</tr>
<%
}
%>
<tr bgcolor="gray">
<td><div align="center">
<strong>Menu ID</strong>
</div></td>
<td><div align="center">
<strong>Name </strong>
</div></td>
<td><div align="center">
<strong>Info</strong>
</div></td>
<td><div align="center">
<strong>Price</strong>
</div></td>
<td colspan="2"><div align="center">
<strong>Action</strong>
</div></td>
</tr>
<%
String sUserID=request.getParameter("username");
session.setAttribute("username", sUserID);
int icount = 0;
rs = stmt.executeQuery("SELECT menu.menuID, menu.name, menu.info, menu.price, menu.RestaurantID FROM menu INNER JOIN clients ON menu.username = clients.username where menu.username='" +sUserID+ "'");
while (rs.next()) {
//menu_slno = rs.getInt("menu_slno");
MenuId = rs.getString("MenuId");
%>
<tr>
<td><div align="center"><%=++icount%></div></td>
<td><%=rs.getString("Name")%></td>
<td><%=rs.getString("Info")%></td>
<td><%=rs.getDouble("Price")%></td>
<td><div align="center">
Edit
</div></td>
<td><div align="center">
<a
href="view_menu.jsp?delete_menu=yes&MenuId= <%=MenuId%>&MenuId=<%=MenuId%>"
onclick="return del()">Delete</a>
</div></td>
</tr>
<%
}
%>
</table>
Add Menu
</body>
</html>

When a user clicks on the delete link, the username parameter is not set in the URL. So when the page refreshes, the String sUserID=request.getParameter("username"); call return null or empty, and then the rest of the page is not displayed because the following SQL Query returns nothing without a valid username.
It seems that you only need to add something like &username=<%=sUserID%> to your delete link to make it work:
Delete
P.S: I assume that this a legacy JSP, and that you have no choice but continuing using such ugly code. If you have a choice, I strongly recommend you to drop those scriptlets and this all-in-the-view architecture, and start using JSTL tags, servlets and beans.

Related

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>

How can a execute a query in JSP on text change of input box

Now i am doing this code which is working on submit button click.
<%#page import="java.sql.CallableStatement"%>
<%#page import="javax.imageio.ImageIO"%>
<%#page import="java.io.ByteArrayOutputStream"%>
<%#page import="java.awt.image.BufferedImage"%>
<%#page import="java.io.InputStream"%>
<%#page import="java.sql.ResultSet"%>
<%#page import="connectionss.Connectionss"%>
<%# 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 title here</title>
</head>
<body>
<form action="ShowUSerInfo.jsp" method="post">
<input type="text" name="tagID">
<input type="submit" value="Search" name="submit" >
</form>
<%
String TAGID="";
String y=request.getParameter("submit");
if("Search".equals(y))
{
TAGID = request.getParameter("tagID");
out.println(TAGID);
String GetUserpass = "{call sp_USerInfoByTagID(?)}";
//Connection conn = Connection.GetConnection();
CallableStatement cs;
cs = Connectionss.GetConnection().prepareCall(GetUserpass);
cs.setString(1,TAGID);
%>
<table border="1">
<th>First Name</th>
<th>last Name Name</th>
<th>Student ID</th>
<th>Address</th>
<th>NIC</th>
<%
ResultSet rs1;
rs1=cs.executeQuery();
while(rs1.next()){
String UserName=rs1.getString("fId_FirstName");
String UserID= rs1.getString("fId_User_UniversityID");
String Adress = rs1.getString("fId_Address");
String NIC = rs1.getString("fId_NIC");
String lastName = rs1.getString("fId_LastName");
%>
<tr >
<td><span style="color:red;"><%= UserName %></span></td>
<td> <span style="color:red;"><%= lastName %></span></td>
<td><span style="color:red;"><%= UserID %></span></td>
<td><span style="color:red;"><%= Adress %></span></td>
<td><span style="color:red;"><%= NIC %></span></td>
</tr>
</table>
<%}} %>
</body>
</html>
But i want to execute this code when text changes on input box. Basically text box is getting value from NFC cards. so when i tap my NFC card on Reader value is transfer to text box and at this time i want to execute my sql query that will take the user information against TAGID.
since jsp is server side you'll need to collect the input on client and make a ajax call.
<form action="ShowUSerInfo.jsp" method="post">
<input type="text" id="text" name="tagID">
<input type="submit" value="Search" name="submit" >
</form>
<div id="#res></div>
javascript :
$('#text').change(function(e){
$.ajax({url: "someurl", success: function(result){
$("#res").html(result);
}});
});
});
this will perfectly work in your case,
Let's say our HTML looks something like,
<form>
<input id="txt" type="text" name="name"/>
<input id="btn" type="button" value="change"/>
</form>
Java-Script like,
$(document).ready(function(){
$('#txt').keypress(function(e){
ontextchange();
});
$('#txt').keyup(function(e){
if(e.keyCode == 8)
{
//if user erase from text-box then comes here...
}
});
function ontextchange(){
//do whatever while text change, i.e. ajax call or something else...
}
});

Spring MVC JSP Form using multiple objects needs drop-down list

My Spring JSP Form uses 2 classes that I put in a wrapper class. The employee name part works. But now I need to create a drop-down list of Clients to choose from. I'm updating someone else's code, I believe "resultBoard.getFilteredResultsClients()" will return a List of Clients. Any tips or sample code of a Spring JSP Form that uses a drop-down to select from a List?
Java wrapper class with employee and client classes inside:
public class EmployeeFormWrapper {
private NewEmployeeVM employee = new NewEmployeeVM();
private ClientVM client = new ClientVM();
public NewEmployeeVM getEmployee(){
return this.employee;
}
public ClientVM getClient(){
return this.client;
}
}
My Controller class:
#Controller
#SessionAttributes({"resultBoard", "filterBoard"})
public class NewEmployeeController {
#Autowired
NewEmpDAO newEmpDAO;
#RequestMapping(value = "NewEmpInput", method = RequestMethod.GET)
public String promptEmployee(Model model)
{
model.addAttribute("myForm", new EmployeeFormWrapper());
return "NewEmpInput";
}
#RequestMapping(value = "NewEmpInput", method = RequestMethod.POST)
public String newEmployee(#ModelAttribute("myForm") EmployeeFormWrapper myForm)
{
NewEmployeeVM employee = myForm.getEmployee();
ClientVM client = myForm.getClient();
System.out.println("Employee = " + employee.getFirstName() + " " + employee.getLastName());
System.out.println("Client = " + client.getText());
try{newEmpDAO.writeNewEmployee(employee);}
catch (Exception e){
e.printStackTrace();
}
return "ConfirmNewEmp";
}
}
My JSP:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# page session="false"%>
<%# page import="com.model.FilterBoard"%>
<!DOCTYPE html>
<!-- <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> -->
<html>
<head>
<link rel="stylesheet"
href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link href="assets/css/bootstrap.css" rel="stylesheet">
<link href="assets/css/bootstrap-responsive.css" rel="stylesheet">
<link rel="stylesheet"
href="<c:url value='/resources/css/mainStyle.css'/>">
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<style type="text/css">
body {
color:#000000;
// background-color:#FFFFFF;
background-color:tan;
background-image:url('Background Image');
background-repeat:no-repeat;
}
a { color:#0000FF; }
a:visited { color:#800080; }
a:hover { color:#008000; }
a:active { color:#FF0000; }
</style>
<title>New Employee Proposed To Project</title>
</head>
<body class="NewEmpBody">
<p>New Employee</p>
<form:form commandName="myForm" modelAttribute="myForm">
<table>
<tr>
<td>First Name:</td>
<td><form:input path="employee.firstName" /></td>
<td>Middle Initial:</td>
<td><form:input path="employee.middleInitial" /></td>
</tr>
<tr>
<td>Last Name:</td>
<td><form:input path="employee.lastName" /></td>
</tr>
<tr>
<td>Clients:</td>
<td>
<ul>
<c:forEach items="${resultBoard.getFilteredResultsClients()}"
var="filteredResultsClient">
<li><form:button name="toggleClient" class="btn btn-link"
value='${filteredResultsClient.toJSON()}'>
${filteredResultsClient.getText()}
</form:button></li>
</c:forEach>
</ul>
</td>
</tr>
<tr>
<td colspan="3"><input type="submit" value="Submit" /></td>
</tr>
</table>
</form:form>
</body>
</html>
I got it, I changed my JSP to look like this and it gave me a nice drop-down list:
<body class="NewEmpBody">
<p>New Employee Proposed To Project Before Entered Into OpenAir</p>
<form:form commandName="myForm" modelAttribute="myForm">
<table>
<tr>
<td>First Name:</td>
<td><form:input path="employee.firstName" /></td>
<td>Middle Initial:</td>
<td><form:input path="employee.middleInitial" /></td>
</tr>
<tr>
<td>Last Name:</td>
<td><form:input path="employee.lastName" /></td>
</tr>
<tr>
<td>Client :</td>
<td><form:select path="client.text">
<form:option value="NONE" label="--- Select ---" />
<form:options items="${resultBoard.getFilteredResultsClients()}" />
</form:select>
</td>
</tr>
<tr>
<td colspan="3"><input type="submit" value="Submit" /></td>
</tr>
</table>
</form:form>
</body>

Spring MVC second Post method #ModelAttribute is null

I have a form that has two buttons, a submit button and an update button.
Here is the JSP:
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<!-- Bootstrap core CSS !-->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<!-- Custom scripts/styles for this page !-->
<script type="text/javascript" src="${pageContext.request.contextPath}/static/script/jquery.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/static/script/script.js"></script>
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/static/css/style.css" />
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Test</title>
</head>
<body>
<!-- General Information Form -->
<form:form id="form" method="POST" action="${pageContext.request.contextPath}/create" modelAttribute="task">
<div id="general">
<table style="width: 224px;">
<tr>
<td colspan="2"><form:select id="systemType" path="systemType" items="${systemTypes}" /></td>
</tr>
<tr>
<td id="buffer"></td>
</tr>
<tr>
<td colspan="2"><form:select id="userName" path="user.fullName" items="${userFullNames}" /></td>
</tr>
<tr>
<td id="buffer"></td>
</tr>
<tr>
<td style="width: 50%;"><label for=line><b>Line: </b></label></td>
<td><form:select path="location.line" items="${lines}" id="line"/></td>
</tr>
<tr>
<td id="buffer"></td>
</tr>
<tr>
<td style="width: 50%;"><label for=position><b>Position: </b></label></td>
<td><form:select path="location.position" items="${positions}" id="position" /></td>
</tr>
<tr>
<td id="buffer"></td>
</tr>
<tr>
<td colspan="2">
<input id="submitButton" type="submit" name="submit" value=Submit />
<input style="display:none;" id="updateButton" type="submit" name="update" value="Update" />
<input id="cancel" style="float: right;" type="Reset" value="Cancel" />
</td>
</tr>
</table>
</div>
</form:form>
</body>
</html>
Here is my controller:
#Controller
#RequestMapping("/")
public class HomeController {
private TaskService taskService;
#Autowired
public void setTaskService(TaskService taskService) {
this.taskService = taskService;
}
#RequestMapping(value = "/", method = RequestMethod.GET)
public String initForm(Model model, HttpServletRequest request) {
Task task = new Task();
model.addAttribute("task", task);
return "home";
}
#RequestMapping(value="/create", params="submit", method = RequestMethod.POST)
public String submitForm(#ModelAttribute("task")Task task,BindingResult result, Model model) {
taskService.create(task);
return "redirect:/";
}
#RequestMapping(value="/create", params="update", method = RequestMethod.POST)
public String updateForm(#ModelAttribute("task")Task task, BindingResult result, Model model) {
System.out.println("Updating: " + task.toString());
taskService.update(task);
return "redirect:/";
}
The idea being that hitting the submit button will make a new item, and the update button will edit an existing one. The two .POST methods have different parameters specified to distinguish them.
The submit button is working as expected. However when the update button is pressed a Task object is delivered to the updateForm controller method - but all of its fields are null.
I am not sure why the form is binding the fields to the Task correctly on the submit method, but seemingly creating a new Task and not binding it at all in the update method.
I am inclined to just combine these methods into a single controller method and use some Java logic to determine whether to submit/update based on the parameter - but am curious as to what I'm missing and why this doesn't work.
Ok, I feel very stupid. This was not a SpringMVC issue at all. The problem was caused by a Jquery method that was disabling a part of the form. This gave the appearance that the form was not binding, but actually it was just binding to null values.

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