Is it possible to bind the value from <option> to an object field as an integer in JSP?
I have a form like this in my jsp page:
<form:select class="form-control" path="mark" >
<c:forEach begin="1" end="10" var="i" >
<option value="${i}">${i}</option>
</c:forEach>
</form:select>
And I want to bind the selected value to a field in an object:
@Entity
public class Feedback {
private Integer mark;
// getters, setters...
}
Now I have a TypeMismatch exception: Unable to convert "String" to "Integer".
How can I store the value of an integer object from <select>?
You have a TypeMismatch Exception because you are trying to bind String
(the request parameter is String) to Integer
.
You just need to parse its value to get an int, use Integer.parseInt()
:
Feedback feedback = new Feedback();
if(request.getParameter("radios") != null) {
feedback.setMark(Integer.parseInt(request.getParameter("radios")));
}
And add name="radios"
to yours select
:
<form:select class="form-control" name="radios" path="mark" >
<c:forEach begin="1" end="10" var="i" >
<option value="${i}">${i}</option>
</c:forEach>
</form:select>
All request parameters are in the form of a String, so I would ask you to change the variable from Integer to String and then pass it to Integer before the logic you want to process.
This binding works great for me. For a cleaner way, you can use an intermediate bean to bind, and then you can convert the String to a primitive before storing.