我正在使用Maven和Spring开发Java Severlet。
我需要创建具有动态行数的表。这些行应使用变量“ amountRows”创建。到目前为止,我最好的猜测是使用嵌入式Java代码创建静态数量的行,然后使用CSS / JavaScript动态隐藏它们。
任何想法我如何摆脱for循环中的“ 15”并将其替换为变量“ amountRows”?
或者对更平滑的解决方案有什么想法?
<form action="/myServlet/.../Page.html" method="post">
<table>
<caption><center><b>Table Title</b></center></caption>
<tr><td><input type="number" min="00000" max="30" name="amountRows"/></td></tr>
<tr>
<td>column-title</td><td>column-title</td><td>column-title</td><td>column-title</td>
</tr>
<%
int i = 1;
for(; i <= 15; i++) {
out.print("<tr><td>Cell1</td><td>Cell2</td><td>Cell3</td><td>Cell4</td");
}
%>
</table>
<input type="submit"/>
</form>
您可以使用Thymeleaf进行此操作。这是我的一个项目的示例:
<!doctype html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
<head>
<title>Home</title>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<!-- Bootstrap CSS -->
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"
integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO"
crossorigin="anonymous">
<link rel="stylesheet" href="/css/main.css"/>
</head>
<body>
<div class="row">
<div class="container col-9">
<table class="table table-striped">
<thead>
<th class="standard">Song Title and Artist</th>
<th class="year" style="font-weight:900">Year</th>
</thead>
<tbody>
<tr th:each="song : ${songs}">
<td>
<a href="#"
th:href="@{/playsong(id=${song.songId})}"
th:text="${song.title + ' - ' + song.artist}">
Song title and artist
</a>
</td>
<td class="year" th:text="${song.year}">
Song year
</td>
</tr>
</tbody>
</table>
</div>
</div>
<footer>
© Copyright 2020 Lindsay Nickalo. All rights reserved.
</footer>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"
integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49"
crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"
integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy"
crossorigin="anonymous"></script>
</body>
</html>
在映射中,您只需使用model.addAttribute("amountRows", amountRows);
将变量添加到模型中,然后就可以在Thymeleaf的html中使用它了。对于我的示例,我传入了Song对象的整个列表,然后使用th:each="song : ${songs}"
为每首歌曲制作了一个表格行。在Thymeleaf中,您可以使用${variable}
在您的POM中,包括
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>