我目前有两个文件,register.html和register.jsp。 HTML文件向用户询问某些信息,JSP文件应该将信息写入文本文件。我不断收到文件错误,特别是在PrintWriter部分。任何帮助将非常感激。谢谢!
这是我得到的错误:
An error occurred at line: 14 in the jsp file: /register.jsp
Duplicate local variable pw
11:
12: try {
13:
14: PrintWriter pw=null;
15: pw = new PrintWriter(new FileWriter(new File(nameOfTextFile), true));
16: // PrintWriter pw = new PrintWriter(new FileOutputStream(nameOfTextFile));
17:
register.html:
<%@ page import="java.io.*, java.util.Date" %>
<DOCTYPE! html>
<HTML>
<HEAD>
<TITLE>Registration</TITLE>
</HEAD>
<BODY>
<h1>Enter the following information to sign and create an account in the Book.</h1>
<form name=registrationForm action="register.jsp">
<table border=0>
<tr><td align=right>Username:</td>
<td><input type=text name="Username" size=25></td>
</tr>
<tr><td align=right>Password:</td>
<td><input type=text name="password" size=25></td>
</tr>
<tr><td align=right>Email address:</td>
<td><input type=text name="email" size=25></td>
</tr>
<tr>
<!--<td valign=middle align=right>Comments:</td>
<td><TextArea rows=5 cols=35 name="comments">none</TextArea>
</td>-->
</tr>
</table>
<br>
<input type="submit" value="Register" name="button" onClick="validatingForm()">
<input type=reset value="Start Over">
</form>
</BODY>
</HTML>
register.jsp:
<%@ page import="java.io.* , java.util.Date" %>
<HEAD>Thanks for registering!</TITLE></HEAD>
<BODY>
<%
String un =request.getParameter("Username");
String pw =request.getParameter("password");
String nameOfTextFile = "/xampp/tomcat/webapps/gb/userss.txt"; //directory path and name of file
try {
PrintWriter pw=null;
pw = new PrintWriter(new FileWriter(new File(nameOfTextFile), true));
// PrintWriter pw = new PrintWriter(new FileOutputStream(nameOfTextFile));
pw.println(un);
pw.println(pw);
pw.close();
} catch(IOException e) {
out.println(e.getMessage());
}
%>
</BODY>
</HTML>
答案 0 :(得分:1)
正如其他人所说,您应该将此代码移动到java类中。话虽如此,我相信你的问题是你已经定义了两个名为pw的变量。
String un =request.getParameter("Username");
String pw =request.getParameter("password"); //FIRST DECLARATION OF PW
String nameOfTextFile = "/xampp/tomcat/webapps/gb/userss.txt"; //directory path and name of file
try {
PrintWriter pw=null; //SECOND DECLARATION OF PW causes error
pw = new PrintWriter(new FileWriter(new File(nameOfTextFile), true));
// PrintWriter pw = new PrintWriter(new FileOutputStream(nameOfTextFile));
pw.println(un);
pw.println(pw);
pw.close();
} catch(IOException e) {
out.println(e.getMessage());
}
尝试:
String un =request.getParameter("Username");
String pw =request.getParameter("password");
String nameOfTextFile = "/xampp/tomcat/webapps/gb/userss.txt"; //directory path and name of file
try {
PrintWriter printWriter=null;
printWriter = new PrintWriter(new FileWriter(new File(nameOfTextFile), true));
// PrintWriter pw = new PrintWriter(new FileOutputStream(nameOfTextFile));
printWriter.println(un);
printWriter.println(pw);
printWriter.close();
} catch(IOException e) {
out.println(e.getMessage());
}