简体   繁体   中英

Print to txt file from servlet and jsp's

I can't seem to get my web application to write to my WEB-INF/EmailList.txt My code is this

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 class:

    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);
            }
    }

I have gotten the real path as I was supposed to, but it isn't working any idea what is going on here I have tried it every way that I could and I can't seem to figure out what is going on, I am using Netbeans 8 and Tomcat 8 on a windows 7 machine. Is there something that may need to be reconfigured that I am overlooking.

Change the add method in UserIO class as below :

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

    }

Have you tried by closing the PrintWriter in UserIO ?

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

I suggest you one thing that is more easy to use rather than writing HTML content directly in Servlet.

Simply move the HTML content in a separate HTML/JSP file and forward the request to that HTML/JSP that will separate the view from Servlet.

Step to follow:

  • Get the parameters from the request that is submitted by form
  • Set the parameters in the request attributes
  • Use ${} pattern that will be replaced from the request attributes

Sample code:

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);
}

Project structure:

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

Read more about


Note: Don't forget to close the stream. Always handler it in try-catch-finally or as you are already using The try-with-resources Statement .

If you are using Eclipse IDE then you might looking at wrong location. The resultant file will be under tomcat tmp directory as shown below:

Simply print the resultant path and look at this location.

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

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