Why isn&#39;t my List<object> displaying on my webpage?

时间:2018-03-22 23:50:01

标签: java spring jsp spring-mvc

I'm trying to display the contents of a List<> of objects that are linked to the currently logged in user on a jsp page. The object is successfully created and stored in the database with a user_id of the user who created it, and with a simple system.out.print debugger I can see its added to the List.

But when I try to display this on the NewFile.jsp webpage its as if the the List is empty. There is no error, instead the page is just blank as if there is no List to iterate through.

Skill method in UserController

  @RequestMapping(value = "/skill", method = RequestMethod.POST)
public String skill(@ModelAttribute("skillForm") Skill skillForm, BindingResult bindingResult, Model model, Principal principal) {
    skillValidator.validate(skillForm, bindingResult);

    if (bindingResult.hasErrors()) {
        return "skill";
    }

    // Adds skill object to database and adding it to Users skill list
    String name = principal.getName();
    skillService.save(skillForm, name);
    User currentUser = userService.findByUsername(principal.getName());
    currentUser.addSkill(skillForm);
    // Debug here shows that the list contains correct data and the list size
    System.out.println(skillForm.getSkillName());
    System.out.println(skillForm.getCategory());
    System.out.println(currentUser.getSkills().size());

    // Attempting to pass the list to NewFile.jsp to be displayed
    List<Skill> savedSkills = currentUser.getSkills();
    for(int i = 0; i < savedSkills.size(); i++) {
         model.addAttribute("skills", savedSkills);
         /*model.addAttribute("currentUser", currentUser);*/
    }

    return "NewFile";
}

NewFile.jsp

<table>
    <c:forEach var="o" items="${savedSkills}" > 
    <tr>
          <td>Skill Name:<c:out value = "${o.skillName}"/></td>
          <td>Category:<c:out value = "${o.category}"/>  </td>          
    </tr>
    </c:forEach>            
</table>

3 个答案:

答案 0 :(得分:0)

You need to specify what skill to be added , you are adding the List as an attribute but you need to the object that's inside it

for(int i = 0; i < savedSkills.size(); i++) {
         model.addAttribute("skills", savedSkills[i]);
         /*model.addAttribute("currentUser", currentUser);*/
    }

答案 1 :(得分:0)

尝试在return语句之前添加代码model.addAttribute("savedSkills", savedSkills);。您尚未添加以“savedSkills”命名的模型属性。

答案 2 :(得分:0)

有一些错误。首先,你不需要循环。

List<Skill> savedSkills = currentUser.getSkills();
model.addAttribute("skills", savedSkills);

其次,你的EL有错误的参数名称,就像其他人所说的那样。

<c:forEach var="o" items="${skills}" >