I am outputting the contents of a product from a product object(containing catalog no, product name, vendor, price, quantity(a textbox) and a checkbox(to select the product)) as a tabular display. When a user checks a checkbox(indicating the product checked), I get the values into a servlet. However, when I have to get the qty(which is a text box array), I am unable to get values for which the product checkbox is checked. Instead , I get the values of the qty for all products on the page irrespective of whether they are checked or not. How can I modify this behavior so that I only get the qty values for the products that are checked and added to cart?

Recommended Answers

All 6 Replies

Can you post the code you have at the jsp page?

Can you post the code you have at the jsp page?

Here is the code.

1. The Product(in this case chemical) object and that builds the table

package com.classes.chemical;
import java.sql.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.servlet.http.*;

public class Chemical 
{
protected String catNo;

protected String chemicalName;

protected float price;
protected String vendor;
protected String category;
protected String qty;
protected final String CR = "\n";



public Chemical(ResultSet rs)
{
	try
	{
			
	catNo=rs.getString("CatalogNo");
	chemicalName=rs.getString("Chemical_Name");
	//unt=rs.getString("UNIT");
	price=rs.getFloat("PRICE");
	vendor=rs.getString("VENDOR");
	category=rs.getString("category");
	}
	catch(SQLException e)
	{
		e.printStackTrace();
	}
}
public String toTableString(int rowNumber)
{
	
	String replyString="";
	String tdBegin = "<td>";
	
	String checkBox = "<input type = \"checkbox\" name = chem[] value = "+catNo+" >";
	String textBox = "<input type = \"textbox\" name = qty[] size = \"5\" value = \"1\">";
	String tdEnd = "</td>" + CR;
	replyString += "<tr>"+CR;
	replyString +=tdBegin + rowNumber + tdEnd;
	replyString +=tdBegin + catNo + tdEnd;
	replyString +=tdBegin + chemicalName+ tdEnd;
	//replyString +=tdBegin + unt+ tdEnd;
	replyString +=tdBegin + price + tdEnd;
	replyString +=tdBegin + vendor + tdEnd;
	replyString +=tdBegin + category+ tdEnd;
	replyString +=tdBegin + textBox + tdEnd;
	replyString +=tdBegin + checkBox + tdEnd;
	
	return replyString;
}
}

2. Code that builds the HTML tabular display

