How to get data from HTML Form in Servlet.

In this tutorial, you will learn how to get data from HTML form in ServletIt's not hard. First, we need an HTML form that asks the user for his/her name and age. The following page should suffice:

formdata.html file:
How to get data from HTML Form in Servlet.

This form should go in an HTML file under the server's document_root directory. This is the location where the server looks for the static file to serve. By putting this file in this, directory, it can be accessed directly at http://server:8080/formdata.

When the user submits this form, his name and age are sent to the GetFormData Servlet because we have set action attribute to point to the servlet. By default, the form is using the GET method, so any data is appended to the request URL as a query string. A servlet HttpRequest object gives it access to the form data in its query string.
Read more about HTTP Get Method: HTTP GET Method

GetFormData.java file:
How to get data from HTML Form in Servlet.

web.xml file:

How to get data from HTML Form in Servlet.

In above, we are writing a servlet that gets the form data from HTML page and print on the browser.The getParameter() method is used to get the data from HTML file.The getParameter() method gives servlet access to the parameter in its query string. It returns the parameter decoded value or null if the parameter is not specified.


Handling Post request in HttpServlet.

You have seen the servlet that implement doGet() method. Now this time, we are trying to handle post request. To handle the post request, we use doPost() method of Http servlet.

Read more about HTTP Post Method: HTTP Post Method

formdata.html file:

How to get data from HTML Form in Servlet.

GetFormData.java file:

How to get data from HTML Form in Servlet.

web.xml file:


How to get data from HTML Form in Servlet.

In general,it is best if a servlet implement either doGet() or doPost().Deciding which to implement depends on what sort of request the servlet needs to be able to handle. You may be wondering what would have happened the GetFormData servlet been accessed with a post request before we implemented doPost() method. In that case, an error to the client saying the requested URL does not support that method.

formdata.html file:

How to get data from HTML Form in Servlet.

GetFormData.java file:

How to get data from HTML Form in Servlet.



How to get data from HTML Form in Servlet.




How to get data from HTML Form in Servlet. How to get data from HTML Form in Servlet. Reviewed by Prashant Srivastava on October 13, 2018 Rating: 5

No comments:

Powered by Blogger.