我正在从Mysql数据库中检索行并将每行存储为列表中的对象。 我将列表传递给请求范围,我试图使用JSTL循环遍历列表并访问对象变量。
以下是我将行检索为对象的方法:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
// get list of objects
List<Game> gameRatingsThisWeek = getHighestRatedGameThisWeek();
request.setAttribute("gameRatingsThisWeek", gameRatingsThisWeek);
RequestDispatcher rd = getServletContext().getRequestDispatcher("/dashboard.jsp");
rd.forward(request, response);
private List<Game> getHighestRatedGameThisWeek() {
List<Game> list = new ArrayList<Game>();
try(Connection con = ds.getConnection()){
String query = "SELECT overallRating, count(*) as Total, g.name"
+"FROM gameSurvey gs, game g"
+"WHERE g.id = gs.gameID AND"
+"date BETWEEN (NOW() - INTERVAL 7 DAY) AND NOW()"
+"GROUP by overallRating"
+"ORDER by Total desc";
PreparedStatement ps = con.prepareStatement(query);
ResultSet rs = ps.executeQuery();
while(rs.next()){
Game game = new Game();
game.setName(rs.getString("name"));
game.setRating(rs.getInt("overallRating"));
game.setTotal(rs.getInt("Total"));
list.add(game);
}
ps.close();
}catch(SQLException e){}
return list;
}
}
我知道SQL查询没问题,因为我之前测试过它。
这是Game类:
public class Game {
private int rating, total;
private String name;
// get
public int getRating(){
return rating;
}
public int getTotal(){
return total;
}
public String getName(){
return name;
}
// set
public void setRating(int rating){
this.rating = rating;
}
public void setTotal(int total){
this.total = total;
}
public void setName(String name){
this.name = name;
}
}
在dashboard.jsp文件中,我尝试遍历列表:
<c:forEach items="${gameRatingsThisWeek}" var="game">
<c:out value="${game.name}"></c:out>
</c:forEach>
我导航到检索并转发到.jsp页面的servlet。但没有任何内容输出到网页。
答案 0 :(得分:1)
您当前的查询在每个字符串文字中都缺少空格。这意味着您的数据库看到以下语句:
SELECT overallRating, count(*) as Total, g.nameFROM gameSurvey gs, game gWHERE g.id = gs.gameID ANDdate BETWEEN (NOW() - INTERVAL 7 DAY) AND NOW()GROUP by overallRatingORDER by Total desc
只需添加空格并再试一次。
String query = "SELECT overallRating, count(*) as Total, g.name "
+"FROM gameSurvey gs, game g "
+"WHERE g.id = gs.gameID AND "
+"date BETWEEN (NOW() - INTERVAL 7 DAY) AND NOW() "
+"GROUP by overallRating "
+"ORDER by Total desc";