我有一个 Spring MVC 项目,它使用 .csv 文件来存储我的数据(目前数据存储在我计算机的本地 C:\中)。
我的目标是显示 csv 文件中的每一行数据,直到 jsp 页面上的最后一行。为了做到这一点,我意识到我需要 Controller 文件中的循环来从 csv 文件读取数据,以及 jsp 页面中的循环来获取数据并将其显示在网页上。
我尝试过使用
<c:forEach>
在jsp页面中,将csv数据附加到整个字符串中,并用分隔符“|”分隔行在每行的末尾,然后通过模型获取整个附加的长字符串并传递到 jsp 中并执行
<c:forEach>
在jsp页面上,使用split将它们按所提到的分隔符分开,并逐行显示数据行。这种方法的问题在于,每次刷新网页时,相同的数据 block 都会被复制并显示,而且复制的时间越来越长。
我应该怎么做?以下是我的代码:
Controller :
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Locale;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.request.WebRequest;
import au.com.bytecode.opencsv.CSVReader;
import au.com.bytecode.opencsv.CSVWriter;
@Controller
public class HomeController {
String [] CurnextLine;
String [] FutnextLine;
String curdate;
String curtype;
String cursys;
String curdes;
String futdate;
String futtype;
String futsys;
String futdes;
String currentString;
private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
@RequestMapping(value="/c_Outage", method=RequestMethod.POST)
public String writecurrent(@RequestParam String date, String type, String system, String description, Locale locale, HttpSession session, @ModelAttribute("currentOutage") CurrentData cd,
Model model) throws Exception{
String csvFilename1 = "C:/temp/csv/curdata.csv";
CSVWriter writer1 = new CSVWriter(new FileWriter(csvFilename1, true));
String [] record1 = {date,type,system,description};
writer1.writeNext(record1);
writer1.close();
return "currentO";
}
@RequestMapping(value="/f_Outage", method=RequestMethod.POST)
public String writefuture(@RequestParam String datefuture, String typefuture, String systemfuture, String descriptionfuture, Locale locale, HttpSession session, @ModelAttribute("futureOutage") CurrentData cd,
Model model) throws Exception{
//CurrentData cd2 = new CurrentData();
String csvFilename2 = "C:/temp/csv/futdata.csv";
CSVWriter writer2 = new CSVWriter(new FileWriter(csvFilename2, true));
String [] record2 = {datefuture,typefuture,systemfuture,descriptionfuture};
writer2.writeNext(record2);
writer2.close();
return "futureO";
}
@RequestMapping(value = "/", method = RequestMethod.GET)
public String home(Locale locale, Model model, HttpServletRequest req) throws Exception {
logger.info("Welcome home! The client locale is {}.", locale);
String csvFilename1 = "C:/temp/csv/curdata.csv";
CSVReader reader1 = new CSVReader(new FileReader(csvFilename1));
while ((CurnextLine = reader1.readNext()) != null) {
currentString += CurnextLine[0] + "\t" + CurnextLine[1] + "\t" + CurnextLine[2] + "\t" + CurnextLine[3] + "\t" + "|"; //appending each data each time the while loop loops
curdate = CurnextLine[0];
curtype = CurnextLine[1];
cursys = CurnextLine[2];
curdes = CurnextLine[3];
}
model.addAttribute("currentString", currentString); //This is the long appended string which is to be split in the jsp page by the delimiter '|'
model.addAttribute("curdate", curdate);
model.addAttribute("curtype", curtype);
model.addAttribute("cursys", cursys);
model.addAttribute("curdes", curdes);
String csvFilename2 = "C:/temp/csv/futdata.csv";
CSVReader reader2 = new CSVReader(new FileReader(csvFilename2));
while ((FutnextLine = reader2.readNext()) != null) {
futdate = FutnextLine[0];
futtype = FutnextLine[1];
futsys = FutnextLine[2];
futdes = FutnextLine[3];
}
model.addAttribute("futdate", futdate);
model.addAttribute("futtype", futtype);
model.addAttribute("futsys", futsys);
model.addAttribute("futdes", futdes);
return "home";
}
@RequestMapping(value = "/c_Outage", method = RequestMethod.GET)
public String c_outage(HttpSession session, WebRequest request, Model model) {
return "currentO";
}
@RequestMapping(value = "/f_Outage", method = RequestMethod.GET)
public String f_outage(HttpSession session, WebRequest request, Model model) {
return "futureO";
}
}
jsp页面-home.jsp
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<%@ page session="false" %>
<html>
<head>
<title>Home</title>
</head>
<body>
<h1>
Admin Error Page Control
</h1>
<form name="hw" method="POST">
<table>
<tr><td><h2>Main Menu</h2></td><td></td></tr>
<tr><td> </td><td></td></tr>
<tr><td><a href="./c_Outage">Input Current Outage</a></td><td></td></tr>
<tr><td><a href="./f_Outage">Input Future Outage</a></td><td></td></tr>
</table>
</form>
<h2>Current Outages</h2>
<table>
<h3><td> Date </td> <td> Type </td> <td> System </td> <td> Description </td></h3>
<tr><td> ${ curdate } </td><td> ${ curtype } </td><td> ${ cursys } </td><td> ${ curdes } </td></tr>
</table>
<table>
<c:set var="input_ra" value="${currentString}" />
<c:forEach var="ra_split" items="${fn:split(input_ra, '|')}" >
<tr><td><c:out value="${ra_split}" /></tr></td>
</c:forEach>
</table>
<h2>Future Outages</h2>
<table>
<h3><td> Date </td> <td> Type </td> <td> System </td> <td> Description </td></h3>
<tr><td> ${ futdate } </td><td> ${ futtype } </td><td> ${ futsys } </td><td> ${ futdes } </td></tr>
</table>
<h2>Past Outages</h2>
<table>
<h3><td> Date </td> <td> Type </td> <td> System </td> <td> Description </td></h3>
<tr><td> ${ pasdate } </td><td> ${ pastype } </td><td> ${ passys } </td><td> ${ pasdes } </td></tr>
</table>
</body>
</html>
当前O.jsp
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@ page session="false" %>
<html>
<head>
<title>Home</title>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<!-- Calender Style Sheet Begin -->
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
<script>
$(function() {
for (i = 0; i < 100000; i++) {
$( "#datepicker"+i ).datepicker({ dateFormat: "mm/dd/yy", firstDay: 1, changeYear: true });
}
});
</script>
</head>
<body>
<%-- <form:form method="post" action="" commandName="currentOutage"> --%>
<form:form method="post" modelAttribute="currentOutage">
<tr><td><h2>Input Current Outage</h2></td><td></td></tr>
<tr><td> </td><td></td></tr>
<tr><td>Date: </td><td><input type="text" name="date" id="datepicker1" style="width: 80px;"></td></tr>
<tr><td>Type: </td><td>
<select name="type">
<option value="">Select...</option>
<option value="Planned">Planned</option>
<option value="Unplanned">Unplanned</option>
<option value="Emergency">Emergency</option>
</select>
</td></tr>
<tr><td>System: </td><td><input type="text" name="system" ></td></tr>
<tr><td>Description: </td><td><input type="text" name="description" style="width: 250px;" ></td></tr>
<p class="submit"><input type="submit" name="commit" value="Add Current Issue"></p>
</form:form>
<h2>Current Outages</h2>
<tr><td>${curdate}</td></tr><tr><td>${curtype}</td></tr><tr><td>${cursys}</td></tr><tr><td>${curdes}</td></tr>
<%--
<c:out value="${date}" />
<c:out value="${system}"/> --%>
</body>
</html>
futureO.jsp 页面:
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@ page session="false" %>
<html>
<head>
<title>Home</title>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<!-- Calender Style Sheet Begin -->
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
<script>
$(function() {
for (i = 0; i < 100000; i++) {
$( "#datepicker"+i ).datepicker({ dateFormat: "mm/dd/yy", firstDay: 1, changeYear: true });
}
});
</script>
</head>
<body>
<form:form method="post" action="" commandName="futureOutage">
<tr><td><h2>Input Future Outage</h2></td><td></td></tr>
<tr><td> </td><td></td></tr>
<tr><td>Date: </td><td><input type="text" name="datefuture" id="datepicker2" style="width: 80px;"></td></tr>
<tr><td>Type: </td><td>
<select name="typefuture">
<option value="">Select...</option>
<option value="Planned">Planned</option>
<option value="Unplanned">Unplanned</option>
<option value="Emergency">Emergency</option>
</select>
</td></tr>
<tr><td>System: </td><td><input type="text" name="systemfuture" ></td></tr>
<tr><td>Description: </td><td><input type="text" name="descriptionfuture" style="width: 250px;" ></td></tr>
<p class="submit"><input type="submit" name="commit" value="Add Future Issue"></p>
</form:form>
</body>
</html>
Maven pom.xml 文件 CSV 依赖项:
<dependency>
<groupId>net.sf.opencsv</groupId>
<artifactId>opencsv</artifactId>
<version>2.3</version>
</dependency>
供您引用,我正在使用 Spring Tool Suite。如果您想帮助我,您可以在 Spring Tool Suite 中创建一个 Spring MVC 项目,并在 pom.xml 文件中添加上述 Maven 依赖项。我已经在上面提供了所有代码。
非常感谢您的帮助。如果您能帮助我解决问题,我将接受最佳答案并投票给正确的答案。
最佳答案
pythonhiew,看起来你的 currentString 是全局的,每次你在文件中读取当前的 currentString 条目时,它都会累积。
我建议您将 currentString 移动到映射中并在那里初始化它。
像这样:
@RequestMapping(value = "/", method = RequestMethod.GET)
public String home(Locale locale, Model model, HttpServletRequest req) throws Exception {
logger.info("Welcome home! The client locale is {}.", locale);
String currentString = null; //here
String csvFilename1 = "C:/temp/csv/curdata.csv";
CSVReader reader1 = new CSVReader(new FileReader(csvFilename1));
while ((CurnextLine = reader1.readNext()) != null) {
currentString += CurnextLine[0] + "\t" + CurnextLine[1] + "\t" + CurnextLine[2] + "\t" + CurnextLine[3] + "\t" + "|"; //appending each data each time the while loop loops
curdate = CurnextLine[0];
curtype = CurnextLine[1];
cursys = CurnextLine[2];
curdes = CurnextLine[3];
}
model.addAttribute("currentString", currentString); //This is the long appended string which is to be split in the jsp page by the delimiter '|'
model.addAttribute("curdate", curdate);
model.addAttribute("curtype", curtype);
model.addAttribute("cursys", cursys);
model.addAttribute("curdes", curdes);
String csvFilename2 = "C:/temp/csv/futdata.csv";
CSVReader reader2 = new CSVReader(new FileReader(csvFilename2));
while ((FutnextLine = reader2.readNext()) != null) {
futdate = FutnextLine[0];
futtype = FutnextLine[1];
futsys = FutnextLine[2];
futdes = FutnextLine[3];
}
model.addAttribute("futdate", futdate);
model.addAttribute("futtype", futtype);
model.addAttribute("futsys", futsys);
model.addAttribute("futdes", futdes);
return "home";
}
关于java - Spring MVC - 如何在jsp页面上显示CSV文件中的每一行数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28976391/