Struts 2:显示歌曲表 - null被打印

时间:2013-11-29 05:57:01

标签: java list jsp struts2 iterator

我正在尝试使用以下字段填充html歌曲表。

歌曲名称专辑名称

为了做到这一点,我已经从struts 2 action类向JSP发送了 Song Song 对象。以下是歌曲和专辑类的结构。

  Song
  ----
      Title:String
      album: Album

  Album
  -----
      title : String
      releasedYear:int

问题在于,当我尝试遍历 allSongs 列表时,我可以打印歌曲名称,但它不会打印专辑名称。以下是我使用struts标签编写的JSP代码。

<table width="500px">
    <s:iterator value="allSongs">
     <tr>
        <td><s:property value="Title" /></td> // this is getting printed
        <td><s:property value="album.title" /></td>   // this doesnt get printed
     </tr>
    </s:iterator>
</table>

我尝试在JSP中使用以下代码来查找问题。但它显示为null作为输出。

System.out.println(pageContext.findAttribute("album")

你能帮助我吗?如果提供的信息不充分,请告诉我,我会更新问题。提前谢谢。

注意:我在将列表传递给JSP之前检查了列表,在那里正确填充了值。

行动类

public class HomeAction {

    private List<Song> allSongs;

    public List<Song> getAllSongs() {
            return allSongs;
    }

    public void setAllSongs(List<Song> allSongs) {
            this.allSongs = allSongs;
    }

    private MusicManager musicManager;

    public MusicManager getMusicManager() {
            return musicManager;
    }

    public void setMusicManager(MusicManager musicManager) {
            this.musicManager = musicManager;
    }

    // all struts logic here
    public String displayAllSongs() {
            allSongs = musicManager.listAllSongs();
            return "SUCCESS";

    }
}

歌曲课程

@Entity
@Table(name = "Song", catalog = "myFavMusic")
public class Song implements Serializable {

    @Id
    @GeneratedValue(strategy = IDENTITY)
    private Integer id;

    @ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    private Album album;

    @ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    private Singer singer;

    private Integer rating;

    //getter setters
}

专辑类

@Entity
public class Album implements Serializable {

    public Album() {
            super();
    }

    @OneToMany(fetch = FetchType.EAGER, mappedBy = "album")
    private List<Song> songs = null;

    @Id
    @GeneratedValue
    @Column(name = "ALBUM_ID", unique = true, nullable = false, length = 20)
    private Integer id;

    @Column(name = "TITLE", unique = true, nullable = false)
    private String title;

    // album or song , this could be replaced with enum later
    @Column(name = "TYPE", nullable = false)
    private String type;

    @Column(name = "RELEASED_YEAR", nullable = false)
    private Integer releasedYear;
//getter setters
}

1 个答案:

答案 0 :(得分:0)

我解决了这个问题。 Song类没有相册属性的getter方法。正如JB Nizet所说,我检查了所有类的getter和setter,并解决了这个问题。谢谢你们。

为了识别问题,我使用了jsp中的scriptlet块并编写了java代码来找出问题所在。当我尝试编写song.getAlbum()行时,我发现在歌曲类中没有定义getAlbum方法。

    List<com.myprojects.myfavmusic.domain.Song> allSongs =(List<com.myprojects.myfavmusic.domain.Song>)pageContext.findAttribute("allSongs");
    for (com.myprojects.myfavmusic.domain.Song song : allSongs) {  
            System.out.println(song.getAlbum().getTitle());
}