5

My JSP contains this form tag:

<form action="MyServlet" method="post">
    Fname:<input type="text" id="fname" placeholder="type first name"/>
    <input type="submit" value="ok"/>
</form>

My servlet is:

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.cad.database.DatabaseClass;
import com.cad.example.service.InputService;


public class Input extends HttpServlet {

    private static final long serialVersionUID = 1L;
    public Input() {
        super();
        // TODO Auto-generated constructor stub
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String fname = request.getParameterById("fname");
        System.out.println("My name "+fname);
    }   
}
tpsaitwal
  • 422
  • 1
  • 5
  • 23

5 Answers5

6

You can use name field. Thats the proper way and can go with the method request.getParameter().

beta-tank
  • 390
  • 1
  • 4
  • 17
5

Add a name attribute to the input element. Now that, your HTML will look like,

<form action="MyServlet" method="post">
Fname:
<input type="text" name="fname" placeholder="type first name" />
<input type="submit" value="ok" />
</form>

This can be accessed anywhere in your servlet/java code as,

String fName = request.getParameter("fname");

As far as i know, ID attribute cannot be used to get values in java. JavaScript can be used in cases to get the innerText or innerHTML using an ID attribute.

ChandrasekarG
  • 1,384
  • 13
  • 24
3

You can use the below updates:

In jsp/html, add attribute name:

<input type="text" id="fname" name="fname" placeholder="type first name"/>

In servlet:

String fname = request.getParameter("fname");
1

Also add name="fname" to

<input type="text" name="fname" id="fname" placeholder="type first name"/>

Retrieve it like this

String fname = request.getParameter("fname");
Harshit
  • 5,147
  • 9
  • 46
  • 93
1

You already got your answer that you need to specify name attribute in your input text field

<input type="text" name="fname" id="fname" placeholder="type first name"/>

But why you need to specify this name attribute in input text field that may be still not clear to you.

We Use input text on form elements to submit information. Only input tags with a name attribute are submitted to the server. So if don’t specify the name attribute and do request.getParameter("fname"); you don’t get the value at server end at all.

Bacteria
  • 8,406
  • 10
  • 50
  • 67