用JSP实现简单的留言板
时间: 2023-11-27 11:05:06 浏览: 61
Certainly! To implement a simple guestbook using JSP, you can follow these steps:
1. Create a new JSP file in your project and name it "guestbook.jsp".
2. Add a form to the JSP file that includes input fields for name and message:
<form action="addMessage.jsp" method="post">
Name: <input type="text" name="name"><br>
Message: <textarea name="message"></textarea><br>
<input type="submit" value="Submit">
</form>
3. Create a new JSP file named "addMessage.jsp" that handles form submission:
<%
// Get the input values from the request parameters
String name = request.getParameter("name");
String message = request.getParameter("message");
// Store the message in a file or database
// For example, you could use a FileWriter:
FileWriter writer = new FileWriter("guestbook.txt", true);
writer.write(name + ": " + message + "\n");
writer.close();
%>
4. Confirm that messages are being added to the file or database by displaying them on another JSP page. You could name it "viewMessages.jsp":
<%
// Read the messages from the file or database
// For example, you could use a FileReader:
FileReader reader = new FileReader("guestbook.txt");
BufferedReader br = new BufferedReader(reader);
// Display the messages in HTML format
out.println("<html><head><title>Guestbook</title></head><body>");
String line = null;
while ((line = br.readLine()) != null) {
String[] parts = line.split(": ");
String name = parts[0];
String message = parts[1];
out.println("<p><b>" + name + "</b>: " + message + "</p>");
}
out.println("</body></html>");
// Close the file
br.close();
reader.close();
%>
5. Test your guestbook by visiting "guestbook.jsp" and submitting messages. Then visit "viewMessages.jsp" to see the messages that have been posted.
I hope this helps! Let me know if you have any other questions.
阅读全文