简体   繁体   中英

Why isn't my List<Object> displaying on my webpage?

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>

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);*/
    }

Try by adding the code model.addAttribute("savedSkills", savedSkills); before the return statement. You haven't add the model attribute named with "savedSkills".

There are some mistakes. First you don't need a loop.

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

Second, your EL has the wrong argument name, just like the others had stated.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM