If a servlet is called by an HTTP GET or POST request that came from a form, you can call the getParameter method of the request object to get the values entered by the user in each form field.
Here's an example:
String name = request.getParameter("name");
Here the value entered in the form input field named name is retrieved and assigned to the String variable name.
Retrieving data entered by the user in a servlet is easy.
We also need a form in which the user can enter the data.
To do that, you create the form by using a separate HTML file.
The following code shows an HTML file named InputServlet.html that displays the form shown in the following.
<html>
<head>
<title>Input Servlet</title>
</head>
<body>
<form action="/servlet/InputServlet" method="post">
Enter your name:
<input type="text" name="Name">
<br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
The action attribute in the form tag of this form specifies that /servlet/InputServlet is called when the form is submitted, and the method attribute indicates that the form is submitted via a POST rather than a GET request.
The form itself consists of an input text field named name and a Submit button.
The form would get some text from the user and send it to a servlet.
The code below shows a servlet that can retrieve the data from the form.
package com.demo2s.inputservlet; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class InputServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) /*w w w. d e m o2 s . c o m*/ throws IOException, ServletException { String name = request.getParameter("Name"); response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<html>"); out.println("<head>"); out.println("<title>Input Servlet</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>"); out.println("Hello " + name); out.println("</h1>"); out.println("</body>"); out.println("</html>"); } }
The code retrieves the value entered by the user in the name field and uses it in the HTML that's sent to the response PrintWriter object.
PreviousNext