How to assign map keys and values ββ- object's modelAttribute property in JSP forms using Spring?
I have a question web application in Spring. Here's the code to get the Q&A form and return it to exam.jsp:
@RequestMapping(value = "/")
public String getExam(ModelMap map) {
List<Question> questions = new ArrayList<Question>();
// Here I am getting the all data for questions list
// and basically I am sending to the view the list of questions, where each question has list of variants
map.addAttribute("questions", questions);
return "exam";
}
My model classes:
public class Question {
private int id;
private String text;
private List<Variant> variants;
//getters and setters
}
public class Variant {
private int id;
private int questionId;
private int correctness;
private String text;
//getters and setters
}
public class AnswerSheetWrapper {
Map<Integer, Integer> answerSheet;
//getter and setter
}
In my exam.jsp: I am getting the questions attribute from the getExam method from the controllers. I am creating groups of radio objects for each question and filling in the modelattribute "answerSheetWrapper" (I may be doing this wrong, so please tell me how to do it). I want the answerSheet map to contain the question id as keys and id variant as values :
<form:form action="/exam/calculate" modelAttribute="answerSheetWrapper">
<c:forEach items="${questions}" var="question">
${question.text}<br />
<c:forEach items="${question.variants}" var="variant">
<form:radiobutton path="answerSheet['${question.id}']" value="${variant.id}"/>${variant.text} <!--Here code throws Exception when runned-->
</c:forEach>
<br />
</c:forEach>
<input type="submit" value="GΓΆndΙr"/>
</form:form>
And this is my controller method where the form action takes place:
@RequestMapping(value = "/exam/calculate")
public String calculate(@ModelAttribute("answerSheetWrapper")AnswerSheetWrapper answerSheetWrapper) {
// do processing with modelAttribute object
return "someView";
}
I'm not sure if I give the path in the form: radiobutton correctly .
When I run the application, I get:
HTTP Status 500 - An exception occurred processing JSP page /resources/pages/exam.jsp at line 29
The main reason:
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'answerSheetWrapper' available as request attribute
So where is the problem in my code? Any help is appreciated.
source to share
It seems you forgot to add answerSheetWrapper
to the model. You are currently only adding questions, so change your controller code like this:
map.addAttribute("questions", questions);
map.addAttribute("answerSheetWrapper", new AnswerSheetWrapper());
Also this
<form:radiobutton path="answerSheet['${question.id}']"
value="${variant.id}"/>${variant.text}
it is probably better to write using the attribute label
form:radiobutton
<form:radiobutton path="answerSheet['${question.id}']"
value="${variant.id}" label="${variant.text}" />
source to share