Servlet向JSP发送错误信息

时间:2018-12-12 17:46:43

标签: java jsp servlets dao

我正在尝试创建一个Java Web项目,该项目列出艺术家,艺术家列出的专辑和专辑列出的歌曲。问题是我将按歌手列出的专辑正确列出到浏览器页面中,但是当我尝试按专辑列出歌曲时,它们却相互混合。例如,在浏览器上,当我单击“ Metallica”时,我从Aerosmith heh那里获得了歌曲。 以下是我有关歌曲的DAO,JSP和servlet文件。

TrackDAO:

public List<Track> findTracksByAlbum(Album album) throws SQLException, ClassNotFoundException {
    Connection connection = null;
    PreparedStatement statement = null;
    ResultSet result = null;
    List<Track> tracksByAlbum = new ArrayList<>();
    Track track = null;

        try {
            connection = new ChinookDatabase().connect();
            String sql = ("SELECT * FROM Track WHERE AlbumId = ?");
            statement = connection.prepareStatement(sql);
            statement.setLong(1, album.getId());
            result = statement.executeQuery();

            while(result.next()) {
                long id = result.getLong("TrackId");
                String name = result.getString("Name");
                tracksByAlbum.add(new Track(id, name));
            }
        }

        catch (SQLException e) {
            throw new RuntimeException(e);
        }
        finally {
            ChinookDatabase.closeQuietly(connection, statement, result);
        }
        return tracksByAlbum;
    }

JSP:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Kappaleet</title>
</head>
<body>
<h1>Tässä kaikki kappaleet</h1>
<c:forEach items="${ tracks }" var="track">
<li>
<c:out value="${ track.getName() }" />
</li>
</c:forEach>
</body>
</html>

Servlet:

@WebServlet("/Track")
public class TrackServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

private AlbumDAO albumDao = new AlbumDAO();
private TrackDAO trackDao = new TrackDAO();

protected void doGet(HttpServletRequest request, HttpServletResponse 
response)

    throws ServletException, IOException {

        String stringId = request.getParameter("id");
        long id = Long.parseLong(stringId);
        List<Track> track = null;

        try {
            Album album = albumDao.findAlbum(id);
            track = trackDao.findTracksByAlbum(album);
        } catch (ClassNotFoundException | NumberFormatException | 
SQLException e) {
            e.printStackTrace();
        }

    request.setAttribute("tracks", track);
    String jsp = "/kappaleet.jsp";
    RequestDispatcher dispather = 
request.getServletContext().getRequestDispatcher(jsp);
    dispather.include(request, response);
}
}

0 个答案:

没有答案