【问题标题】:Spring MVC does not display DB data in jspSpring MVC在jsp中不显示DB数据
【发布时间】:2016-06-29 16:52:54
【问题描述】:

我正在处理一个存储各种学习材料链接的大学项目。我的数据库中有一个文本教程的链接列表,项目文件如下:

TextTutorialController.java:

package io.spring.learn.web;

import java.util.List;

import javax.inject.Inject;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import io.spring.learn.proc.TextTutorial;
import io.spring.learn.proc.TextTutorialService;

@Controller
@RequestMapping("/textTutorials")
public class TextTutorialController {

    @Inject
    TextTutorialService service;

    @RequestMapping(value = "/listOfTextTutorials", method = RequestMethod.GET)
    public String showList(ModelMap model) {
        List<TextTutorial> listOfTextTutorials = service.findAll();
        model.addAttribute("textTutorialList", listOfTextTutorials);
        return "listOfTextTutorials";
    }

}

listOfTextTutorials.jsp:

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

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>List of Text Tutorials</title>
</head>
<body>
    <h1>List of Text Tutorials on Spring:</h1>
    <table>
        <tr>
            <th>ID</th>
            <th>Name</th>
            <th>URL</th>
            <th>Alexa Global Rank</th>
            <th>Total Chapters</th>
            <th>% Completed</th>
        </tr>
        <c:forEach var="textTutorial" items="${textTutorialList}">
            <tr>
                <td><c:out value="${textTutorial.id}" /></td>
                <td><c:out value="${textTutorial.name}" /></td>
                <td><c:out value="${textTutorial.url}" /></td>
                <td><c:out value="${textTutorial.alexaGlobalRank}" /></td>
                <td><c:out value="${textTutorial.totalChapters}" /></td>
                <td><c:out value="${textTutorial.percentCompleted}" /></td>
            </tr>
        </c:forEach>
    </table>
</body>
</html>

index.jsp:

<!DOCTYPE html>

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>

<html>
    <head>
        <meta charset="utf-8">
        <title>Welcome</title>
    </head> 
    <body>
        <a href="textTutorials/listOfTextTutorials.html">List of Text Tutorials on Spring</a>
    </body>
</html>

在Tomcat上运行应用程序后,控制台显示DB连接正常,甚至查询了一些SELECT语句:

[EL Info]: 2016-06-29 03:29:17.721--ServerSession(2113257970)--EclipseLink, version: Eclipse Persistence Services - 2.5.0.v20130507-3faac2b
[EL Info]: connection: 2016-06-29 03:29:18.265--ServerSession(2113257970)--file:/Users/AgentDen/Documents/Java/MyProjectSpringMVC/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/LearnSpringMVC/WEB-INF/classes/_LearnSpring login successful
[EL Fine]: sql: 2016-06-29 03:29:18.314--ServerSession(2113257970)--Connection(302754878)--SELECT ID FROM books WHERE ID <> ID
[EL Fine]: sql: 2016-06-29 03:29:18.842--ServerSession(2113257970)--Connection(500719466)--SELECT ID FROM CLASSROOM WHERE ID <> ID
[EL Fine]: sql: 2016-06-29 03:29:18.886--ServerSession(2113257970)--Connection(1612903660)--SELECT ID FROM general_articles WHERE ID <> ID
[EL Fine]: sql: 2016-06-29 03:29:18.905--ServerSession(2113257970)--Connection(250314644)--SELECT ID FROM online_courses WHERE ID <> ID
[EL Fine]: sql: 2016-06-29 03:29:18.922--ServerSession(2113257970)--Connection(474813894)--SELECT ID FROM text_tutorials WHERE ID <> ID
[EL Fine]: sql: 2016-06-29 03:29:18.936--ServerSession(2113257970)--Connection(1688125903)--SELECT ID FROM youtube_tutorials WHERE ID <> ID
[EL Fine]: sql: 2016-06-29 03:29:19.619--ServerSession(2113257970)--Connection(585968463)--SELECT ID, alexa_global_rank, chapters_studied, date_finished, date_started, days_spent, LANGUAGE, LEVEL, NAME, percent_completed, personal_rating, total_chapters, URL FROM text_tutorials

但我的jsp中显示的一切都只是html标题和表头,但模型中没有显示任何数据:

List of Text Tutorials on Spring:

ID  Name    URL Alexa Global Rank   Total Chapters  % Completed

JSTL 包含在 pom.xml 中:

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>jstl</artifactId>
    <version>1.2</version>
</dependency>

