Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read value of a input field in JSP form through a Servlet using id of that field? [duplicate]

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);
    }   
}
like image 404
tpsaitwal Avatar asked Dec 09 '22 01:12

tpsaitwal


2 Answers

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

like image 122
Anandhakumar Subramaniam Avatar answered Dec 10 '22 15:12

Anandhakumar Subramaniam


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.

like image 42
ChandrasekarG Avatar answered Dec 10 '22 15:12

ChandrasekarG