如何在我的servlet中显示html文本区域内容

时间:2018-04-12 22:37:33

标签: java html servlets netbeans

我想使用按钮连接它们,将html文本区域中的文本显示到servlet中。问题是我不知道如何从文本区域获取信息以显示在servlet中。 到目前为止,这是我的方法:

    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();
    }
}

这是我的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>

1 个答案:

答案 0 :(得分:0)

您应该将您的参数作为HTTP协议的GET方法发送。

因此,您需要实现servlet api的doGet方法。

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();
    }
}