Capture multiple check box selection JSP Parameters - java

I found this post that shows how to pass multiple check box selections to another JSP page, but it's not working for me. When I try to get the selected values I get:
checked boxes: [Ljava.lang.String;#3f3fbd
Here are my two pages (be gentle, this is my first attempt at JSP!)
createSHAREfile.jsp basically runs a query to find all the terms that have not been processed and show each term with a check box next to it:
<title>Create SHARE Files</title>
</head>
<body>
<jsp:include page="../menu/header.jsp" flush="false" />
<form name='SelectSHARETerms' method='post' action="SHAREProcessing.jsp">
<fieldset><legend>Select Terms to Process for SHARE</legend>
<table align='left'>
<% String termDetail = "", currDate = "";
currentDateTime datetime = new currentDateTime();
datetime.setCurrDate();
currDate = datetime.getCurrDate();
java.sql.Date todayDate = java.sql.Date.valueOf(currDate);
Terms terms = new Terms();
ArrayList<Terms.termsTable> termsObjList = new ArrayList<Terms.termsTable>();
terms.setTermsSql("Select * from Terms where TermDate <= '" + currDate + "' AND VoucherProcessDate Is Null");
boolean indicator = terms.setListOfTerms();
if (indicator == true) {
int size = terms.getListSize();
termsObjList = terms.getTermsList();
for (int i=0; i<size; ++i) {
Terms.termsTable eachTerm = (Terms.termsTable)termsObjList.get(i);
java.sql.Date termDate = eachTerm.TermDate;
%>
<tr><td><input type=checkbox name=SelectedTermDate id='SelectedTermDate<%=i%>' value="<%=i%>"><%=termDate %></td></tr>
<%
}
}
%>
<tr><td align='center'><input type='submit' value='Submit'></input></td></tr>
</table>
</fieldset>
</form>
</body>
</html>
When the submit button is pressed I call SHAREProcessing.jsp. Right now all i'm trying to do on this page is show which termdates the user has selected so I can use them as parameters to a Java Class that will create the files for the selected terms:
<title>SHARE Processing</title>
</head>
<body>
<jsp:include page="../menu/header.jsp" flush="false" />
<table width='50%' align='center' border='1'>
<% String[] SelectedValues = request.getParameterValues("SelectedTermDate");
System.out.println("checked boxes: " + SelectedValues);
%>
</body>
</html>
Here's where I'm trying to use the code shown in the other post but it's not working :(
Thanks for any help!
Leslie

You're trying to print the whole string array with System.out.println, and so you get that. It's probably working fine.
Try this:
System.out.println("checked boxes:");
for (int i = 0; i < SelectedValues.length; ++i)
System.out.println(" " + SelectedValues[i]);
Also, I beg you: in your spare time, find out about a modern web framework (there are zillions for Java) and strive to escape from the painful world of coding Java inside JSP files.

You're just facing the default value of Object#toString().
Either just loop over it and print each item, or use Arrays#toString(). Here's an SSCCE:
package com.stackoverflow.q2426380;
import java.util.Arrays;
public class Test {
public static void main(String... args) {
String[] array = {"foo", "bar" , "waa"};
System.out.println(array); // [Ljava.lang.String;#addbf1
String arrayAsString = Arrays.toString(array);
System.out.println(arrayAsString); // [foo, bar, waa]
}
}
That said, this problem has actually nothing to do with JSP. It's just a view technology. The problem is rather in the basic Java code --which you wrote at the wrong place, in a JSP file instead of a Java class. I strongly agree with the comments that writing raw Java code in JSP files is a bad practice. Start learning Servlets.

Related

How to do a recursive ( foreach loop ) using include tag ? Tree Structure-JAVA

i would like to know if it possible that a JSP (boucle.jsp) include itself when a condition is true
this code trow me java.lang.StackOverflowError exception
<%
for(Callers ck : calls.get(calls.size()-1)){
pageContext.setAttribute("ck", ck);
System.out.print("Test1 " +ck);
if (app.hasChild(ck)== true) {
c = app.childOf(ck);
calls.add(c);
%>
<li><input type="checkbox" id="c<%=i%>" />
<label class="tree_label"for="c<%=i%>">${ck}<></label>
<%i++;%>
<%#include file="/Pclink/boucle.jsp" %>
</li>
<%
}else {
%>
<li><span class="tree_label">${ck}</span></li>
<%
}
}
calls.remove(calls.size()-1);
%>
</ul>*
well , include is a static import , wich means the first thing happends is :
<%#include file="/Pclink/boucle.jsp" %>
brings the content of "Pclink/boucle.jsp " and it put it in our jsp and because boucle.jsp call it selfs so it include it again and again ...
so what we need is a dynamique inclule which is <jsp:include page="boucle.jsp" />
NB: the boucle.jsp in that case must be a full jsp page not only a part of the code that u want it to be recursive;
and if you want to reach data from boucle.jsp
all u have to do is puch data from the initial jsp with
request.setAtrribute("name_ that you_want_to_call_it ",variable);
and u catch it in boucle.jsp with
variable = request.getAttribute("name_ that you_called_it ");
however i'm not tooo good at english , i hope understand something.

Is it possible to get Javascript array in JSP page

I am developing a web application in which I which I have a JavaScript array and I want this array in my JSP page and iterate it save the data in database.
var value = response;
for (var key in value) {
if (value.hasOwnProperty(key)) {
alert(key + " -> " + value[key]);
var sample = new Array();
sample=value[key];
console.log(sample);
// document.getElementById('');
}
}
});
I want this data on my JSP page is it possible. If it is possible, then how?
You can have javascript in jsp but that will always execute on client side. So if you want to save some stuff on trigger of some event inside browser you can do that by making ajax call or form submission. Ajax is preferred way because its faster and better experience for user
But if you have intention of execution of javascript on server side thats not possible
Java script client side script whereas jsp is server side script so you can't simply do this.
What you can do is submit the calculated variable from javascript to server by form-submission, or using URL parameter or using AJAX calls and then you can make it available on server to store in database.
Client Side:
<script type="text/javascript">
var n = document.getElementById("data");
var f=new Array( "apple", "orange", "mango" );
n.value = f;
</script>
<form action="Your_JSP.jsp" method="POST">
<input type="hidden" id="data" name="data" value="" />
<input type="submit" />
</form>
Server Side:
<%
String val = request.getParameter("data");
String aa[]=val.split(",");
for(String x : aa )
out.println(x);
//now hereyou can use aa array tostore in database or do whatever you want
%>
Try this if you have two different jsp:
first.jsp
<script>
var response = [];
...
var put = function(form) {
form.resp.value = response.join(','); //using comma as separator
};
</script>
<form onsubmit='put(this)' method='next.jsp' method='post'>
<input type='hidden' name='resp' />
<button>Submit</button>
</form>
next.jsp
<%
String[] resp = request.getParameter("resp").split(",");
%>
Response is: ${param.resp} <!-- debugging -->
yes , its possible to do that. you can show array in HTML tag
<!DOCTYPE html>
<html>
<head>
<script>
var value=response;
for (var key in value) {
if (value.hasOwnProperty(key)) {
alert(key + " -> " + value[key]);
var sample = new Array();
sample=value[key];
console.log(sample);
// do here as
document.getElementById("array").innerHTML = sample;
// here array is <p> tag in html and sample is array which will be shown in jsp page.
}
}
</script>
</head>
<body>
<form action="get.jsp" method="POST">
<p id="array" name="array" type="hidden"></p>
<input type="submit" />
</body>
</html>
in get.jsp you will able to get value from array as:
<%
String []array = request.getParameter("array").split(",");
//this String array you can use to store data in DB
%>

