I am writing an online text editor for school. I have been able to save a file with a custom name, so that is not the problem. With an HTML form I have, it submits the text of the TextArea into a file specified by the user, then set the url to be blah.org/text.jsp?status=gen. Later in the code, I have the program write the file if the variable status == gen, otherwise do nothing. I am not able to create the file when I click submit, and I am thinking it has something to do with me getting the variable in the URL. Here is my code:
/* Set the "user" variable to the "user" attribute assigned to the session */
String user = (String)session.getAttribute("user");
String status = request.getParameter("status");
/* Get the name of the file */
String name = request.getParameter("name");
/* Set the path of the file */
String path = "C:/userFiles/" + user + "/" + name + ".txt";
/* Get the text in a TextArea */
String value = request.getParameter("textArea");
/* If there isn't a session, tell the user to Register/Log In */
if (null == session.getAttribute("user")) {
out.println("Please Register/Log-In to continue!");
if (status == "gen") {
try {
FileOutputStream fos = new FileOutputStream(path);
PrintWriter pw = new PrintWriter(fos);
pw.println(value);
pw.close();
fos.close();
}
catch (Exception e) {
out.println("<p>Exception Caught!");
}
} else {
out.println("Error");
}
}
and the form:
<form name="form1" method="POST" action="text.jsp?status=gen">
<textarea cols="50" rows="30" name="textArea"></textarea>
<center>Name: <input type="text" name="name" value="Don't put a .ext"> <input type="submit" value="Save" class="button"></center>
other code here </form>
Replace
if (status == "gen") {
with
if ( status.equals("gen") ) {
or even better
if ( "gen".equals(status) ) {
Your first statement does Object equality and not String equality. Therefore, it always returns false.
You're comparing Strings with ==
instead of comparing them with .equals()
. ==
compares the strings are the same object instance, not if they contain the same characters.
Make sure to read the IO tutorial . Streams should always be closed in a finally block, or you should use the Java 7 try-with-resources construct.
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.