0

I have used the LinkHashMap to retrieve data from database and populate it to my listbox in JSF. The listbox gets populated. Basically, if the user selects two items from the listbox and click calculate command button, the application should display him the total price. Basically in my table, I have two columns, Item and Price. The Item (String) gets displayed in the listbox. But my issue is how to I retrieve the price (double) which is the value so that I can calculate the price for the number of selections that the user makes in the JSF page. Please help me to resolve this issue. Thanks & Regards.

See my codes below:

Java Codes

import java.util.LinkedHashMap;
import java.util.Map;
import java.sql.*;
public class Menu2 {
String url = "jdbc:mysql://localhost:3306/esd";
String user = "root";
String pw = "root";

String favlst;
double total;
Map<String,Object> lst; {
    try{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(url, user, pw);


String sql = "SELECT * FROM list";
Statement stt = con.createStatement();
ResultSet rs = stt.executeQuery(sql);

lst = new LinkedHashMap<String, Object>();
while(rs.next()){
    double price = rs.getDouble("Price");
    String item = rs.getString("Item");
    lst.put(item, price);
}


}catch(Exception e){

    }
}

public double getTotal() {
    return total;
}

public void setTotal(double total) {
    this.total = total;
}

public Map<String, Object> getSelectlst() {
    return lst;
}

public String Calculate(){
    total = 0;
double price = 0;
price += (Double)lst.get(item);


return "success";
  }
}

JSF Page

<f:view>
<h:form>
    <h3> Generated by Map </h3>

    <h:selectOneListbox value = "#{menu2.selectlst}">
        <f:selectItems value = "#{menu2.selectlst}"/>
    </h:selectOneListbox>   

    <br> <br>

    <h:commandButton value = "Calculate" action = "#{menu.Calculate}"/>
    <br> <br>
Total: Rs <h:outputLabel value = "#{menu.total}"></h:outputLabel>

</h:form>

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
James Smith
  • 55
  • 2
  • 11

1 Answers1

1

I'm not really sure about your objective, but obviously the selectOneListbox value is incorrect. You bind the selectItems to a LinkedHashMap, which seems to be fine. But the value of your selection is bound to the same!

What I'm suggesting:

  • Model your elements as an Object e.g. StoreItem (with attributes id,name,price)
  • Use a List<StoreItem> allItems for all available items
  • Use a List<StoreItem> selectedItems for the selectedItems
  • Use <f:selectItems value="#{menuBean.allItems}" var="i" itemLabel="#{i.name}" itemValue="#{i}"/>
  • Register a converter for the StoreItem to convert between String representation (using the id) and Object representation.
  • Iterate in you calculate method over the selectedItems.
Thor
  • 6,607
  • 13
  • 62
  • 96