How to take value from div in Java Script and sort to it?

I am making an application that receive data from servlet to jsp page.
I have used List<> mechanism to store and retrieve data.
So I have used one time a html design code and embed it into for loop that display data untill List<> data end.
I want to sort data retrieved data on jsp page using java script but how to get value of that retrieved data in Java Script I don't know.
My JSP Code :
<div class="listinggitems">
<%
List<Integer> prdIDList = (List<Integer>)request.getAttribute("prodID");
List<String> prdNAMEList = (List<String>)request.getAttribute("prodNAME");
List<String> prdIMAGEList = (List<String>)request.getAttribute("prodIMAGE");
List<Float> prdPRICEList = (List<Float>)request.getAttribute("prodPRICE");
List<String> prdFEATUREList = (List<String>)request.getAttribute("prodFEATURE");
for(int i = 0;i < prdIDList.size();i++)
{
Integer prdID = prdIDList.get(i);
String prdNAME = prdNAMEList.get(i);
String prdIMAGE = prdIMAGEList.get(i);
Float prdPRICE = prdPRICEList.get(i);
String prdFEATURE = prdFEATUREList.get(i);
%>
<div class="mainitemlist">
<div class="mainitemlistimage"><div align="center"> <img src="product_images/<%= prdIMAGE %>" height="125px" width="100px"></div></div>
<div class="mainitemlistname">
<div align="center"><%= prdNAME %></div>
</div>
<div class="mainitemlistprice">
<div align="center"><%= prdPRICE %></div>
</div>
<div class="mainitemlistfeatures"><div align="center"><%= prdFEATURE %></div></div>
</div>
<%
}
%>
</div>
I have taken 2 buttons:
1 for to sort data as per price,
2 for to sort data as per name.
When user click on button it calls Java Script Function to Sort data.
But how to get all data into Java Script for to sort I don't know.
Anyone will guide me, how to do that ?
I strongly believe that the most appropriate solution to this issue is the use of AJAX as suggested by Hussain Akhtar Wahid failing that my suggestion to convert the product data to a JSON object and pass that to a JavaScript function would allow you to use mainly JavaScript. However if you must use nothing more than the request object and JavaScript then I have a solution for you.
In short, you must get the product data from the request object into a JavaScript object. This is possible but it not a pretty. Then once the product data is in the JavaScript object you can sort it using a custom sort function in JavaScript.
Here is your modified JSP code: ShowProduct.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%# page import="java.util.*"%>
<!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>Product Catalogue</title>
<link rel="stylesheet" type="text/css" href="sortList/layout.css" />
<script type="text/javascript" src="sortList/sort.js"></script>
<script type="text/javascript">
//Puts the products into the product array of the catalogue object
<%
List<Integer> prdIDList = (List<Integer>) request.getAttribute("prodID");
List<String> prdNAMEList = (List<String>) request.getAttribute("prodNAME");
List<String> prdIMAGEList = (List<String>) request.getAttribute("prodIMAGE");
List<Float> prdPRICEList = (List<Float>) request.getAttribute("prodPRICE");
List<String> prdFEATUREList = (List<String>) request.getAttribute("prodFEATURE");
for (int i = 0; i < prdIDList.size(); i++) {
Integer prdID = prdIDList.get(i);
String prdNAME = prdNAMEList.get(i);
String prdIMAGE = prdIMAGEList.get(i);
Float prdPRICE = prdPRICEList.get(i);
String prdFEATURE = prdFEATUREList.get(i);
%>
catalogue.product[<%=i%>] = {pId:<%=prdID%>, pImage:"<%=prdIMAGE%>", pName:"<%=prdNAME%>", pPrice:<%=prdPRICE%>, pFeature:"<%=prdFEATURE%>"};
<%
}
%>
</script></head>
<body onload="catalogue.sortByName()">
<button onclick="catalogue.sortById()">Sort By Id</button>
<button onclick="catalogue.sortByName()">Sort By Name</button>
<button onclick="catalogue.sortByPrice()">Sort By Price</button>
<div id="container"><div id="mainitemlist"></div></div>
</body></html>
A lot of changes to go over so I will be brief. Two major changes.
Instead of displaying the product data immediately I cycle through the lists and put the data into a JavaScript array of objects. The array is call product and is a property of the catalogue literal object. See the JavaScript file below.
catalogue.product[<%=i%>] = {pId:<%=prdID%>, pImage:"<%=prdIMAGE%>", pName:"<%=prdNAME%>", pPrice:<%=prdPRICE%>, pFeature:"<%=prdFEATURE%>"};
I have created a div into which to insert the product data once it is sorted.
<div id="container"><div id="mainitemlist"></div></div>
I have also created three buttons that sort the product data
<button onclick="catalogue.sortById()">Sort By Id</button>
<button onclick="catalogue.sortByName()">Sort By Name</button>
<button onclick="catalogue.sortByPrice()">Sort By Price</button>
I have created a JavaScript file called sort.js which sorts and displays the product data.
// The catalogue literal object
var catalogue = {
sortDirection: -1, // The direction of the sort
product: [], // The product list generated by the JSP
// Sorts the products by their ID
sortById: function sortById() {
catalogue.product.sort(function(a, b) {
return catalogue.sortDirection * (a.pId - b.pId);
});
catalogue.sortDirection *= -1;
catalogue.display();
},
// Sorts the products by their NAME
sortByName: function sortByName() {
catalogue.product.sort(function(a, b) {
var result = 0;
var nameA = a.pName.toLowerCase(), nameB = b.pName.toLowerCase();
if (nameA < nameB) {
result = -1;
} else if (nameA > nameB) {
result = 1;
} else {
result = 0;
}
return catalogue.sortDirection*result;
});
catalogue.sortDirection *= -1;
catalogue.display();
},
// Sorts the products by their PRICE
sortByPrice: function sortByPrice() {
catalogue.product.sort(function(a, b) {
return catalogue.sortDirection * (a.pPrice - b.pPrice);
});
catalogue.sortDirection *= -1;
catalogue.display();
},
// Displays the sorted products
display: function display(){
var node = document.getElementById('container');
while (node.hasChildNodes()) {
node.removeChild(node.firstChild);
}
var html = "";
for(var i = 0; i < catalogue.product.length; i++){
var tableRow = new catalogue.tableRow(catalogue.product[i]);
html += tableRow.generateHTML();
}
document.getElementById('container').innerHTML = html;
},
// Contructor object for the table row
tableRow: function tableRow(product){
this.id = product.pId;
this.image = product.pImage;
this.name = product.pName;
this.price = product.pPrice;
this.feature = product.pFeature;
var image = "<div id='mainitemlist'><div id='mainitemlistimage'><a href='product?pid=prdID'><img src='product_images/prdIMAGE'></a></div>";
var name = "<div id='mainitemlistname'><a href='product?pid=prdID'>prdNAME</a></div>";
var price = "<div id='mainitemlistprice'>prdPRICE</div>";
var features = "<div id='mainitemlistfeatures'>prdFEATURE</div></div>";
this.generateHTML = function generateHTML(){
html = "";
html += image.replace("prdIMAGE", this.image).replace("prdID", this.id);
html += name.replace("prdNAME", this.name).replace("prdID", this.id);
html += price.replace("prdPRICE", this.price);
html += features.replace("prdFEATURE", this.feature);
return html;
};
}
};
This script creates a catalogue literal object that contains all the properties and methods necessary to sort and display the product data.
There are three sort functions: sortById, sortByName and sortByPrice. Each implements a custom sort. I wont explain how custom sort works in as there are many article on the internet that explain it very well.
In order for the sort to be bidirectional (sorts alternate low to high on clicking the sort button) I use the sortDirection variable that alternates its value between 1 and -1. This controls the direction of the sort.
The display method produces the output to the screen by passing each product object in the product array to the constructor of the tableRow constructor object. Then by calling the generateHTML() method on this object the HTML for each row is generated.
This an example of the template that is used to generate the HTML:
var name = "<div id='mainitemlistname'>
<a href='product?pid=prdID'>prdNAME</a></div>";
This method replaces the place holders prdID and prdName with the real values, obtained from the product and returns a string of HTML to the display method. Then this HTML in inserted into the ShowProduct DOM by setting the innerHTML property.
This JavaScript can be improved substantially nevertheless you have some code that gives you a rough solution to your issue. But I must reiterate that this is not the best way to tackle this issue, especially as you are using scriptlets which I am sure you know are taboo.
EDIT: Its missing the CSS, see below. Save it in a file called layout.css and import is in the HEAD elements of the HTML like so: <link rel="stylesheet" type="text/css" href="sortList/layout.css" />
div#mainitemlist{
float: left;
width: 100%;
}
div#mainitemlistimage {
float: left;
width: 200px;
}
div#mainitemlistimage img{
height: 125px;
width: 100px;
}
div#mainitemlistname{
float: left;
width: 200px;
}
div#mainitemlistname a{
color: #9caeb9;
text-decoration: none;
}
div#mainitemlistprice{
float: left;
width: 200px;
}
div#mainitemlistfeatures{
float: left;
width: 200px;
}

