How to access dynamically created text box in jsp page - java

How can I access the values in the textBox to pass it into a SQL database. What will be the text-box's unique name in each row?
The code is as follows:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%# page import="java.sql.*" %>
<%# page import="java.io.*" %>
<html>
<head><title>orderSample</title>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(document).ready(function() {
$('.add').click(function() {
$(this).closest('tr').find('.quantity').attr('disabled', !this.checked);
});
});
</script>
</head>
<body bgcolor="white">
<form method=post name=orderForm>
<h1>Data from the table 'item details' of database 'caffe' in sql </h1>
<%
System.out.println("adadadasasasasasasasasas");
int i = 0;
%>
<TABLE cellpadding="15" border="1" style="background-color: #ffffcc;">
<TR>
<TD>ORDER ID</TD>
<TD>ORDER PRICE</TD>
<TD>Quantity</TD>
<TD>Add Item</TD>
</TR>
<%do{
System.out.println("I am in Ob");
%>
<TR>
<TD>asdadsas</TD>
<TD>asdasdasd</TD>
<td><input type="checkbox" class="add" /></td>
<td><input type="text" class="quantity" /></td>
<!-- <td><INPUT TYPE="TEXT" NAME="NAME_TEXT<%=i%>" VALUE="" IsEnabled="{Binding ElementName=checkBox1, Path=IsChecked}"/></td>
<td><INPUT TYPE="TEXT" NAME="NAME_TEXT<%=i%>" VALUE="" /></td>
<td><input type="checkbox" name="others<%=i%>" onclick="enable_text(this.checked,<%=i%>)" ></td>-->
</TR>
<%i++; }while(i<2); %>
</TABLE>
</form>
</body>
</html>

Either give them all the same name
<td><input type="text" name="name" /></td>
so that you can use
String[] values = request.getParameterValues("name");
Or give them all the same prefix
<td><input type="text" name="name${someDynamicValue}" /></td>
so that you can use
for (Entry<String, String[]> entry : request.getParameterMap().entrySet()) {
if (entry.getKey().startsWith("name")) {
String value = entry.getValue()[0];
// Add to list?
}
}
Or when it is an incremental suffix
<td><input type="text" name="name${index}" /></td>
then use
for (int i = 0; i < Integer.MAX_VALUE; i++) {
String value = request.getParameter("name" + i);
if (value == null) {
break;
}
// Add to list?
}

Related

Webapp Not working only in Chrome, but working in FireFox and Eclipse Default Browser

