Issue
I want to append the message entered in the form to the text area instead of replacing it using the doPost method of HttpServlet. I have only managed to completely replace the html...
@WebServlet(name = "helloServlet", value = "/hello-servlet")
public class HelloServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
out.println("<html><body>");
// dont redirect to a new page, but write the response directly to the response object
out.println("<form action=\"hello-servlet\" method=\"post\" target=\"chat\">");
out.println("Message: <input type=\"text\" name=\"message\"/>");
out.println("<input type=\"submit\" value=\"Submit\"/>");
out.println("</form>");
out.println("<textarea name=\"chatoutput\" id=\"chat\" cols=\"50\" rows=\"10\"readonly>");
out.println("Hello");
out.println("</textarea>");
out.println("</body></html>");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String message = req.getParameter("message");
}
}
Solution
You have to store the chat somewhere. You could use a database or a file. An alternative place is to use a Servlet member variable. Of course chat will be lost when the server is shutdown. Here is demonstration code.
package rick;
import java.io.IOException;
import java.io.PrintWriter;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
@WebServlet(name = "helloServlet", value = "/hello-servlet")
public class HelloServlet extends HttpServlet {
String chat = "Hello <br>";
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
String message = req.getParameter("message");
if(message != null && !"".equals(message.trim())) {
chat += message + "<br>" ;
}
out.println("<html><body>");
out.println("<form action=\"hello-servlet\" method=\"post\" >");
out.println("Message: <input type=\"text\" name=\"message\"/>");
out.println("<input type=\"submit\" value=\"Submit\"/>");
out.println("</form>");
out.println(chat);
out.println("</body></html>");
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
}
Answered By - rickz
Answer Checked By - Robin (JavaFixing Admin)