jsp- loop input tag for multiple value

I am new to JSP and don't have much idea. So just let me clarify my requirement.
Say I have a program as below, where there's a First.jsp with an array Match_List[5].
String[] Match_List;
Match_List[] = {a, b, c, d, e};
<form name="Team_Playerdetails" method="post" action="db_Match_Edit.jsp">
<TABLE>
<% for (int j = 0; j < 10; j++) { %>
<TR>
<TD>
<SELECT name="Stat_Match_name">
<% for (int i = 0; i < 5; i++) { %>
<option>
<% out.println(Match_List[i][1]); %>
</option>
<% } %>
</SELECT>
</TD>
</TR>
<% } %>
</TABLE>
<input type="submit" name="submit" value="Add All" tabindex="10" class="button" />
</form>
Now this form above will display a same drop down lists 10 times. I want to select different options in these ten lists say like below:
List_1 Option: a
List_2 Option: d
List_3 Option: e
List_4 Option: b
List_5 Option: c
.....
List_10 Option: d
Now I need that once user clicks the submit button then the variable should be moved to db_Match_Edit.jsp. Here I will have the code to catch the value as
U_Stat_Match_name = request.getParameter("Stat_Match_name");
But since all the 10 drop down options are getting caught by the same select variable name Stat_Match_name. So on db_Match_Edit.jsp I am only getting the last selected option in U_Stat_Match_name.
But I need all the 10 selected options in the db_Match_Edit.jsp jsp in an array.
Either just use HttpServletRequest#getParameterValues():
String[] statMatchNames = request.getParameterValues("Stat_Match_name");
// ...
Or just give them each an unique value based on the iteration index:
<select name="Stat_Match_name_<%=j%>">
and grab them individually as follows:
for (int j = 0; j < 10; j++) {
String statMatchName = request.getParameter("Stat_Match_name_" + j);
// ...
}
Unrelated to the concrete problem, this oldschool JSP code style suggests that you're learning JSP by a heavily outdated resource of possibly more than 10 years old. I recommend to concentrate on more recent and sane learning resources. Start at How to avoid Java code in JSP files? and then read our JSP wiki page.

