Spring MVC - 如何在jsp页面上显示CSV文件中的每一行数据?

时间:2015-03-11 00:11:48

标签: java jsp maven spring-mvc csv

我有一个Spring MVC项目,它使用.csv文件存储我的数据(现在数据存储在本地计算机的C:\中)。

我的目标是显示csv文件中的每一行数据,直到我的jsp页面上的最后一行。为了做到这一点,我意识到我需要一个Controller文件中的循环来读取csv文件中的数据,并在jsp页面中有一个循环来获取并在网页上显示它们。

我尝试过使用

<c:forEach> 

在jsp页面中,将csv数据附加到由行分隔的整个字符串中,并带有分隔符“|”在每一行的末尾然后通过模型获取整个附加的长字符串并传入jsp并执行

<c:forEach> 

在jsp页面上,使用'split'按照提到的分隔符拆分它们并逐个显示数据行。这种方法的问题在于,每次刷新网页时,都会复制和显示相同的数据块,并且只会越来越长时间复制。

我该怎么做?以下是我的代码:

控制器:

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>&nbsp;</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>

currentO.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>&nbsp;</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>&nbsp;</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依赖项。我已经提供了上面的所有代码。

非常感谢你的帮助。如果你能帮助我解决问题,我会接受最好的答案并提出正确的答案。

1 个答案:

答案 0 :(得分:2)

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";
    }