I am doing my practice project and meet a problem. How can I encapsulate data i entered in jsp into a set which is inside a object using ModelDriven. Here's the sample code.
I have debugged my program and it showed null value. I knew the problem is inside the jsp but i don't how to solve it.
Order:
public class Order {
private int id;
private Date createDate;
private Date requestDate;
private double totalCost;
private String status;
private Vehicle vehicle; //contains car info
private Set<Part> parts = new HashSet<>();
//setters and getters
}
Part:
public class Part {
private int id;
private int quality;
private double laborCost;
private int status;
//setters and getters
}
My action code:
public class OrderAction extends ActionSupport implements ModelDriven<Order>{
private Order order = new Order();
public Order getOrder() {return order;}
public void setOrder(Order order) {this.order = order;}
@Override
public Order getModel() { return order;}
public String addOrder(){
try{
orderSerive.addOrder(order);
}catch (Exception e){
return LOGIN;
}
return "home";
}
My jsp page sample:
<div class="form-group" id="part1">
<s:label value="1" cssClass="col-md-1 col-sm-1 col-xs-4 col-md-offset 1"/>
<div class="col-md-6 col-sm-6 col-xs-12">
<s:textfield cssClass="form-control" id="partModel"/>
</div>
<div class="col-md-2 col-sm-2 col-xs-4 col-md-offset-1">
<s:textfield name="parts[1].quality" cssClass="form-control"/>
</div>
</div>
Your code is right for a List, that you can index with [n]
because List are indexed:
<s:textfield name="parts[1].quality" cssClass="form-control"/>
it can't work for a Set, instead, because Sets don't have indexes.
You can index a Set by one of its properties (in this case id
) like follows:
Specify the property in the file OrderAction-conversion.properties
(in the same folder of the action) with the format KeyProperty_parts=id
.
Note: some tweak could be needed due to the fact that parts
is not a Set of the action, but of an object of the action.
Use the (n)
idiom:
<s:textfield name="parts(1).quality" cssClass="form-control"/>
Override hashCode()
and equals()
.
Read all the twisted story on the official documentation.