How to write HTML page to invoke a servlet

    0
    112
    Spread the love
    • 1
    •  
    •  
    •  
    •  
    •  
    •  
    •  
    •  
    •  
      1
      Share

    This post will tell you how to write a client end HTML file that will call your  back end servlet.
    http://www.askqtp.com/2012/01/how-to-call-servlet-from-html-using.html
    This post is further enhancement of this concept.

    The simple HTML code can be…..

    <html>
    <head>
    <meta http-equiv=”Content-Type” content=”text/html; charset=windows-1252″></meta>
     </head>
        <body>
            <form action=”servlet2″ method=”get” enctype=”text/plain” name=”sample”>
                <input type=”text” name=”text” value=”text” maxlength=”20″ size=”20″/>
                <input type=”submit” name=”Submit” value=”Submit”/>
            </form>
         </body>
    </html>

    So here we are creating a HTML file. There is a form inside it . Within the form there is a textbox where we can give some input. There is a submit button which submits data to the server. The method “get” is to send the information to the server. The target servlet is servlet2.

    The servlet will be…

    import java.io.IOException;
    import java.io.PrintWriter;
    import javax.servlet.*;
    import javax.servlet.http.*;

    public class Servlet2 extends HttpServlet {
        private static final String CONTENT_TYPE = “text/html; charset=windows-1252”;
        public void init(ServletConfig config) throws ServletException {
            super.init(config);
        }
        /**Process the HTTP doGet request.
         */
        public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            response.setContentType(CONTENT_TYPE);
            String data=request.getParameter(“text”);
            PrintWriter out = response.getWriter();
            out.println(“<html>”);
            out.println(“<head><title>Servlet2</title></head>”);
            out.println(“<body>”);
            out.println(“<p>The servlet has received a GET. This is the reply.Your data is </p>”+data);
            out.println(“</body></html>”);
            out.close();
        }
    }

    as the request type is get , so doGet has to be configured…Here inside the doGet we are receiving the request which is thrown from your HTML from written above. The container which is carrying this textbox value is “text”. The code to get the value is

    request.getParameter(variable_Name);

    You are done!!!! try sending data from Client to server and get a response. 

    Don't miss out!
    Subscribe To Newsletter

    Receive top technical news, lesson ideas, travel tips and more!

    Invalid email address
    Give it a try. You can unsubscribe at any time.

    Spread the love
    • 1
    •  
    •  
    •  
    •  
    •  
    •  
    •  
    •  
    •  
      1
      Share

    LEAVE A REPLY

    Please enter your comment!
    Please enter your name here