简体   繁体   English

通过JSP页面上载CSV文件并使用Servlet打印其内容。

[英]Upload a CSV file through a JSP page and print its contents using a Servlet..?

I need to design a JSP page through which user uploads a CSV file and then I need to print its contents on the screen through a Servlet. 我需要设计一个JSP页面,通过该页面用户可以上传CSV文件,然后需要通过Servlet在屏幕上打印其内容。

The HTML code goes likes this HTML代码像这样

<form action="decode" enctype="multipart/form-data" method="post>
    <input type="file" name="record" />
    <input type="submit" />
</form>

Now In decode.java, 现在在decode.java中,

DiskFileItemFactory fi = new DiskFileItemFactory();
ServletContext sc = this.getServletConfig().getServletContext();
File file = (File) sc.getAttribute("javax.servlet.context.tempdir");
fi.setRepository(file);
ServletFileUpload upload = new ServletFileUpload(fi);
List<FileItem> items = upload.parseRequest(request);

What should I do next to read each and every word from the uploaded CSV file...? 接下来,我应该怎么做才能读取上传的CSV文件中的每个单词...? I do not want to store the CSV file anywhere. 我不想将CSV文件存储在任何地方。 Just want to read its contents and print them. 只想阅读其内容并打印它们。

You can read CSV files using Apache's CSV parser library for JAVA. 您可以使用Apache的JAVA CSV解析器库读取CSV文件。

And then after importing the library in your classpath you can simply use it as 然后在您的类路径中导入库后,您可以简单地将其用作

Reader in = new FileReader(file); //The file is the file which you get from the request(java.io.File)
Iterable<CSVRecord> records = CSVFormat.EXCEL.parse(in);
for (CSVRecord record : records) {
    //Do something with the records
}

For more information look into https://commons.apache.org/proper/commons-csv/index.html 有关更多信息,请访问https://commons.apache.org/proper/commons-csv/index.html

I also had a similar requirement, where I need to upload a jsp file through jsp and process it through Servlet 我也有类似的要求,我需要通过jsp上传一个jsp文件并通过Servlet处理它

So Here I used the Library called opencsv by Apache. 因此在这里,我使用了Apache称为opencsv的库。

upload.jsp upload.jsp

<form action="./upload" method="post" enctype="multipart/form-data">
    <input type="text" name="description" />
    <input type="file" name="file" />
    <input type="submit" />
</form>

UploadServlet.java UploadServlet.java

import com.opencsv.CSVReader;


@WebServlet(name = "upload", urlPatterns = { "/upload" })
@MultipartConfig
public class UploadServlet extends HttpServlet {

    public UploadServlet() {
        super();
    }

   protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        Part filePart = request.getPart("file"); 
        InputStream fileContent = filePart.getInputStream();

        Reader in = new InputStreamReader(fileContent);

        CSVReader reader;
        Iterator<String[]> iterator;

        try {

            reader = new CSVReader(new InputStreamReader(fileContent));
            iterator = reader.iterator();

            String[] row = iterator.next();

            Map<Object, String> map = new HashMap<>();
            for(int i = 0; i < row.length; i++){
                map.put(i, row[i]);

                //Do rest of the code

            }

        }catch(Exception e) {}

        in.close();

    }

}

Additional : 其他

While developing the above requirement I also encountered a problem, where a exception is throw specifying ClassNotFound.... (When converting inputstream to CSVReader instance) 在开发上述要求时,我还遇到了一个问题,抛出异常,该异常指定ClassNotFound ....(将inputstream转换为CSVReader实例时)

It's because the library is not attached to Runtime environment even though it's properly attached to Development environment. 这是因为即使将库正确地附加到了开发环境,它也没有附加到运行时环境。

Solution : 解决方案:

Copy the library files to lib folder in the server location and restart the server (shutdown first then start). 将库文件复制到服务器位置的lib文件夹中,然后重新启动服务器(先关闭然后再启动)。 By doing this I was able to solve the issue 通过这样做,我能够解决问题

Another better option is to use some Build tool like gradle or maven rather than going with JSP/Servlet(my personal view) 另一个更好的选择是使用诸如Gradle或Maven之类的Build工具,而不是使用JSP / Servlet(我的个人观点)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM