简体   繁体   中英

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.

The HTML code goes likes this

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

Now In 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...? I do not want to store the CSV file anywhere. Just want to read its contents and print them.

You can read CSV files using Apache's CSV parser library for JAVA.

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

I also had a similar requirement, where I need to upload a jsp file through jsp and process it through Servlet

So Here I used the Library called opencsv by Apache.

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

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)

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). 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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