如何从控制器传递一个列表到JSP页面?

3
我正在使用Spring框架实现一个公告板。
为了在JSP上显示文章列表,我从数据库中获取了一些信息,并将其保存到List<BulletinBoardList>中。
我的目的是将这个List带到JSP并保存它。我尝试了下面的代码:
@RequestMapping(value = "/", method = RequestMethod.GET)
public String home(Locale locale, Model model) {
    logger.info("Welcome home! The client locale is {}.", locale);

    /*
    Date date = new Date();
    DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
    
    String formattedDate = dateFormat.format(date);
    
    model.addAttribute("serverTime", formattedDate );
    */
    List<BulletinBoardList> result = sqlSession.selectList("board.getList");
    
    model.addAttribute("list", result);
    

    
    
    return "home";
}

接下来,这段代码是用于从控制器中检索列表的:

<%@ page import com.heesu.third.BulletinBoardList, java.util.List %>
<% BulletinBoardList list = ${list} %>

但它从未生效。
1个回答

8

我已经在JSP中使用JSTL完成了这样的事情。请看我的代码。这里我的列表是“inf”,我的对象有不同的字段,但我认为你可以适应它:

<%@ 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>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Real time info</title>
<link href="webjars/bootstrap/3.3.6/css/bootstrap.min.css"
                    rel="stylesheet">
</head>
    <body>
    <div class="container">
        <table class="table table-striped">
            <caption><h3>Result (People):</h3></caption>
            <thead>
                <tr class="tr tr-success">
                    <td>Id</td>
                    <td>Name</td>
                    <td>PIN</td>
                </tr>   
            </thead>
            <tbody>
                <c:forEach items="${inf}" var="temp">
                    <tr>
                        <td>${temp.id}</td>
                        <td>${temp.name}</td>
                        <td>${temp.pin}</td>
                        <td>
                            <a class="btn btn-info" href="/update-person?id=${temp.id}">Update</a>
                            <a class="btn btn-danger" onclick="return confirm('Are you sure you want to delete?')" href="/delete-person?id=${temp.id}">Delete</a>
                        </td>
                    </tr>
                </c:forEach>
            </tbody>
        </table>
    </div>
    <script src="webjars/jquery/2.2.4/jquery.min.js"></script>
    <script src="webjars/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</body>
</html>

这里是控制器的具体部分:

@RequestMapping(value = "/search", method = RequestMethod.POST)
    public String handleRequest(@RequestParam String search,
            ModelMap model){
        List<UserInfo> inf = searchServ.listPeople(search);
        model.put("inf", inf);
        return "info";
    }

你的问题非常相似。我希望这可以帮到你。只是补充一点 - 我正在使用Bootstrap来设计我的图形用户界面。


1
谢谢!这非常有帮助!我投了你一票,但由于我的等级太低,它没有公开显示。 - Leo
很高兴它能帮到你! - strash

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接