How to change list(select) data dynamically - java

I am adding product details.
So for that with it I have to add product attribute, product feature with it.
I am loading all data of attribute from mysql table.
I am using one mechanism that first user have to select attribute category from list (select control), when user select category then as per it data of other list (select control) changes.
main category image :
sub attribute category :
I have added data like this in JavaScript array :
var at_category_id = [];
var at_category_name = [];
<%
List<Integer> aIDList = (List<Integer>) request.getAttribute("aID");
List<String> aNAMEList = (List<String>) request.getAttribute("aNAME");
for (int i = 0; i < aIDList.size(); i++)
{
%>
at_category_id.push(<%= aIDList.get(i) %>);
at_category_name.push(<%= aNAMEList.get(i) %>);
<%
}
%>
var option_str = document.getElementById('list_main_category');
for (var i=0; i<at_category_id.length; i++)
{
option_str.options[option_str.length] = new Option(at_category_id[i],at_category_name[i]);
}
I have done same like this for attribute and add data to JavaScript array.
var at_id = [];
var at_name = [];
<%
List<Integer> acIDList = (List<Integer>) request.getAttribute("acID");
List<String> acNAMEList = (List<String>) request.getAttribute("acNAME");
for (int i = 0; i < aIDList.size(); i++)
{
%>
at_id.push(<%= acIDList.get(i) %>);
at_name.push(<%= acNAMEList.get(i) %>);
<%
}
%>
but now how to move forward I don't know.
I want to do something like that.
Means when user click on first list that is main category how second list will be changed ?
any suggestion please.

The usual way would be to put a javascript action on the value changing for the first combo box.
At that point you can either (easy way) submit the whole form and then send back the new page with the extra value added or (slightly more complex) do an AJAX call to fetch the data and populate the new dropdown.

Related

JSP how to Loop through an Array with Filters for unique objects?

