In this tutorial, you will learn how to get data from HTML form in Servlet. It'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:
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.
Read more about HTTP Get Method: HTTP GET Method
GetFormData.java file:
web.xml file:
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:
GetFormData.java file:
web.xml file:
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:
web.xml file:
GetFormData.java file:
How to get data from HTML Form in Servlet.
Reviewed by Prashant Srivastava
on
October 13, 2018
Rating:
No comments: