Servlet – Fetching Result
Servlet is a simple java program that runs on the server and is capable to handle requests from the client and generate dynamic responses for the client.
How to Fetch a Result in Servlet?
It is depicted below stepwise as shown below as follows:
- You can fetch a result of an HTML form inside a Servlet using request object‘s getParameter() method.
- request.getParameter() takes the name of the corresponding input field of HTML form (whose value we want to fetch) as the parameter. This method will then fetch/retrieve the value passed in that input field.
- Assign the value fetched from request.getParameter to a String variable because this method returns a String value.
- Note: If you submit an integer or float value through the HTML form and want to retrieve it in the same datatype, then you will have to typecast the value while/after retrieving it through request.getParameter(), as this method returns only a String value.
In order to display the result through a Servlet, print the String variable which has stored the value retrieved from request.getParameter()
The steps are as follows:
- Create an HTML form with an appropriate method. Be mindful of the method you use in the HTML form, whether get or post.
- Create a Servlet.
- Inside the Servlet, write the logic inside doGet() or doPost() method accordingly.
Note: In the following code, logic is written in doGet() method because, in the (above) HTML form, the method is “get” by default as the method is not explicitly mentioned as the post in the HTML form.
Note: Kindly learn how to create a Servlet before moving on to fetching results.