Java Servlet Get User Input


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.

Working with forms

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.

    <title>Input Servlet</title>  
    <form action="/servlet/InputServlet" method="post"> 
      Enter your name:&nbsp; 

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.

InputServlet servlet

The code below shows a servlet that can retrieve the data from the form.

package com.demo2s.inputservlet; 
import javax.servlet.*; 
import javax.servlet.http.*; 
public class InputServlet extends HttpServlet 
    public void doGet(HttpServletRequest request, 
         HttpServletResponse response) 
            throws IOException, ServletException 
        String name = request.getParameter("Name"); 
        PrintWriter out = response.getWriter(); 
        out.println("<title>Input Servlet</title>"); 
        out.println("Hello " + name); 

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.