首页 > 解决方案 > 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 的新手。任何帮助将不胜感激。:)

标签: javamysqlspring

解决方案


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


推荐阅读