В контроллере проекта Spring MVC у меня есть список, который я помещаю на карту модели, как показано ниже.
@GetMapping("/teacher/{userId}/add_thiesis")
public String dashboard(ModelMap model, @PathVariable Long userId) {
List<Course> courses = courseRepo.findAll();
model.put("courses", courses);
String uId = String.valueOf(userId);
ArrayList<String> questions = new ArrayList<>();
model.put("id", uId);
model.put("thiesis", new Thiesis());
model.put("questions",questions);
return "add_thiesis";
}
Теперь я хочу заполнить его динамически, используя метод post, в виде тимьяна. Для этого я использую скрипт JavaScript. Это не весь код html, но для простоты я добавляю только часть JS.
window.addEventListener("load", start);
var i='0';
var question = '<div class="form-group row">'+
'<label for="name" class="col-12 col-sm-4 col-form-label">Question:</label>'+
'<div class=" col-12 col-sm-8">'+
'<input type="text"'+ ' class="form-control" placeholder="Enter question here..." th:field="{questions['+i+']"} required/><br/>'+
'</div>'+
'</div>';
function start(){
var plus = document.getElementById("plus");
var minus = document.getElementById("minus");
plus.addEventListener("click", add);
minus.addEventListener("click", remove);
}
function add(){
var addQuestion = document.getElementById("question_body");
addQuestion.innerHTML += question;
i++;
console.log(i);
}
function remove(){
var removeQuestion = document.getElementById("question_body");
if(i>0){
console.log(removeQuestion.lastChild.nodeName);
removeQuestion.removeChild(removeQuestion.lastChild);
i--;
console.log(i);
}
}
А вот метод post, который проверен на работоспособность.
@PostMapping("/teacher/{userId}/add_thiesis")
public String addThiesis(Thiesis thiesis, ArrayList<String> questions)
{
for (String question : questions) {
Question q = new Question();
q.setQuestion(question);
questionService.save(q);
}
System.out.println("addThiesis called");
String tmpCourse = thiesis.getTmpCourse();
thiesisService.save(thiesis, tmpCourse);
System.out.println(thiesis.getId());
return "" ;
}
Это показывает мне ошибку: Ошибка разрешения шаблона [], шаблон может не существовать или может быть недоступен для любого из сконфигурированных Resolvers Template, что, безусловно, из-за: th:field="{questions['+i+']"
. Есть ли способ заполнить массив динамически, потому что количество добавляемых вопросов является переменной. Есть ли способ с этим справиться?