0

I want to display the text from the text area of an html into a servlet using a button to connect them. The problem is that i dont know how to take the information from the text area to display in the servlet. This is my method so far:

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException
    {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<h1>Display content here </h1>");
//Here I want to have the text area content displayed.
        out.println();
    }
}

Here is my html:

<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>Sample</title>
        <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    </head>
    <body>
        <div>
            <p>show content of text area when clicking the button</p>
            <p></p>    
                <form action="MyServlet" method="GET">
                <textarea name= "name" rows="1" cols="30"></textarea>
                <p></p> 
                <button type="submit" href="MyServlet.do">Get content</button></form>
        </div>
    </body>
</html>
  • https://docs.oracle.com/javaee/6/api/javax/servlet/ServletRequest.html#getParameter(java.lang.String) – vanje Apr 12 '18 at 23:13
  • the problem is i dont know how to add the method to the servlet. My glassfish server has all the appropriate changes. – coolhuggies Apr 12 '18 at 23:37
  • If you are wanting the HTML to be interactive with a servlet then you are going to need to use Ajax (maybe jquery). Otherwise the when clicking on a submit button the `form` will be redirected. – Scary Wombat Apr 13 '18 at 01:45

1 Answers1

0

You're supposed to send your parameter as a GET method of HTTP protocol.

So, you need to implement doGet method of the servlet api.

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    try
    {
        response.setContentType("text/html");
        String name = request.getParameter("name") ;
        PrintWriter out = response.getWriter();
        out.println("<h1>Display name of your text area here: </h1>");
        //Here I want to have the text area content displayed.
        out.println(name);
        out.println();
        out.flush();
    }
    catch(Exception ex)
    {
        ex.printStackTrace();    
    }
    finally
    {
        out.close();
    }
}
tommybee
  • 2,409
  • 1
  • 20
  • 23