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);
}
}
You can use name
field. Thats the proper way and can go with the method request.getParameter()
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With