есть метод который вернет ответы с помощью id.
@RequestMapping(value = "/getAnswerByQuestionId",method = RequestMethod.GET)
public String getAnswerByQuestionId(ModelMap map,@RequestParam("id")int id){
List<Answer> findAllBYQuestionId=answerRepository.findAllByQuestionId(id);
map.addAttribute("findAllAnswersByQuestionId",findAllBYQuestionId);
map.addAttribute("addAnswer",new Answer());
return "answerResult";
}
этот метод идет в JSP сюда
<spring:form action="/addAnswer" method="post" enctype="multipart/form-data" modelAttribute="addAnswer">
<c:forEach items="${findAllAnswersByQuestionId}" var="name">
${name.text}
<input type="hidden" value="${name.id}" name="questionId">
</c:forEach>
<spring:textarea path="text"></spring:textarea>
<input type="file" name="pict">
<input type="submit" value="add">
</spring:form>
на втором строке печатает результат. В этом JSP под результатом есть форма для добавлении ответа. Когда все ок - добавили ответ, данные идут сюда
@RequestMapping(value = "/addAnswer",method = RequestMethod.POST)
public String addAnswer(@ModelAttribute("answer")Answer answer,@AuthenticationPrincipal UserDetails userDetails,@RequestParam("questionId")int id,@RequestParam("pict")MultipartFile[] files) throws IOException {
File dir = new File(imageUploadPath);
if (!dir.exists()) {
dir.mkdir();
}
for (MultipartFile file : files) {
String picName = System.currentTimeMillis() + "_" + file.getOriginalFilename();
File picture = new File("D:\\bankSystem\\" + picName);
file.transferTo(picture);
answer.setImage(picName);
answer.setUserUsername(userDetails.getUsername());
answer.setQuestionId(id);
}
answerRepository.save(answer);
return "redirect:/getAnswerByQuestionId";
}
Здесь добавляется и идет обратно на этот метод getAnswerByQuestionId, чтобы пользователь добавил еще один ответ либо увидел его ответ. Проблема в том, что когда идет обратно на этот метод getAnswerByQuestionId возникает ошибка
request param id is not present
вот скажет, что не давали id, чтобы он смог печатать результат. Можно ли сделать так, чтобы не давать id и войти на этот JSP?
Параметр можно передать с помощью RedirectAttributes. Когда вы делаете перенаправление запроса, то необходимо чтобы требуемые параметры находились в url.
@RequestMapping(value = "/addAnswer",method = RequestMethod.POST)
public String addAnswer(@ModelAttribute("answer")Answer answer,
@AuthenticationPrincipal UserDetails userDetails,
@RequestParam("questionId")int id,
@RequestParam("pict")MultipartFile[] files,
RedirectAttributes redirectAttributes) throws IOException {
....
redirectAttributes.addAttribute("id", id);
return "redirect:/getAnswerByQuestionId";
}
Для более детального ознакомления см. документацию.
Апостиль в Лос-Анджелесе без лишних нервов и бумажной волокиты
Основные этапы разработки сайта для стоматологической клиники
Продвижение своими сайтами как стратегия роста и независимости