I'm writing a web app. First I'll Explain the process, followed by code and finally the problem.
I've 2 identical jsps, index.jsp and GetCaseData.jsp
Here there are 2 buttons one in the top and the other at the bottom. and initially, the second button is disabled
When I hit the Get case Button. the data from database gets fetched into the textboxes(GetCaseData.jsp) and the submit box gets enabled and the getcase gets disabled.
When I hit submit, the data gets saved to another table in DB
Below are the codes.
Index.jsp
<%#page import="org.bean.UserBean"%>
<%# 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"%>
<!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">
<script type="text/javascript"
src="http://code.jquery.com/jquery-1.10.0.min.js"></script>
<link rel="stylesheet" type="text/css" href="myCssFile.css">
<title>Insert title here</title>
<script type="text/javascript">
function enableSubmit() {
document.getElementById("getCase").disabled = true;
document.getElementById("submitButton").disabled = false;
}
function enableGetCase() {
document.getElementById("getCase").disabled = false;
document.getElementById("submitButton").disabled = true;
}
</script>
</head>
<body>
<div class="header" id="header">
<form id="form1"></form>
</div>
<div class="bodytag">
<form method="get" action="GetData">
<input type="Submit" value="Get Case" name="getCase" id="getCase"
onclick="enableSubmit()" />
<table>
<tr>
<td>Case Number</td>
<td><input id="Text1" type="text" value="" /></td>
<td>Case Owner</td>
<td><input id="Text6" type="text" value="" /></td>
</tr>
<tr>
<td>Source</td>
<td><input id="Text2" type="text" /></td>
<td>Status</td>
<td><input id="Text7" /></td>
</tr>
<tr>
<td class="auto-style2">Issue</td>
<td class="auto-style2"><input id="Text3" value="" type="text" /></td>
<td class="auto-style2">Reason</td>
<td class="auto-style2"><input id="Text8" value="" type="text" /></td>
</tr>
<tr>
<td>Date/Time Opened</td>
<td><input id="Text4" type="text" value="" /></td>
<td>Age(Days)</td>
<td><input id="Text10" type="text" value="" /></td>
</tr>
<tr>
<td>Resolution</td>
<td><select id="Select1" name="D1">
<option></option>
</select></td>
<td>Final Status</td>
<td><select id="Select2" name="D2">
<option value=" "></option>
</select></td>
</tr>
<tr>
<td>Start Time</td>
<td><input id="Text5" type="text" value="Start Time" /></td>
<td>End Time</td>
<td><input id="Text9" type="text" value="end Time" /></td>
</tr>
</table>
<input type="button" value="Submit" name="submitButton"
id="submitButton" disabled="disabled" onClick="enableGetCase()" />
</form>
</div>
<script type="text/javascript" src="SampleJS.js"></script>
</body>
Servlet
package org.servlet;
import org.DAO.*;
import org.bean.UserBean;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet("/GetData")
public class GetData extends HttpServlet {
private static final long serialVersionUID = 1L;
public GetData() {
super();
}
GetDataDAO getdatadao = null;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// set content type
try {
getdatadao = new GetDataDAO();
List<UserBean> userBeans = getdatadao.list();
request.setAttribute("userBeans", userBeans);
request.getRequestDispatcher("GetCaseData.jsp").forward(request, response);
} catch (Exception e) {
e.printStackTrace();
}
}
}
GetDataDAO
package org.DAO;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import org.bean.UserBean;
import org.code.general.DBConnection;
public class GetDataDAO {
DBConnection dbConnection = new DBConnection();
public List<UserBean> list() throws Exception {
List<UserBean> userBeans = new ArrayList<UserBean>();
try {
String userName = new com.sun.security.auth.module.NTSystem().getName();
System.out.println(userName);
Connection conn = dbConnection.getConn();
Statement stmt = dbConnection.getStmt();
ResultSet rs = dbConnection.getRs();
String excelPath = dbConnection.getExcelPath();
String queryString = null;
dbConnection.createClassForNameForExcel();
conn = DriverManager.getConnection(
"jdbc:odbc:Driver={Microsoft Excel Driver (*.xls)};DBQ=" + excelPath + "; READONLY=FALSE;");
System.out.println("Connecting to database…");
System.out.println("Oracle JDBC Driver Registered!");
if (conn != null) {
System.out.println("You made it, take control your database now!");
} else {
System.out.println("Failed to make connection!");
}
stmt = conn.createStatement();
queryString = "Select * from [report1448039568905$] where STATE IS NULL";
rs = stmt.executeQuery(queryString);
ResultSetMetaData rsmd = rs.getMetaData();
// int rowCount = rsmd.getColumnCount();
System.out.println("bno of cols are " + rsmd.getColumnCount());
while (rs.next()) {
UserBean userBean = new UserBean();
userBean.setCaseNumber(rs.getString(1));
userBean.setCaseOwner(rs.getString(2));
userBean.setStatus(rs.getString(4));
userBean.setIssue(rs.getString(5));
userBean.setReason(rs.getString(6));
userBean.setDateOpened(rs.getString(7));
userBean.setAge(rs.getInt(8));
userBeans.add(userBean);
}
rs.close();
conn.commit();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
return userBeans;
}
}
SampleJS.js
$(window).load(
function() {
$("#form1").on(
'submit',
function(e) {
$.ajax({
type : "get",
url : "GetTheCounts",
data : $(this).serialize(),
success : function(msg) {
console.log(JSON.stringify(msg));
var $span = $('<span class="totalTime">')
.appendTo($('#header'));
$span.append("Status: (Worked/Total) -")
.append("\t\t\t\t\t").append(
msg.DAOCount).append("/")
.append(msg.excelCount);
var $span1 = $('<span class="effeciency">')
.appendTo($('#header'));
$span1.append("Effeciency : ").append(
msg.effeciency);
}
});
e.preventDefault();
}).submit();
});
GetCaseData.jsp
<%#page import="org.bean.UserBean"%>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#page import="java.util.*"%>
<%#page import="java.text.SimpleDateFormat"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!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>
<script type="text/javascript"
src="http://code.jquery.com/jquery-1.10.0.min.js"></script>
<link rel="stylesheet" type="text/css" href="myCssFile.css">
<script type="text/javascript">
function enableSubmit() {
document.getElementById("getCase").disabled = true;
document.getElementById("submitButton").disabled = false;
}
function enableGetCase() {
document.getElementById("getCase").disabled = false;
document.getElementById("submitButton").disabled = true;
}
function dynamicdropdown(listindex) {
document.getElementById("subcategory").length = 0;
switch (listindex) {
case "closed":
document.getElementById("subcategory").options[0] = new Option(
"Please select framework", "");
document.getElementById("subcategory").options[1] = new Option(
"Closed", "Closed");
document.getElementById("subcategory").options[2] = new Option(
"Cash Apps/Financial Processing",
"Cash Apps/Financial Processing");
break;
case "open":
document.getElementById("subcategory").options[0] = new Option(
"Please select framework", "");
document.getElementById("subcategory").options[1] = new Option(
"Waiting For BLUP", "Waiting For BLUP");
document.getElementById("subcategory").options[2] = new Option(
"Waiting for Clarification from Rep",
"Waiting for Clarification from Rep");
document.getElementById("subcategory").options[3] = new Option(
"Waiting for Supervisor Assistance",
"Waiting for Supervisor Assistance");
document.getElementById("subcategory").options[4] = new Option(
"Need to route the case to Cash Apps/FP",
"Need to route the case to Cash Apps/FP");
document.getElementById("subcategory").options[5] = new Option(
"Waiting for Approval", "Waiting for Approval");
document.getElementById("subcategory").options[6] = new Option(
"Send Updated Invoice", "Send Updated Invoice");
break;
case "reassigned":
document.getElementById("subcategory").options[0] = new Option(
"Please select framework", "");
document.getElementById("subcategory").options[1] = new Option(
"Assigned to other agent", "Assigned to other agent");
document.getElementById("subcategory").options[2] = new Option(
"Assigned to other queue", "Assigned to other queue");
break;
}
return true;
}
var date = Date.parse(new Date());
function getLastDate() {
var date = new Date();
document.getElementById("endTime").value = [ date.getMonth() + 1,
date.getDate(), date.getFullYear() ].join('/')
+ ' '
+ [ date.getHours(), date.getMinutes(), date.getSeconds() ]
.join(':');
setTimeout(function() {
document.getElementById("myForm").submit();
}, 3000);
}
</script>
</head>
<body>
<div class="header" id="header">
<form id="form1"></form>
</div>
<div class="bodytag">
<form method="post" id="myForm" action="PostData">
<%
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
String startFormattedDate1 = sdf.format(date);
Date d1 = sdf.parse(startFormattedDate1);
date = new Date();
String startFormattedDate2 = sdf.format(date);
%>
<input type="Submit" value="Get Case" name="getCase" id="getCase"
disabled="disabled" />
<table>
<tr>
<td>Case Number</td>
<td><input id="caseNumber" name="caseNumber" type="text"
value="${userBeans[0].getCaseNumber()}" /></td>
<td>Case Owner</td>
<td><input id="caseOwner" name="caseOwner" type="text"
value="${userBeans[0].getCaseOwner()}" /></td>
</tr>
<tr>
<td>Source</td>
<td><input id="source" name="source" type="text" /></td>
<td>Status</td>
<td><input id="status" name="status" type="text"
value="${userBeans[0].getStatus()}" /></td>
</tr>
<tr>
<td class="auto-style2">Issue</td>
<td class="auto-style2"><input id="issue" name="issue"
value="${userBeans[0].getIssue()}" type="text" /></td>
<td class="auto-style2">Reason</td>
<td class="auto-style2"><input id="reason" name="reason"
value="${userBeans[0].getReason()}" type="text" /></td>
</tr>
<tr>
<td>Date/Time Opened</td>
<td><input id="dateOpened" type="text" name="dateOpened"
value="${userBeans[0].getDateOpened()}" /></td>
<td>Age(Days)</td>
<td><input id="age" type="text" name="age"
value="${userBeans[0].getAge()}" /></td>
</tr>
<tr>
<td>Resolution</td>
<td><select id="Select1" name="resolution"
onchange="javascript: dynamicdropdown(this.options[this.selectedIndex].value);">
<option value="" disabled selected>Select</option>
<option value="closed" id="closed">Closed</option>
<option value="open" id="open">Open</option>
<option value="reassigned" id="reassigned">Reassigned</option>
</select></td>
<td>Final Status</td>
<td><select name="finalStatus" id="subcategory">
<option value="" disabled selected>Please select
framework</option>
</select></td>
</tr>
<tr>
<td>Start Time</td>
<td><input id="startTime" type="text" name="startDate"
value="<%=startFormattedDate1%>" /></td>
<td>End Time</td>
<td><input id="endTime" name="endDate" type="text" /></td>
</tr>
</table>
<input type="button" value="Submit Form" onclick="getLastDate()"
id="postData" name="postData" />
</form>
</div>
<script type="text/javascript" src="SampleJS.js"></script>
</body>
</html>
The problem is this program doesn't run fine in Chrome, but in FireFox and Eclipse default browser it works fine.
In Chrome, only the toggling of buttons happen. Enable and disabling of both the buttons. There is no data fetched into textboxes or there is no submission to DB done.
Below are the screenshots of Chrome and FF after I click the Get Case button.
Chrome O/P:
FireFox O/P:

Struts2 form validation with annotation and input tag [duplicate]

This question already has answers here:
How to use css styles in struts2 tags?
(2 answers)
How to validate HTML tag using Struts 2
(3 answers)
Closed 7 years ago.
I am learning form validation in struts2. I have successfully implemented it and it's showing an error message on jsp page when text field is blank. But now I remove <s:textfield> and instead of it I am using <input type="text"> tag. Now this is not working can any one please let me know how to achieve this ?
following is my code
#Namespace("/User")
#ResultPath("/")
#Result(name = "input", location = "pages/registration.jsp")
public class UserAction extends ActionSupport implements ServletRequestAware, ModelDriven<User>
{
/**
*
*/
private static final long serialVersionUID = 1L;
User user = new User();
private HttpServletRequest servletRequest;
List<User> users = new ArrayList<User>();
public User getModel()
{
return user;
}
public User getUser()
{
return user;
}
public void setUser(User user)
{
this.user = user;
}
public HttpServletRequest getServletRequest()
{
return servletRequest;
}
public void setServletRequest(HttpServletRequest servletRequest)
{
this.servletRequest = servletRequest;
}
public List<User> getUsers()
{
return users;
}
public void setUsers(List<User> users)
{
this.users = users;
}
#Action(value = "register", results = {#Result(name = "input", location = "pages/registration.jsp"), #Result(name = "success", location = "pages/registration.jsp")})
// #InputConfig(methodName = "registeruser")
public String register()
{
return SUCCESS;
}
#Action(value = "registeruser", results = {#Result(location = "pages/welcome.jsp")})
public String registeruser()
{
UserDao userDao = new UserDaoImpl();
try
{
String uploadFilePath = servletRequest.getSession().getServletContext().getRealPath("/").concat("/User/images");
CommonUtils.uploadFile(user.getFile(), uploadFilePath, user.getFileFileName());
userDao.save(user, uploadFilePath);
}
catch (Exception e)
{
System.out.println(e);
}
return SUCCESS;
}
public void validate()
{
System.out.println("in");
if ("".equals(user.getFirstName()))
{
addFieldError("firstName", "First name should not be blank");
}
if ("".equals(user.getLastName()))
{
addFieldError("lastName", "Last name should not be blank");
}
}
}
Jsp Page
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# taglib uri="/struts-tags" prefix="s" %>
<!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>Registration</title>
</head>
<body>
<form action="registeruser" method="post" enctype="multipart/form-data">
<s:actionerror/>
<table>
<tr>
<td>First Name</td>
<td><input type="text" name="firstName" id="firstName"></td>
<%-- <td><s:textfield name="firstName"></s:textfield></td> --%>
</tr>
<tr>
<td>Last Name</td>
<td><input type="text" name="lastName" id="lastName"></td>
</tr>
<tr>
<td>Contact Number</td>
<td><input type="text" name="contactNumber" id="contactNumber"></td>
</tr>
<tr>
<td>Email</td>
<td><input type="text" name="email" id="email"></td>
</tr>
<tr>
<td>Address</td>
<td><textarea rows="5" cols="50" name="address" id="address"></textarea></td>
</tr>
<tr>
<td>Gender</td>
<td><input type="radio" name="gender" id="male" value="male">Male<br />
<input type="radio" name="gender" id="female" value="female">Female</td>
</tr>
<tr>
<td>Degree</td>
<td><input type="checkbox" name="degree" id="graduation"
value="graduation">Graduation<br />
<input type="checkbox" name="degree" id="postgraduation"
value="postgraduation">Post Graduation</td>
</tr>
<tr>
<td>Technology</td>
<td><select name="technology" id="technology">
<optgroup label="Java">
<option value="spring">Spring</option>
<option value="hibernate">Hibernate</option>
<option value="struts2">Struts2</option>
</optgroup>
<optgroup label=".Net">
<option value="asp">ASP</option>
<option value="vb.net">VB.NET</option>
</optgroup>
</select></td>
</tr>
<tr>
<td>Upload file</td>
<td><input type="file" name="file" id="file"></td>
</tr>
<tr>
<td><input type="submit" value="Save"></td>
</tr>
</table>
</form>
</body>
</html>
If you remove the <s:textfield /> and use instead a plain HTML <input type="text" />, you need to manually implement the features that otherwise would have been provided by the framework's tag.
Struts2 uses themes to generate HTML, and with the default theme (XHTML), a fieldError is generated automatically. Also remind that with a plain HTML tag, you need to manually set the value. I recommned you to keep using Struts2 tags, but to answer the question, the equivalent of
<s:textfield name="firstName" />
in plain HTML is
<input type="text" name="firstName" value="<s:properry value='firstName'>" />
<s:fielderror fieldName="firstName" />

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>

Clear Cart button in Java

Hi I'm trying to make a "Clear Cart" button in my java code but i'm having difficulty.
I've been trying for a couple of hours but i can't get it to work
I think it has something to do mostly with the first part that has all the strings and variables.
Here's the code:
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<%# page errorPage="errorpage.jsp" %>
<jsp:useBean id="cart" scope="session" class="beans.ShoppingCart" />
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>the Game Store</title>
</head>
<body>
<%
String id = request.getParameter("id");
if ( id != null ) {
String desc = request.getParameter("desc");
Float price = new Float(request.getParameter("price"));
cart.addItem(id, desc, price.floatValue(), 1);
}
%>
Shopping Cart Quantity:
<%=cart.getNumOfItems() %>
<hr>
<center><h3>Games</h3></center>
<table border="1" width="300" cellspacing="0"
cellpadding="2" align="center">
<tr><th>Description</th><th>Price</th></tr>
<tr>
<form action="AddToShoppingCart.jsp" method="post">
<td>Goat Simulator</td>
<td>$11.95</td>
<td><input type="submit" name="Submit" value="Add"></td>
<input type="hidden" name="id" value="1">
<input type="hidden" name="desc" value="Goat Simulator">
<input type="hidden" name="price" value="11.95">
</form>
</tr>
<tr>
<form action="AddToShoppingCart.jsp" method="post">
<td>Metal Gear Solid V</td>
<td>$59.99</td>
<td><input type="submit" name="Submit" value="Add"></td>
<input type="hidden" name="id" value="2">
<input type="hidden" name="desc" value="Metal Gear Solid V">
<input type="hidden" name="price" value="59.99">
</form>
</tr>
<tr>
<form action="AddToShoppingCart.jsp" method="post">
<input type ="submit" name="empty" id="empty-button" value="Empty Cart"/>
</form>
Clear
</tr>
</table>
</body>
</html>
Here's the second page for the entire page
<%# page errorPage="errorpage.jsp" %>
<%# page import="java.util.*" %>
<jsp:useBean id="cart" scope="session" class="beans.ShoppingCart" />
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>Shopping Cart Contents</title>
</head>
<body>
<center>
<table width="300" border="1" cellspacing="0"
cellpadding="2" border="0">
<caption><b>Shopping Cart Contents</b></caption>
<tr>
<th>Description</th>
<th>Price</th>
<th>Quantity</th>
</tr>
<%
Enumeration e = cart.getEnumeration();
String[] tmpItem;
// Iterate over the cart
while (e.hasMoreElements()) {
tmpItem = (String[])e.nextElement();
%>
<tr>
<td><%=tmpItem[1] %></td>
<td align="center">$<%=tmpItem[2] %></td>
<td align="center"><%=tmpItem[3] %></td>
</tr>
<%
}
%>
</table>
</center>
Back to Catalog
</body>
</html>

JAVA String error in JSP

Im getting a curious error with an ArrayList, below is the code (note that this code was copied from an online servlet example, I am a JAVA novice).
the JSP:
<%#page import="p.SecondExample"%>
<%# page language="java" import="java.util.*;"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>Servlet Application</TITLE>
<script language="javascript">
function editRecord(id){
window.location.href="editServlet/"+id;
}
function deleteRecord(id){
window.location.href="deleteUser/"+id;
}
</script>
</HEAD>
<BODY>
<br>
<table align="center">
</table>
<br>
<table width="600px" align="center" style="background-color:#EDF6EA;border:1px solid #000000;">
<tr><td colspan=9 align="center" height="10px"></td></tr>
<tr><td colspan=9 align="center"><!-- Add New User--></td></tr>
<tr><td colspan=9 align="center" height="10px"></td></tr>
<tr style="background-color:#7BA88B;font-weight:bold;">
<td>Sector Segment</td><td>Color</td>
</tr>
<%
String bgcolor="";
int count=0;
List viewList = new ArrayList();
Iterator viewItr;
SecondExample se = new SecondExample();
se.doPost(request, response);
if(request.getAttribute("userList")!=null && request.getAttribute("userList")!="")
{
List userList = (ArrayList)request.getAttribute("userList");
Iterator itr = userList.iterator();
System.out.println(userList);
while(itr.hasNext())
{
if(count%2==0)
{
bgcolor = "#C8E2D1";
}
else
{
bgcolor = "#EAF8EF";
}
viewList = (ArrayList)itr.next();
int id = Integer.parseInt(viewList.get(0).toString());
viewItr = viewList.iterator();
%>
<tr style="background-color:<%=bgcolor%>;">
<%
while(viewItr.hasNext())
{
%>
<td><%=viewItr.next()%></td>
<%
}
count++;
%>
<td><input type="button" name="edit" value="Edit" style="background-color:#49743D;font-weight:bold;color:#ffffff;" onclick="editRecord(<%=id%>);" ></td>
<td><input type="button" name="delete" style="background-color:#ff0000;font-weight:bold;;color:#ffffff;" value="Delete" onclick="deleteRecord(<%=id%>);"></td>
</tr>
<%
}
}
if(count==0)
{
%>
<tr><td colspan="9" align="center"> </td></tr>
<tr><td colspan="9" align="center">No Record Avaliable</td></tr>
<%
}
%>
<tr><td colspan=9 align="center" height="2px"></td></tr>
</table>
</BODY>
</HTML>
in debug, the error appears to occur with:
viewList = (ArrayList)itr.next();
int id = Integer.parseInt(viewList.get(0).toString());
viewItr = viewList.iterator();
where my error appears as:
org.apache.jasper.JasperException: java.lang.ClassCastException: java.lang.String cannot be cast to java.util.ArrayList
I'm not quite sure why or how to make next a string. Any help is greatly appreciated.
Yep, itr.next() returns a String, which cannot be cast into an ArrayList.
String value = (String) itr.next();
int id = Integer.parseInt(value);
The following few lines of code in which you're iterating over your viewArray can be removed now, too.

Categories

Resources