调用将csv文件读入servlet的类方法

时间:2017-05-14 06:04:34

标签: java servlets

我正在编写一个代码,用于从多个发件人向连续循环中的一个收件人发送电子邮件。我必须从csv文件中读取发件人emailID,因为我已经编写了一个raeding代码,如下所示:

public class ReadFile {

    CsvReader senders;

    public CsvReader read(){

        try {
            senders = new CsvReader("C:/Users/D/Documents/Senderlist.csv"); 
            senders.readHeaders();

            while (senders.readRecord())
            {
                String SenderID = senders.get("SenderID");
                String ReceiverID = senders.get("ReceiverID");

                // perform program logic here
                System.out.println(SenderID + " : " + ReceiverID);
            }

            senders.close();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        ArrayList<String> al=new ArrayList<String>();
        al.add("senders");
        //traversing list through iterator 
        Iterator itr=al.iterator();  

        while(itr.hasNext()){  
            System.out.println(itr.next());  
        }  
        return senders;

    }

}

现在如何在我的servlet中调用此方法来连续循环读取和发送电子邮件,servlet如下:

public class MailController extends HttpServlet {

    private static final long serialVersionUID = 1L;
    private String ExchangeIP;
    private String port;

    public MailController() {
        super();
        // TODO Auto-generated constructor stub
    }

    public void init() {
        // reads SMTP server setting from web.xml file
        ServletContext context = getServletContext();
        ExchangeIP = context.getInitParameter("ExchangeIP");
        port = context.getInitParameter("port");
    }

    /**
    * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
    */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doPost(request, response);
    }

    /**
    * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
    */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // read from field
        List<File> uploadedFiles= saveUploadedFiles(request);
        String sender=request.getParameter("sender");// reading from the form page
        String recipient=request.getParameter("recipient");
        String subject=request.getParameter("subject");
        String content=request.getParameter("content");
        String resultMessage = ""; 

        try {
            EmailUtility.sendEmail(ExchangeIP, port,user, recipient, subject, content, uploadedFiles);
        resultMessage = "The e-mail has been sent successfully";
        } catch (Exception ex) {
            ex.printStackTrace();
            resultMessage = "There were an error: " + ex.getMessage();
        } finally {
            //deleteUploadFiles(uploadedFiles);
            request.setAttribute("Message", resultMessage);
    getServletContext().getRequestDispatcher("/Result.jsp").forward(request, response);
        }   

}

2 个答案:

答案 0 :(得分:0)

如果您唯一关心的是阅读CSV文件并在Servlet中迭代您从该文件中读取的项目,那么为什么不简单地在servlet中调用read()方法?并像这样更改read()方法

public List<String> getSenderEmails() {
        CsvReader senders = new CsvReader("C:/Users/D/Documents/Senderlist.csv");
        senders.readHeaders();

        List<String> senderEmails = new ArrayList<>();

        while (senders.readRecord()) {
            String senderID = senders.get("SenderID");
            String receiverID = senders.get("ReceiverID");

            // perform program logic here
            System.out.println(senderID + " : " + receiverID);
            senderEmails.add(senderID);
        }

        return senderEmails;
}

NB:

  • 我不知道你CsvReader正在做什么。但假设在这里它是一种库或Util calss。因此需要Exception handeling。
  • 但我建议的主要想法是返回CsvReader或类似的东西而不是返回您刚关注的电子邮件地址列表。

接下来你可以从servlet调用getSenderEmails()并迭代它来发送电子邮件

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // read from field
    List<File> uploadedFiles = saveUploadedFiles(request);
    String sender = request.getParameter("sender");// reading from the form page
    String recipient = request.getParameter("recipient");
    String subject = request.getParameter("subject");
    String content = request.getParameter("content");
    String resultMessage = "";    

    try {
        List<String> senderEmails = ReadFile.getSenderEmails();
        for (String user : senderEmails) {
            EmailUtility.sendEmail(ExchangeIP, port, user, recipient, subject, content, uploadedFiles);
        }
        resultMessage = "The e-mail has been sent successfully";
    } catch (Exception ex) {
    } finally {
    }
}

答案 1 :(得分:0)

如果您有班级名称,ReadFile

public class ReadFile {

    public static ReadFile thisCls;
    private String filename = "C:/Users/D/Documents/Senderlist.csv";

    public static ReadFile getSenderClass()
    {
        if(thisCls == null) thisCls = new ReadFile();

        return thisCls;
    }

    private CSVRead() {}

    public List<String []> readCsv() {

        try {
            CSVReader reader = new CSVReader(new FileReader(filename));
            // UTF-8
            // CSVReader reader = new CSVReader(new InputStreamReader(new FileInputStream(filename), "UTF-8"), ",", '"', 1);
            String[] s;
            while ((s = reader.readNext()) != null) 
            {
                data.add(s);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return data;
    }
}

然后,您的servlet类可能是

public class MailController extends HttpServlet {

    .....skip code....


    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // read from field
        List<File> uploadedFiles= saveUploadedFiles(request);
        String sender=request.getParameter("sender");// reading from the form page
        String recipient=request.getParameter("recipient");
        String subject=request.getParameter("subject");
        String content=request.getParameter("content");
        //String resultMessage = ""; 
        List<String> resultMessage = new ArrayList<String>();

        //<==============================
        CSVRead read = new CSVRead();
        List<String[]> data = CSVRead.readCsv();

        //assuming you have a sender in a second column value
        Iterator<String[]> it = data.iterator();

        String targetSender = null;

        try {
            String[] array = (String[]) it.next();

            targetSender = array[1];

            EmailUtility.sendEmail(ExchangeIP, port,sender, recipient, subject, content, uploadedFiles);

            resultMessage.add("The e-mail has been sent successfully to " + targetSender);
        } catch (Exception ex) {
            ex.printStackTrace();
            resultMessage.add("There were an error: " + ex.getMessage() + " while sending user " + targetSender);
        }


        try{
            while (it.hasNext()) {
                try {
                    String[] array = (String[]) it.next();

                    targetSender = array[1];

                    EmailUtility.sendEmail(ExchangeIP, port,targetSender, recipient, subject, content, uploadedFiles);

                    resultMessage.add("The e-mail has been sent successfully to " + targetSender);
                } catch (Exception ex) {
                    ex.printStackTrace();
                    resultMessage.add("There were an error: " + ex.getMessage() + " while sending user " + targetSender);
                }
            }
        } finally {
            //deleteUploadFiles(uploadedFiles);
            request.setAttribute("Message", resultMessage);
            getServletContext().getRequestDispatcher("/Result.jsp").forward(request, response);
        } 

    }

}

我不知道EmailUtility类的sendEmail方法。 我假设第3个参数必须是发件人。