package com.classes.click;
import com.classes.chemical.*;

	public static void displayHTML(HttpServletResponse response, ResultSet r)
	{
		 
		String CR = "\n";
		Chemical chemi = null;
		try {
			//build the HTML page heading
			String htmlHead = "<html><head><title>List of Chemicals</title></head></html>" +CR;
			//build the HTML body
			String htmlBody="<body><center>" +CR;
			htmlBody +="<h1>Chemical List</h1>" +CR;
			htmlBody +="<hr></center><p>" +CR;
			htmlBody +="<form action = \"CartServlet\" method = \"Post\" >" +CR;
			//build the table heading
			String tableHead = "<center><table border width=100% cellpadding=5>" +CR;
			tableHead +="<tr>" +CR;
			//tableHead +="<th></th>" +CR;
			tableHead +="<th>Sl No </th>" +CR;
			tableHead +="<th>Catalog NO</th>" +CR;
			tableHead +="<th>Chemical Name</th>" +CR;
			//tableHead +="<th>Unit</th>" +CR;
			tableHead +="<th>Price</th>" +CR;
			tableHead +="<th>Vendor</th>" +CR;
			tableHead +="<th>Category</th>" +CR;
			tableHead +="<th>Qty</th>" +CR;
			tableHead +="<th><input type = \"Submit\" value = \"Add to Cart\"></th>";
			
			
			//build the table body
			String tableBody = "";
			int rowNumber=1;
			while(r.next())
			{
				chemi = new Chemical(r);
				tableBody +=chemi.toTableString(rowNumber);
				rowNumber++;
			}
			
			
			//build the table bottom
			String tableBottom = "</table></center>";
			
			//build html page bottom
			String htmlBottom = "</form></body></html>";
			
			//build complete HTML page
			htmlBody +=tableHead + tableBody + tableBottom;
			htmlBody += "<p><hr>";
			String htmlPage = htmlHead +htmlBody + htmlBottom;
			
			//send the data to the browser
			PrintWriter outputToBrowser = new PrintWriter(response.getOutputStream());
			response.setContentType("text/html");
			outputToBrowser.println(htmlPage);
			outputToBrowser.close();
		} catch (Exception e) {
			
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

3. Code that processes the cart selections. Here I want to be able to process the qty[] for each chemical checked. I am unable to do that.

static DbConnect dbc = new DbConnect();
		private void processRequest(HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException, SQLException {
		logg("Request received");
		HttpSession session = request.getSession();
		Connection conn=dbc.openCon();
		Statement st=null;
	   	PreparedStatement stmt=null;
		ResultSet rs=null;
		
		String [] chemname = new String[200];
		chemname = request.getParameterValues("chem[]");
		int size = chemname.length;
		String [] qty1 = new String[200];
		
		
		 
		 
		      List<String> catalogno = Arrays.asList(chemname);  
		   
		   
		  
		   
		      for (String ex : catalogno)  
		       {  
		          System.out.println(ex);  
		st=conn.createStatement();
		      	
		ResultSet rx = Cart.cartRead(ex);
		while(rx.next())
		{
			
			String catNo1 = rx.getString("CATALOGNO");
			String chemicalName1 = rx.getString("CHEMICAL_NAME");
			float price1 = rx.getFloat("PRICE");
			String vendor1 = rx.getString("VENDOR");
			String category1 = rx.getString("CATEGORY");
			String requestor = (String) session.getAttribute("user");
			
			String ins="INSERT INTO dbo.manager_cart2(CATALOGNO,CHEMICAL_NAME, PRICE, VENDOR, CATEGORY, REQUESTOR, VALIDATION) values ('"+catNo1+"', '"+chemicalName1+"',  "+price1+", '"+vendor1+"', '"+category1+"', '"+requestor+"', 'new')";
			
			stmt=conn.prepareStatement(ins);
			stmt.executeUpdate();
		}
		}

I am a beginner JAVA programmer and so I am using old school code

First of all the Chemical class is not correct.
You need to make it more general. What if you want to create an instance of that object with values from somewhere else. Not a ResultSet.
Add another constructor with no arguments and get/set methods

public float getPrice() {
  return price;
}

public void setPrice(float pr) {
  price = pr;
}

At the toTableString method the input tag is wrong. You need to have quotes at the value attribute like this:

<input type = \"tex\" name = "qty[]" size = \"5\" value = \"1\">

What you do with size and value needs to be done with name as well: name = "qty"
Also:
"<input type = \"checkbox\" name = "chem" value = \""+catNo+"\" >"

Although the above advice will not be used because you will delete the toTableString method. Never write that kind of code.
Put it into a jsp!

<input type = "checkbox" name = "chem" value = "<%=catNo%>" >

See. Much easier without having to worry aboyut escape characters for the ""
If you don't know what this is <%=catNo%> then you need a lot more studying to do.

You will also need to delete the displayHTML. Don't use servlets to display HTML code. Put it in a jsp. It is a lot easier
Also there is no such thing as a type="textBox". Better study some html. Look at this:
http://www.w3schools.com

About your problem. If you want only one product selected at a time then use radio buttons:

<input type="radio" name = "catNo" value = "<%=catNo%>" >

You will have many radio butons with the same name, that is why only one would be selected.
So when you do this:

String catNo1 = request.getParameter("catNo");

You will have one value. The one selected. If you want to get the other attributes as well you can do this at the jsp:

<input type = "text" name="qty_<%=catNo%>" size = "5" value = "1">
<!-- or/and -->
<input type = "text" name="name_<%=catNo%>" size = "10" value = "">

After you submit and get the catNo, you can get the specific row of the radio buton selected:

String catNo1 = request.getParameter("catNo");

String qty1 = request.getParameter("qty_"+catNo1);
String name1 = request.getParameter("name_"+catNo1);

All the code that displays will go at the jsp. You can still submit to a servlet run the queries and then redirect back to the jsp.
That means you will need to change the way you read the Chemicals.

You have put a lot of code where it doesn't belongs and it is messed up.

Remove the ResultSet from the Chemical class. You don't need to carry it around.
In the method where you run the select query and you get the ResultSet you will while loop it. You will create a new Chemical instance each time and put it into an ArrayList. Check its API. It has a add method as well a get method.

So one method that returns a list with Chemicals in its own class.
One method that updates with argument one Chemical instance.
One method that inserts with argument one Chemical instance.

In the jsp for example you will call the read method and display. Then you will submit to a servlet if you wish, read the request, call the update/insert method and redirect to the jsp. Look examples with the RequestDispatcher class.

First of all the Chemical class is not correct.
You need to make it more general. What if you want to create an instance of that object with values from somewhere else. Not a ResultSet.
Add another constructor with no arguments and get/set methods

public float getPrice() {
  return price;
}

public void setPrice(float pr) {
  price = pr;
}

At the toTableString method the input tag is wrong. You need to have quotes at the value attribute like this:

<input type = \"tex\" name = "qty[]" size = \"5\" value = \"1\">

What you do with size and value needs to be done with name as well: name = "qty"
Also:
"<input type = \"checkbox\" name = "chem" value = \""+catNo+"\" >"

Although the above advice will not be used because you will delete the toTableString method. Never write that kind of code.
Put it into a jsp!

<input type = "checkbox" name = "chem" value = "<%=catNo%>" >

See. Much easier without having to worry aboyut escape characters for the ""
If you don't know what this is <%=catNo%> then you need a lot more studying to do.

You will also need to delete the displayHTML. Don't use servlets to display HTML code. Put it in a jsp. It is a lot easier
Also there is no such thing as a type="textBox". Better study some html. Look at this:
http://www.w3schools.com

About your problem. If you want only one product selected at a time then use radio buttons:

<input type="radio" name = "catNo" value = "<%=catNo%>" >

You will have many radio butons with the same name, that is why only one would be selected.
So when you do this:

String catNo1 = request.getParameter("catNo");

You will have one value. The one selected. If you want to get the other attributes as well you can do this at the jsp:

<input type = "text" name="qty_<%=catNo%>" size = "5" value = "1">
<!-- or/and -->
<input type = "text" name="name_<%=catNo%>" size = "10" value = "">

After you submit and get the catNo, you can get the specific row of the radio buton selected:

String catNo1 = request.getParameter("catNo");

String qty1 = request.getParameter("qty_"+catNo1);
String name1 = request.getParameter("name_"+catNo1);

All the code that displays will go at the jsp. You can still submit to a servlet run the queries and then redirect back to the jsp.
That means you will need to change the way you read the Chemicals.

You have put a lot of code where it doesn't belongs and it is messed up.

Remove the ResultSet from the Chemical class. You don't need to carry it around.
In the method where you run the select query and you get the ResultSet you will while loop it. You will create a new Chemical instance each time and put it into an ArrayList. Check its API. It has a add method as well a get method.

So one method that returns a list with Chemicals in its own class.
One method that updates with argument one Chemical instance.
One method that inserts with argument one Chemical instance.

In the jsp for example you will call the read method and display. Then you will submit to a servlet if you wish, read the request, call the update/insert method and redirect to the jsp. Look examples with the RequestDispatcher class.

I cant use a radio button, I have to use a checkbox because I have to select multiple products. So when I say I check 4 checkboxes with 4 different products, I would like to get the qty for only those 4 . How can I do that?

I cant use a radio button, I have to use a checkbox because I have to select multiple products. So when I say I check 4 checkboxes with 4 different products, I would like to get the qty for only those 4 . How can I do that?

In the way I described. Only this time you will use the method that returns an array, you will loop the array in order to have the catNo and use the parametetric request.getParameter in order to get the rest for each row:

String [] catNos = request.getParameterValues("catNo"); // this time catNo is the name of the check box
     
for (int i=0;i<catNos.length;i++) {
  String qty1 = request.getParameter("qty_"+catNos[i]);
  String name1 = request.getParameter("name_"+catNos[i]);
}

Each element of the catNos will have the CATALOGNO of each row selected and in the loop you will get the values of the each of the other elements, provided that you declared the input tags as described.

In the way I described. Only this time you will use the method that returns an array, you will loop the array in order to have the catNo and use the parametetric request.getParameter in order to get the rest for each row:

String [] catNos = request.getParameterValues("catNo"); // this time catNo is the name of the check box
     
for (int i=0;i<catNos.length;i++) {
  String qty1 = request.getParameter("qty_"+catNos[i]);
  String name1 = request.getParameter("name_"+catNos[i]);
}

Each element of the catNos will have the CATALOGNO of each row selected and in the loop you will get the values of the each of the other elements, provided that you declared the input tags as described.

Thanks, I think this might solve my problem. I will try this later in the day and mark this thread solved, if this works.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.