Tuesday, September 16, 2008

How to create html:select drop down using LabelValueBean


1. If you have a list of Users

List userList;

User user1 = new User(1, "Jim ", "Carter");
User user2 = new User(2, "Tom ", "Harris");
User user3 = new User(3, "Nick ", "Harper");
User user4 = new User(4, "Nathan ", "Twist");
User user5 = new User(5, "Ricky ", "Matthews");

userList=new ArrayList();
userList.add(user1);
userList.add(user2);
userList.add(user3);
userList.add(user4);
userList.add(user5);

Where User entity is :

User entity consist of two properties
firstName and lastName with unique id.

/// User.java.........................

public class User {

private int id;

private String firstName;

private String lastName;

public User(int id, String firstName, String lastName) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
}

public String getFirstName() {
return firstName;
}

public void setFirstName(String firstName) {
this.firstName = firstName;
}

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public String getLastName() {
return lastName;
}

public void setLastName(String lastName) {
this.lastName = lastName;
}
}

2.Now, If you need to have html:select with labels consisting of firstName and lastName and user's unique id as the value of each html:option.

like

Jim - Carter
Tom - Harris
Nick - Harper
Nathan - Twist
Ricky - Matthews

In Action you need to write


String[] labels = { "firstName", "lastName" };


Here
firstName and lastName are the names of the properties you want to combine.


Then you need to call custom method
populateLabelValueBean created precisely for combining the two properties. Pass your userList, properties array and property name that have to be used as a value in html:option.


userList=
populateLabelValueBean(list, labels, "id");


Set this list in request before displaying the JSP.

request.setAttribute("list",
userList );


Implementation of the method
populateLabelValueBean

public List populateLabelValueBean(List values,String[] labelProperties, String valueProperty) {

List labelValues = new ArrayList();

for (Object object : values) {

StringBuffer labelBuffer = new StringBuffer();
for (String string : labelProperties) {
labelBuffer.append(BeanUtils.getProperty(object, string));
labelBuffer.append(" - ");
}

String value = BeanUtils.getProperty(object, valueProperty);
String label = labelBuffer.toString();
label = label.replaceFirst("\\s-\\s$", "");

LabelValueBean labelValueBean = new LabelValueBean(label, value);

labelValues.add(labelValueBean);

}

return labelValues;
}


3. Your JSP page will consist of

""



No comments: