简体   繁体   中英

Java servlet to write text file in Windows 10, NetBeans and Glassfish

I am trying to write a Java servlet that receives a simple post and writes the contents as a text file. I am developing in NetBeans 8.2 with Glassfish on a Windows 10 machine. I can write a text file via a Java applet , but the same file-write code does not work in the servlet. I am fairly new to NetBeans and Glassfish.

I have html that does the simple post. I generated the skeleton code of the servlet in NetBeans. I believe that the html is making a post to the correct location because it launches the index.html file that was automatically created by NetBeans. However, no text file is created. I do not see error messages within Netbeans, but I might not know where to look. I occasionally see an empty file named gfv3ee6.dpf created in the /build/web folder after a post. I am running NetBeans and the html as administrator.

I enclose my html and current Java code. I have tried many variations (different functions, different ways of defining the file path) discussed on Stackoverflow, but have not found the correct combination. I am enclosing one of the more simple examples that I have tried. Once I am past the hurdle of file-write, I would like to make future writes an append operation.

I would also appreciate any suggestions for best practices for when I ultimately deploy my html and servlet to a server. My overall goal is for the html be a long questionnaire that posts the responses to the Java servlet, wherein the servlet then scores the responses and sends a pdf file to the user. I have actually completed all this business logic (without the post) in an applet, but I cannot perform a simple file-write in a servlet.

To me, it appears that servlets and applets write files differently and that I cannot find the correct code for servlets.

I do not think this is an issue, but the name of the project is JustReact5, whereas the name of the class is Just5React.

HTML

<form action="http://localhost:8080/JustReact5" method="post">

  Your name:<br>
  <input type="text" name="yourname" <br>
  <input type="submit" value="Submit">   

</form>

Java

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author joseph
 */
public class Just5React 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");

PrintWriter pw = response.getWriter();
String yourname = request.getParameter("yourname");


try{
File file = new File("C:/temp/outputfile.txt");
FileWriter fstream = new FileWriter(file,true);
BufferedWriter out = new BufferedWriter(fstream);
out.write(yourname);
out.newLine();
out.close();
}

catch (Exception e){
System.err.println("Error: " + e.getMessage());
}



    }

// NetBeans doGet, doPost, getServletInfo code
// omitted for brevity

}

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
    <servlet>
        <servlet-name>Just5React</servlet-name>
        <servlet-class>Just5React</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>Just5React</servlet-name>
        <url-pattern>/Just5React</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
</web-app>

Kindly find the piece of code that might help. I have used Java 8 for storing response to a file.

response.getWriter().append("Served at: ").append(request.getContextPath());

    String emailID = request.getParameter("email");
    String password = request.getParameter("psw");
    String password_repeat = request.getParameter("psw-repeat");
    String remember = request.getParameter("remember");

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

    responseList.add(emailID);
    responseList.add(password);
    responseList.add(password_repeat);
    responseList.add(remember);

    System.out.println("Writing data : " + responseList);

    writeResponseToFile(responseList);

private void writeResponseToFile(List<String> responseList) {
String filePath = "/Users/sunilchityala/Desktop/writeResponseToFile.txt";

    try {
        Files.write(Paths.get(filePath), responseList, StandardCharsets.UTF_8, StandardOpenOption.CREATE, StandardOpenOption.APPEND);
    } catch (IOException e) {
        e.printStackTrace();
    }

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