java - 从 servlet 和 jsp 打印到 txt 文件

标签 java jsp tomcat servlets netbeans

我似乎无法让我的网络应用程序写入我的 WEB-INF/EmailList.txt 我的代码是这样的

小服务程序:

    package email;

    import business.User;
    import data.UserIO;
    import java.io.IOException;
    import java.io.PrintWriter;
    import javax.servlet.ServletContext;
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;

    /**
     *
     * @author Richard Davy
     */
    @WebServlet(name = "AddToEmailServlet", urlPatterns = {"/AddToEmailServlet"})
    public class AddToEmailServlet extends HttpServlet {

         /**
         * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
         * methods.
         *
         * @param request servlet request
         * @param response servlet response
         * @throws ServletException if a servlet-specific error occurs
         * @throws IOException if an I/O error occurs
         */
         protected void processRequest(HttpServletRequest request, HttpServletResponse response)
                 throws ServletException, IOException {
            response.setContentType("text/html;charset=UTF-8");
            try (PrintWriter out = response.getWriter()) {
                /* TODO output your page here. You may use following sample code. */
                out.println("<!DOCTYPE html>");
                out.println("<html>");
                out.println("<head>");
                out.println("<title>Servlet AddToEmailServlet</title>");            
                out.println("</head>");
                out.println("<body>");
                out.println("<h1>Servlet AddToEmailServlet at " + request.getContextPath() + "</h1>");
                out.println("</body>");
                out.println("</html>");
            }
        }

        // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the +   sign on the left to edit the code.">
        /**
         * Handles the HTTP <code>POST</code> method.
         *
         * @param request servlet request
         * @param response servlet response
         * @throws ServletException if a servlet-specific error occurs
         * @throws IOException if an I/O error occurs
         */
        @Override
        protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
            //get parameters from the form
            String firstName = request.getParameter("firstName");
            String lastName = request.getParameter("lastName");
            String email = request.getParameter("email");

            //get relative file name
            ServletContext context = getServletContext();
            String path = context.getRealPath("/WEB-INF/EmailList.txt");

             //add info to text file
             User user = new User(firstName, lastName, email);
             UserIO.add(user, path);

            //send response to browser
            response.setContentType("text/html;charset=utf-8");
            PrintWriter out = response.getWriter();
            out.println(
                    "<!Doctype html public \"-//W3C//DTD HTML 4.0 Transitional//EN\">\n"
                    + "<html>\n"
                    + "<head>\n"
                    + "   <title>Thank you for Joining</title>\n"
                    + "</head>\n"
                    + "<body>\n"
                    + "<h1>Thanks for joining our email list</h1>\n"
                    + "     <p>Here is the information you gave:</p>"
                    + "         <table cellspacing=\"5\" cellpadding=\"5\" border=\"1\">\n"
                    + "             <tr>\n"
                    + "                 <td>First Name: </td>\n"
                    + "                 <td>" + firstName + "</td>\n"
                    + "             </tr>\n"
                    + "             <tr>\n"
                    + "                 <td>last Name: </td>\n"
                    + "                 <td>" + lastName + "</td>\n"
                    + "             </tr>\n"
                    + "             <tr>\n"
                    + "                 <td>Email: </td>\n"
                    + "                 <td>" + email + "</td>\n"
                    + "             </tr>"
                    + "         </table>\n"
                    + "         <p>If you wish to add another email address click the     return<br/>\n"
                    + "         button below. </p>"
                    + "         <form action=\"join_email_list.html\">\n"
                    + "             <input type=\"submit\" value=\"return\">\n"
                    + "         </form>"
                    + "     </body>\n"
                    + " </html>\n"                
            );
            out.flush();
            out.close();
        }  

        /**
         * Handles the HTTP <code>GET</code> method.
         *
         * @param request servlet request
         * @param response servlet response
         * @throws ServletException if a servlet-specific error occurs
         * @throws IOException if an I/O error occurs
         */
        @Override
        protected void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            doPost(request, response);
        }

        /**
         * Returns a short description of the servlet.
         *
         * @return a String containing servlet description
         */
        @Override
        public String getServletInfo() {
            return "Short description";
        }// </editor-fold>

    }

UserIO 类:

    package data;

    import business.User;
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.io.PrintWriter;

    /**
     *
     * @author Richard Davy
     */
    public class UserIO {
         public static void add(User user, String filepath) throws IOException{
            FileOutputStream file = new FileOutputStream(filepath, true);
            String firstName = user.getFirstName();
            String lastName = user.getLastName();
            String email = user.getEmail();
            PrintWriter writer = new PrintWriter(file); 
                writer.println(user.getEmail() + "|" + user.getFirstName() + "|" +   user.getLastName());
                //System.out.print(email + "|" + firstName + "|"
                       // + lastName);
            }
    }

我已经按照预期获得了真正的路径,但它不起作用,不知道这里发生了什么我已经尝试了所有可能的方法,但我似乎无法弄清楚发生了什么,我在 Windows 7 机器上使用 Netbeans 8 和 Tomcat 8。是否有我忽略的可能需要重新配置的东西。

最佳答案

修改 UserIO 类中的 add 方法如下:

public static void add(User user, String filepath) throws IOException {
        BufferedWriter buffer;

        buffer = new BufferedWriter(new FileWriter(filepath, true));

        buffer.write(user.getEmail() + "|" + user.getFirstName() + "|"
                + user.getLastName());
        buffer.newLine();
        buffer.close();

    }

关于java - 从 servlet 和 jsp 打印到 txt 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24154505/

相关文章:

jsp - grails 2.4.4不使用jsp页面

java - 枚举上的 JSTL foreach

Java Servlet 文件上传错误

apache - 如何将 Windows 上的 Apache 2.2 重定向到 Tomcat(同一台机器)

java - 使用 jcmFIPS jar 部署在 JBoss 上

java - 将 Java 桌面应用程序迁移到 Android 和 iPhone

java - 标签 <c :forEach/> si not doing anything

java - 无法在某些构建类型上运行自动化 Android 测试? JUnit 和 UiAutomator 导入无法解析

java - 使用 hibernate - envers 并获取历史记录时,池连接没有空闲连接?

java - 在 java :comp/env on Tomcat? 之外查找 JNDI 名称