0

I am trying to submit the form without clicking on SUBMIT button. I want to do it without javascript. Is there any way that I can achieve it? I want to get data in jsp from servlet using scriplets but how can I achieve it?

Firstname: Tom

Lastname: Jerry

index.jsp

 <form action="NewServlet" method="post">

  <input type="text" name="firstname"/>// while entering Tom here Jerry 
should appear automatically in below text box

  <input type="text" name="lastname"/>//I am trying to display Jerry while 
user enters Tom on above text box

 </form>

NewServlet.java

  String firstname=request.getParameter("firstname");
  if(firstname.equals("Tom"){
   String lastname="jerry";// return this value "Jerry to index. jsp
   request.setAttribute("lastname", lastname); 
  }
Tom
  • 761
  • 7
  • 22
  • 41
  • You will need a `submit` button which will call your `servlet` to get required response, else use `jquery` and `ajax` . – Swati Aug 18 '19 at 07:44
  • @Swati Hi ok can I fetch data from servlet without using javascript or ajax ? Because if sometime users have disabled javascript in their browser then its difficult – Tom Aug 18 '19 at 09:12
  • You can always inform user to [enable javascript](https://stackoverflow.com/questions/3262479/how-to-inform-if-javascript-is-disabled-in-the-browser) or else the other way you will need a `submit` button under your form to call servlet. – Swati Aug 18 '19 at 11:45

1 Answers1

0

You can try the following :

//scriplet to retrieve the value of the last name
<%
String lastname = null;
if(request.getAttribute("lastname")!=null)
 {
  lastname = (String)request.getAttribute("lastname");
 }else
 {
  lastname = "some_default_value";
 }
%>
<form action="NewServlet" method="post">

<input type="text" name="firstname"/>
//set value of the input tag to the lastname variable using scriplet
<input type="text" name="lastname" value = <%=lastname%>>

</form>

Your servlet file would be :

 String firstname=request.getParameter("firstname");
 if(firstname.equals("Tom")
{
 String lastname="jerry";// return this value "Jerry to index. jsp
 RequestDispatcher dispatcher = request.getRequestDispatcher("index.jsp");
 request.setAttribute("lastname", lastname); 
 dispatcher.forward(request, response);
 }

As for submitting without clicking a submit button, you can have a hidden button of type submit in the form. However this method is tedious and has an unnecessary call to the scriplet moreover it is bad practice in terms of the user's experience. In working it would seem as if the webpage is reloading just to get an automatic suggestion from the servlet.

Also this only works if the user fills in the first name and then clicks enter. Furthermore you would have to add another edge case to check whether to redirect back to index.jsp with the last name or accept the user provided one (in the event that they have). Hence I would suggest you check Auto complete using jquery