Why ((Integer) weightModel.getObject()).intValue(); throws exception
- by yakup
I am learning Wicket by "Enjoying Web Development with Wicket" book. And in an example:
int weight = ((Integer) weightModel.getObject()).intValue();
is used.
When I click Submit button it throws exception.
But after changed the code to:
int weight=Integer.parseInt( (String) weightModel.getObject());
It works fine. What is the reason for throwing the exception?
The full code:
GetRequest.java
package myapp.postage;
import java.util.HashMap;
import java.util.Map;
import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.model.Model;
@SuppressWarnings("unchecked")
public class GetRequest extends WebPage {
private Model weightModel=new Model();
private Model patronCodeModel=new Model();
private Map patronCodeToDiscount;
public GetRequest(){
patronCodeToDiscount=new HashMap();
patronCodeToDiscount.put("p1", new Integer(90));
patronCodeToDiscount.put("p2", new Integer(95));
Form form=new Form("form"){
@Override
protected void onSubmit(){
int weight = ((Integer) weightModel.getObject()).intValue();
Integer discount=(Integer)patronCodeToDiscount.get(patronCodeModel.getObject());
int postagePerKg=10;
int postage=weight*postagePerKg;
if(discount!=null){
postage=postage*discount.intValue()/100;
}
ShowPostage showPostage=new ShowPostage(postage);
setResponsePage(showPostage);
}
};
TextField weight=new TextField("weight",weightModel);
form.add(weight);
TextField patronCode=new TextField("patronCode",patronCodeModel);
form.add(patronCode);
add(form);
}
}
The html file GetRequest.html:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<form wicket:id="form">
<table>
<tr>
<td>Weight</td>
<td><input type="text" wicket:id="weight"/></td>
</tr>
<tr>
<td>Patron code:</td>
<td><input type="text" wicket:id="patronCode"/></td>
</tr>
<tr>
<td></td>
<td><input type="submit"/></td>
</tr>
</table>
</form>
</html>