I have a questionnary web app in Spring. Here is the code of getting form with questions and answer options and returning 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 questions attribute from controllers getExam method. I am creating radiobutton groups for each question and filling in modelattribute 'answerSheetWrapper' (Maybe I am doing it incorrect, so please tell me how to do it). I want the map 'answerSheet' to hold question id's as keys and variant id's 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 form action takes place:
@RequestMapping(value = "/exam/calculate")
public String calculate(@ModelAttribute("answerSheetWrapper")AnswerSheetWrapper answerSheetWrapper) {
// do processing with modelAttribute object
return "someView";
}
I am not sure if I specify the path in form:radiobutton correctly.
When I am running the app I receive:
HTTP Status 500 - An exception occurred processing JSP page /resources/pages/exam.jsp at line 29
The root cause is:
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.
It seems like you forgot to add the answerSheetWrapper to the model. Currently you are adding just the questions, so modify 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}
would probably be better written using the label attribute of form:radiobutton
<form:radiobutton path="answerSheet['${question.id}']"
value="${variant.id}" label="${variant.text}" />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With