有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Spring项目在jsp页面中显示mysql表数据

亲爱的专业人士,我试图在jsp页面(Netbeans,Spring项目)中显示mysql表中的数据。为此,我创建了模型类:

    public class Impression {    
    private int id;
    private String username;
    private String text;    

    public static List<Impression> listAllImpressions() throws SQLException, ClassNotFoundException {
        List<Impression> listImpression = new ArrayList<>();        
        Class.forName("com.mysql.jdbc.Driver");

        try (java.sql.Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/guestbook", "root", "");) {
            Statement st = conn.createStatement();
            st.executeQuery("SELECT impression_id, username, text FROM impression");
            ResultSet rs = st.getResultSet();
            while (rs.next()) {
                int id  = rs.getInt("impression_id");
                String username = rs.getString("username");
                String text = rs.getString("text");
                Impression impression = new Impression(id, "aaa", text);
                listImpression.add(impression);
            }
        }        
        return listImpression;
    }
}

然后创建一个控制器:

@Controller
public class ImpressionController {

    @RequestMapping(value = "/newjsp", method = RequestMethod.GET)
    public String allImpressions(@ModelAttribute("impressions") Impression impression, ModelMap model) throws ClassNotFoundException, SQLException {
        Impression impressions = new Impression();
        List<Impression> listImpressions = Impression.listAllImpressions();
        return "newjsp";
    }

当我尝试像这样在jsp页面(newjsp)中显示数据时,我没有得到任何结果:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>


<!DOCTYPE html>
<html>
    <body>
    <center>
        <h1>List of user impressions</h1>
    </center>
    <div align="center">
        <table border="1" cellpadding="3">
            <tr>
                <th>ID</th>
                <th>Username</th>
                <th>Text</th>
            </tr>
            <c:forEach var="impressions" items="${listAllImpressions}">
                <tr>
                    <td><c:out value="${impressions.id}" /></td>
                    <td><c:out value="${impressions.username}" /></td>
                    <td><c:out value="${impressions.text}" /></td> 
                </tr>
            </c:forEach>
        </table>
    </div>   
</body>
</html>

我是Java Spring MVC的新手。任何帮助都将不胜感激。:)


共 (1) 个答案

  1. # 1 楼答案

    您可能应该首先验证列表是否确实包含项