从servlet和jsp'打印到txt文件

时间:2014-06-11 04:10:12

标签: java jsp tomcat servlets netbeans

我似乎无法将我的Web应用程序写入我的WEB-INF / EmailList.txt我的代码是这个

的Servlet

    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。有什么东西可能需要重新配置,我忽略了。

3 个答案:

答案 0 :(得分:0)

更改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();

    }

答案 1 :(得分:0)

您是否尝试关闭PrintWriter中的UserIO

if(writer!=null)
{
  writer.close();
}

答案 2 :(得分:0)

我建议你使用一个更容易使用的东西,而不是直接在Servlet中编写HTML内容。

只需将HTML内容移动到单独的HTML / JSP文件中,然后将请求转发到将视图与Servlet分开的HTML / JSP。

步骤:

  • 从表单
  • 提交的请求中获取参数
  • 在请求属性中设置参数
  • 使用将从请求属性
  • 替换的${}模式

示例代码:

thanksTemplate.jsp:

<!Doctype html public "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>Thank you for Joining</title>
</head>
<body>
    <h1>Thanks for joining our email list</h1>
    <p>Here is the information you gave:</p>
    <table cellspacing="5" cellpadding="5" border="1">
        <tr>
            <td>First Name:</td>
            <td>${firstName}</td>
        </tr>
        <tr>
            <td>last Name:</td>
            <td>${lastName}</td>
        </tr>
        <tr>
            <td>Email:</td>
            <td>${email}</td>
        </tr>
    </table>
    <p>
        If you wish to add another email address click the return<br />
        button below.
    </p>
    <form action="join_email_list.html">
        <input type="submit" value="return">
    </form>
</body>
</html>

AddToEmailServlet.java

@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");

    ...

    request.setAttribute("firstName", firstName);
    request.setAttribute("lastName", lastName);
    request.setAttribute("email", email);

    request.getRequestDispatcher("/WEB-INF/thanksTemplate.jsp").forward(request, response);
}

项目结构:

webapp
     |
     |___WEB-INF
               |
               |__thanksTemplate.jsp
               |__web.xml

了解更多关于

的信息

注意:请勿忘记关闭该流。始终在try-catch-finally或您已使用The try-with-resources Statement处理它。

如果您使用的是Eclipse IDE,那么您可能会查看错误的位置。生成的文件将位于tomcat tmp目录下,如下所示:

只需打印生成的路径并查看此位置。

.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\MyWebProject\WEB-INF\EmailList.txt