Retrieve data from database and display it dynamically in the rows of the table using textboxes

I'm currently working on an Inventory Management project. I m working with JSP and MySQL on Netbeans Platform. In my project on querying I need to retrieve values from the database and display it in a table. The rows to be displayed should be dynamic in my page. They should be displayed in any number. Suppose When I want to retrieve values based on a particular choice I select, I should be able to display all the data based on the choice and display it in the rows of the table. I am not able to display it in multiple rows of my table because I m using text boxes to display the values.
Here is the code snippet:
<table>
<tr>
<td>
<select name="choice_type">
<option>select</option>
<option value="part_type">part_type</option>
<option value="category">category</option>
<option value="names">names</option>
</select>
</td>
</tr>
<tr>
<th>VAL</th>
<th>VAL DESC</th>
</tr>
<tr>
<td> <input type="text" name="val" id="val" size="15" /></td>
<td> <input type="text" name="val_desc" id="val_desc" size="15" /></td>
</tr>
</table>
<input type="submit" name="Query" value="Query" onClick="getData();"/>
The getData() function is as follows:
function getData(){
xmlHttp=GetXmlHttpObject()
var id=document.getElementById("choice_type").value;
var url="choice_retrieval.jsp";//The code for this file is defined below
url=url+"?choice_type="+id;
xmlHttp.onreadystatechange=stateChanged
xmlHttp.open("GET",url,true)
xmlHttp.send(null);
}
function stateChanged(){
if(xmlHttp.readyState==4 || xmlHttp.readyState=="complete"){
var showdata = xmlHttp.responseText;
var strar = showdata.split(":");
if(strar.length>1){
var strname = strar[1];
document.getElementById("val").value= strar[1];
document.getElementById("val_desc").value= strar[2];
}
}
The Code snippet for choice_retrieval.jsp is as follows:
<%
String ch = request.getParameter("choice_type").toString();
System.out.println(ch);
String data ="";
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://", "", "");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select * from master_panel where choice_type='"+ch+"'");
while(rs.next())
{
data = ":" + rs.getString("val") + ": " + rs.getString("val_desc");
}
out.println(data);
System.out.println(data);
}
catch(Exception e) {
System.out.println(e);
}
%>
Database table used here is master_panel(choice_type varchar,val varchar,val_desc varchar). I have not put any constraints as of now. Based on the choice_type value I need to retrieve the corresponding data(val and val_desc) from the database and display it in dynamic rows.
Assuming that the data is being returned (your stateChanged method is being invoked) you need to dynamically create the table rows (and their contents, the text boxes) in your stateChanged method by modifying the DOM.
To modify the DOM to create the table structure the code should read something like this (assuming you've already removed the previously displayed rows):
var table = document.getElementById('tableId');
var data = xmlHttp.responseText.split(":");
for (int i = 0; i < data.length; i + 2)
{
var valueText = document.createElement('input');
valueText.type = 'text';
valueText.name = 'value' + i;
valueText.value = data[i];
var valueCell = document.createElement('td');
valueCell.appendChild(valueText);
var descriptionText = document.createElement('input');
descriptionText.type = 'text';
descriptionText.name = 'value' + i;
descriptionText.value = data[i + 1];
var descriptionCell = document.createElement('td');
descriptionCell.appendChild(descriptionText);
var tableRow = document.createElement('tr');
tableRow.appendChild(valueCell);
tableRow.appendChild(descriptionCell);
table.tBodies[0].appendChild(tableRow);
}
Also, as #TrueDub said, putting SQL in JSPs is bad for a whole host of reasons. What's worse is building SQL queries with string concatenation - it opens your system to SQL injection attacks, especially when the string being concatenated includes a string captured in the browser.
You're doing quite a few things wrong there, especially having database code within a JSP, but to answer your specific question, you should write your resultset into a list and set this list into the request scope with a specific id. You can then iterate over it using the JSTL tag and display the output using the {} notation.

Categories

Resources