我在这里阅读了类似的问题,但似乎没有一个问题专门针对我的情况。我已经对此感到非常绝望,所以任何建议都将受到高度赞赏!

UPD。 下面是服务的 findAll() 方法的实现:

    package io.spring.learn.proc;

    import java.util.List;

    import javax.persistence.EntityManager;
    import javax.persistence.NoResultException;
    import javax.persistence.PersistenceContext;
    import javax.persistence.TypedQuery;

    import org.springframework.stereotype.Repository;

    @Repository
    public class TextTutorialDaoImpl implements TextTutorialDao {

        @PersistenceContext
        private EntityManager em;

        @Override
        public List<TextTutorial> findAll() {
            TypedQuery<TextTutorial> query = em.createQuery("Select txt from TextTutorial txt", TextTutorial.class);
            return query.getResultList();
        }

    ...

}

以及服务实现:

package io.spring.learn.proc;

import java.util.List;

import javax.inject.Named;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

@Named
public class TextTutorialServiceImpl implements TextTutorialService {

    @Inject
    private TextTutorialDao txtDao;

    @Override
    public List<TextTutorial> findAll() {
        return txtDao.findAll();
    }

...

}

【问题讨论】:

  • 你能确认查询返回值吗?即结果集中至少有一项 - 另外,您知道如何使用调试器(每个 IDE 中都有一个)吗? - 在这种情况下它会派上用场
  • 是的,目前列表中有3个值在'手动'模式下成功返回(通过sql剪贴簿或主控制台输出)
  • 乍一看,从这里看起来一切都很好 - 如果您在 JSP 上打印出 textTutorialList 的长度,您会得到什么?即${fn:length(textTutorialList)}
  • 请同时发布服务和存储库代码

标签: java spring jsp spring-mvc


【解决方案1】:

您的代码看起来不错。我唯一可以怀疑的是您的服务——我相信它会返回一个空列表。您能否在将列表添加到模型图之前打印出列表的大小?

public String showList(ModelMap model) {
    List<TextTutorial> listOfTextTutorials = service.findAll();
    System.out.println(listOfTextTutorials.size()); // <-- This line.
    model.addAttribute("textTutorialList", listOfTextTutorials);
    return "listOfTextTutorials";
}

【讨论】:

  • 好吧,这确实让我更加困惑:以这种方式打印出来时列表的大小实际上是 0,但是当我在控制台模式下使用 main 方法时:ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml"); TextTutorialService tts = ctx.getBean(TextTutorialService.class); List&lt;TextTutorial&gt; ttList = tts.findAll(); for ( TextTutorial tt : ttList ) { System.out.println(tt); } 我确实得到了所有 3 个条目在打印到控制台的列表中!
  • 那么您的查询有问题。你能发布查询列表的服务方法吗?
  • 这里是服务方法的实现:@PersistenceContext private EntityManager em; @Override public List&lt;TextTutorial&gt; findAll() { TypedQuery&lt;TextTutorial&gt; query = em.createQuery("Select txt from TextTutorial txt", TextTutorial.class); return query.getResultList(); }(抱歉格式化 - 无法真正弄清楚如何在 cmets 中格式化代码)
  • 那么可能是Inject注解的原因。您是否尝试以与上述评论中发布的相同方式调用 findAll(),或者使用 spring 专有 Autowired 而不是 Inject?
  • 将注释更改为 Autowired 并没有带来任何变化。以同样的方式调用 findAll() 是什么意思?
【解决方案2】:

把你的控制器方法改成这个怎么样?

@RequestMapping(value = "/listOfTextTutorials", method = RequestMethod.GET)
public ModelAndView showList(ModelMap model) {
    List<TextTutorial> listOfTextTutorials = service.findAll();
    return new ModelAndView("listOfTextTutorials", "textTutorialList", listOfTextTutorials);;
}

对于旧的 JSP 1.2 描述符,您必须手动启用 EL。在您的 JSP 中添加以下代码。

<%@ page isELIgnored="false" %>

【讨论】:

    【解决方案3】:

    好的,感谢@Nguyen Tuan Anh 建议检查从服务返回的 List 的大小,我开始挖掘并意识到 Spring 与 DB 的连接以某种方式损坏。将application-config.xml 中的 db url 从 relative 更改为 absolute 已经解决了问题,尽管我仍然不知道为什么相对路径返回零结果。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-08-21
      • 2012-08-30
      • 2017-11-20
      • 2013-12-20
      • 1970-01-01
      • 1970-01-01
      • 2018-02-07
      • 2017-10-25
      相关资源
      最近更新 更多