2012-12-12 50 views
0

我正在爲學校寫一個在線文本編輯器。我已經能夠使用自定義名稱保存文件,所以這不是問題。使用HTML表單,我們將TextArea的文本提交到用戶指定的文件中,然後將url設置爲blah.org/text.jsp?status=gen。在後面的代碼中,如果變量status == gen,我有程序寫入文件,否則什麼都不做。當我點擊提交時,我無法創建文件,我認爲這與我在URL中獲取變量有關。這裏是我的代碼:沒有得到url變量與JSP

/* 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"); 
} 
} 

和形式:

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

回答

0

您將字符串與==進行比較,而不是將它們與.equals()進行比較。 ==比較字符串是否是相同的對象實例,如果它們包含相同的字符則不是。

請務必閱讀IO tutorial。流應該總是在finally塊中關閉,或者應該使用Java 7 try-with-resources構造。

0

更換

if (status == "gen") { 

if (status.equals("gen")) { 

甚至更​​好

if ("gen".equals(status)) { 

你的第一條語句是對象相等而不是字符串相等。因此,它總是返回false。