Hi all I'm hitting a bit of a snag on this project I'm working on.
I'm trying to make a list of unique list of objects(properties) and give them a list of features you can select from a database table.
this is the code for populating that database
<% String selected_features = rz.fetch("real_estate", "selected_features");
%>
<input name="selected_features" type="hidden" value="<%=selected_features%>"/>
<rz:list module="estate_features" sort="seq_no asc" output="none" options="noscript" filter="">
<%
while(rz.listnext() && rz.listindex >= 0) {
%><rz:listbody>
<div class="rz-checkbox">
<%
String featureName = rz.fetch("estate_features", "feature_text");
String recordid = rz.fetch("estate_features", "_recordid");
String selected = "selected_features_box";
%>
<rzt:checkbox
label="<%=featureName%>"
field="<%=selected%>"
checkedValue="<%=rz.fetch("estate_features", "_recordid")%>"
target=""
checked="<%=("|"+selected_features+"|").indexOf("|"+recordid+"|") >= 0 ? "true" : "false"%>"
/>
<%=("|"+selected_features+"|").indexOf("|"+recordid+"|") >= 0 ? "true" : "false"%>
</div><!-- /.rz-checkbox -->
</rz:listbody>
<% } %>
</rz:list>
and this is the loop I've got going on the page
<rz:list module="real_estate" sort="seq_no asc" output="none" options="noscript" filter="<%="pageid=property-"+rz.pageid%>"><%
while(rz.listnext() && rz.listindex >= 0) {%><rz:listbody>
<%
String features = rz.fetch("real_estate", "selected_features");
String[] feature_arr = StringUtils.split(features, "|");
for (int i=0; i < feature_arr.length; i++ ) {
if(!feature_arr[i].equals("")){
String feature_name = rz.fetch("estate_features", "feature_text", "", "_recordid="+feature_arr[i]);
%>
<li>
<span><%=feature_name%></span>
</li>
<% } } %>
</rz:listbody>
<% } %>
</rz:list>
as of right now the feature works when I make a single unique object. But when I make a second object it generates the entire list
The numbers are the features variable and are the recordid from a test I'm doing the first set 42|43|44|45|46|47|48|49 are for the first object while 50|51|52|53|54|55 are for the second object
It's because your not setting a breakpoint for when it needs to end
for(int i=0; i < feature_arr.length; i++){
if(!feature_arr[i].equals("")){
String feature_name = rz.fetch("estate_features", "feature_text", "", "_recordid="+feature_arr[i]);
this is what you need--->if(feature_arr[i] === feature_name){

Why isn't my List<Object> displaying on my webpage?

I'm trying to display the contents of a List<> of objects that are linked to the currently logged in user on a jsp page. The object is successfully created and stored in the database with a user_id of the user who created it, and with a simple system.out.print debugger I can see its added to the List.
But when I try to display this on the NewFile.jsp webpage its as if the the List is empty. There is no error, instead the page is just blank as if there is no List to iterate through.
Skill method in UserController
#RequestMapping(value = "/skill", method = RequestMethod.POST)
public String skill(#ModelAttribute("skillForm") Skill skillForm, BindingResult bindingResult, Model model, Principal principal) {
skillValidator.validate(skillForm, bindingResult);
if (bindingResult.hasErrors()) {
return "skill";
}
// Adds skill object to database and adding it to Users skill list
String name = principal.getName();
skillService.save(skillForm, name);
User currentUser = userService.findByUsername(principal.getName());
currentUser.addSkill(skillForm);
// Debug here shows that the list contains correct data and the list size
System.out.println(skillForm.getSkillName());
System.out.println(skillForm.getCategory());
System.out.println(currentUser.getSkills().size());
// Attempting to pass the list to NewFile.jsp to be displayed
List<Skill> savedSkills = currentUser.getSkills();
for(int i = 0; i < savedSkills.size(); i++) {
model.addAttribute("skills", savedSkills);
/*model.addAttribute("currentUser", currentUser);*/
}
return "NewFile";
}
NewFile.jsp
<table>
<c:forEach var="o" items="${savedSkills}" >
<tr>
<td>Skill Name:<c:out value = "${o.skillName}"/></td>
<td>Category:<c:out value = "${o.category}"/> </td>
</tr>
</c:forEach>
</table>
There are some mistakes. First you don't need a loop.
List<Skill> savedSkills = currentUser.getSkills();
model.addAttribute("skills", savedSkills);
Second, your EL has the wrong argument name, just like the others had stated.
<c:forEach var="o" items="${skills}" >
You need to specify what skill to be added , you are adding the List as an attribute but you need to the object that's inside it
for(int i = 0; i < savedSkills.size(); i++) {
model.addAttribute("skills", savedSkills[i]);
/*model.addAttribute("currentUser", currentUser);*/
}
Try by adding the code model.addAttribute("savedSkills", savedSkills); before the return statement. You haven't add the model attribute named with "savedSkills".

Add To Cart Doesn't Work

Hi I am trying to implement Add To Cart Mechanism in my web Application.
So that's why temporary i have created 3 JSP pages that implement such mechanism. But it is not working properly.
I have also created session uniquely for to identify specific user session but it is not actually implemented in all page.
Following Is My Code :
test.jsp
<%
Random rkey = new Random();
int randomkey = Math.abs(rkey.nextInt());
String sdata = "keyur"+randomkey;
DateFormat dateFormat = new SimpleDateFormat("HHmmss");
Calendar cal = Calendar.getInstance();
String sess = "keyur"+randomkey+dateFormat.format(cal.getTime());
session.setAttribute("KEYUR", sess);
%>
<% response.sendRedirect("test1.jsp"); %>
test1.jsp
Hello <%= session.getAttribute("KEYUR")%>
<%
String a="shirt",b="jeans";
int a1 = 10,b1=20;
Double a2=100.00,b2=200.00;
%>
<br><br>
A : Add To Cart<br><br>
A1 : Add To Cart
test2.jsp
Hello <%= session.getAttribute("KEYUR")%><br><br><br><br>
Your Cart :
<%
List<String> pname = new ArrayList<String>();
List<Integer> pqty = new ArrayList<Integer>();
List<Double> ppr = new ArrayList<Double>();
%>
<%
pname.add(request.getParameter("item"));
pqty.add(Integer.parseInt(request.getParameter("qty")));
ppr.add(Double.parseDouble(request.getParameter("price")));
Double total=0.00;
%>
<br><br>
<%
for(int i = 0;i < pname.size();i++)
{
String name = pname.get(i);
Integer qty1 = pqty.get(i);
Double pr1 = ppr.get(i);
%>
Name : <%= name %><br>
Qty : <%= qty1 %><br>
Price : <%= pr1 %><br><br>
Total : <%= total += qty1*pr1 %>
<%
}
%>
Right now i have taken static data, if it will work then I'll try it with dynamic data.
Anyone tell me why only one item display in cart.
Suppose user click on Add To Cart then it redirect to test2.jsp and again back to test1.jsp then click on second add to cart then cart should be appended not overwrite.
But currently it is overwriting.
Any Suggestion Please...
test2.jsp
List<String> pname = new ArrayList<String>(); //size is 0
...
pname.add(request.getParameter("item")); //size is 1
That's why you get just one item.
By the way, make your self a favour, don't use JSP scriptlets; use JSTL or write your own tags (look for Java Custom tags)
This procudure looking very Bad codding for store a cart items...
But still you can store as many you want in List
In your page when every time a Test2.jsp called the new keywprd initilize a new cart lists..
thats why previous value get losts....
instead of this code
<%
List<String> pname = new ArrayList<String>()
List<Integer> pqty = new ArrayList<Integer>();
List<Double> ppr = new ArrayList<Double>();
%>
use deceleration block for decleration
<%!
List<String> pname = new ArrayList<String>();
List<Integer> pqty = new ArrayList<Integer>();
List<Double> ppr = new ArrayList<Double>();
%>
after that you can store as many you want ....But there will be possible some duplicate values...to remove duplicate you can use Set at the place of List
I think you have got your query's answer.....
The reason why only one item is displayed is because you are inserting only one item in Lists pname, pqty, ppr.
Use a for loop in-order to insert. So that it contains multiple orders or items..
Hope it will help.

Get Value of dynamically create dropdownlist in JSP

I am new to JSP and servlet for 1 month, and there are many things that I am still unsure off.. Inside a JSP, I have a dropdownlist(the values inside are grab from database) and it would be dynamically created on the number that the user keyed in. Example, the user key in 3, this digit would store in session, and 3 dropdownlist would be generated.
I am able to do this, however I am unable to grab the value of all the 3 dropdownlist in a servlet. and instead of getting 3 diff values, the output repeat the value of the first dropdownlist. Example "john,john,john" instead of "john, ken, andy".
JSP code:
<form action="Adding" method="post">
<%
session = request.getSession();
ProjectGroup projGrp1 = (ProjectGroup)session.getAttribute("PROJECTNAME");
//getMaxMember is the int that user keyed in
int staff =projGrp1.getMaxMember();
for(int i = 0; i < staff; i++) {
%>
<select name="list1" >
<%#page import="sit.bean.*,sit.data.*"%>
<%
GroupTaskManager mgr3 = new GroupTaskManager();
GroupTask[] at3 = mgr3.getCheckBox();
for(int g = 0; g < at3.length; g++) {
%>
<option><%=at3[g].getStaffName()%></option>
<%
}
%>
</select>
<%
}
%>
<input type="submit" name="submit">
</form>
In servlet:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
ProjectGroup projGrp = (ProjectGroup)session.getAttribute("PROJECTNAME");
int member = projGrp.getMaxMember();
String total = null;
for(int i=0; i< member; i++)
{
String names = request.getParameter("list1");
total += names + " , ";
}
PrintWriter pw = response.getWriter();
pw.write("<HTML><BODY>");
pw.write(total);
pw.write("</HTML></BODY>");
pw.close();
}
Can i set the downdownlist name like "list<%i%>", to set different id to each downdownlist? therefore i can retrieve each of them seperately???
In servlet you are getting same parameter every time which is list1 in loop.
and also in JSP creating dropdownlist with same name attribute,
that's why you are getting john,john,john instead of john, ken, andy.
Yes you can use list<%i%> to set different id as well as name
change your select with below in JSP
<select name="list<%=i%>" >
and for loop in servlet with below
for(int i=0; i< member; i++)
{
String names = request.getParameter("list1"+i);
total += names + " , ";
}

How to load session data for Google Chart API using JavaScript

I am trying to load a session data that is to be used to create a pie chart using Google Chart API.However I do not seem to be able to make it work.Can someone give me some guidance on how to do it?Below is the source code:
In AnalyzeUserClient.jsp:
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('visualization', '1', {packages: ['corechart']});
</script>
<script type="text/javascript">
var sessionId = '<%= (HashMap<String, String>)request.getSession().getAttribute("hashMap") %>';
function drawVisualization() {
// Create and populate the data table.
var data = google.visualization.arrayToDataTable([
[sessionId],
]);
// Create and draw the visualization.
new google.visualization.PieChart(document.getElementById('visualization')).
draw(data, {title:"Percentage of Category for User:"});
}
google.setOnLoadCallback(drawVisualization);
</script>
//HTML Code
<div id="visualization" style="width: 600px; height: 400px;"></div>
My data in the session looks like this:
{Environment=1, Education=1, Hospitality_Recreation=2, Disaster_Accident=1, Human Interest=3, Labor=1}
I've just complete something similar when adding a line chart to my Android application. I've modified my scenario to fit with yours;
var data = new google.visualization.DataTable();
// Slice-Value columns.
data.addColumn('string', 'Area');
data.addColumn('number', 'Value');
// Get the injected dataset.
var dataset = '<%= (HashMap<String, String>)request.getSession().getAttribute("hashMap") %>'; //
var mapSize = dataset.length;
for (var i = 0; i < mapSize; i++) { // Iterate over key-value pairs
var keyValuePair = dataset[i]; // Get the i'th value.
var keyValueArray = new String(keyValuePair).split("="); // Split on '='
data.addRow([keyValueArray[0], parseInt(keyValueArray[1])]); // Add record.
}
For completeness...
I've tested my approach in the Google Code Playground and it works. I added the code;
function drawVisualization() {
// Create and populate the data table.
var data = new google.visualization.DataTable();
// Slice-value columns.
data.addColumn('string', 'Area');
data.addColumn('number', 'Value');
var dataset = new Array("Environment=1", "Education=1", "Hospitality_Recreation=2", "Disaster_Accident=1", "Human Interest=3", "Labor=1");
console.log(dataset);
var mapSize = dataset.length;
console.log(mapSize.toString());
for (var i = 0; i < mapSize; i++) { // Iterate over key-value pairs
var keyValuePair = dataset[i]; // Get the i'th value.
var keyValueArray = new String(keyValuePair).split("="); // Split on '='
data.addRow([keyValueArray[0], parseInt(keyValueArray[1])]); // Add record.
}
// Create and draw the visualization.
new google.visualization.PieChart(document.getElementById('visualization')).
draw(data, {title:"Area-Value plot for SO"});
}

Categories

Resources