Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Submitting two or more forms to the same servlet iin JSP

Tags:

java

jsp

servlets

I was learning JSP where i created a login.jsp and register.jsp. Once form in registration page got submitted i am submitting all the values in RegisterUser.java (SERVLET) and getting via dopost later writing to DB. Now i need to submit another form in login.jsp to the same servlet RegisterUser.java (SERVLET). How to create multiple dopost in servlet. If created how the servlet will identify. Please give me the explanation in detail. Thanks in Advance.

like image 301
Vignesh Gopalakrishnan Avatar asked Feb 24 '13 17:02

Vignesh Gopalakrishnan


2 Answers

Look a servlet can have only one doPost method. Now its up-to you to figure out which form is submitted. You can have a hidden field with same name but different values in different forms and in doPost method you can figure out using this value.

String hiddenParam=request.getParameter("Parameter-Name")
if(hiddenParam.equals("value1"){
 //form 1 was posted
}else if(hiddenParam.equals("value2"){
  //form 2 was posted
}

In-fact if you are using Java 7 you can have switch of String to shorten up the code

switch(hiddenParam){
  case "value1":
    //form 1 was posted
    break;
  case "value2":
    //form 2 was posted
    break;
}
like image 95
kaysush Avatar answered Sep 21 '22 16:09

kaysush


create a field
in login form
<input type="hidden" name="pageName" values="login"/>
in register form
<input type="hidden" name="pageName" values="register"/>

now in your servlet dopost method
check
if(request.getParameter("pageName").equals("login"))
{
// do login code here
}
if(request.getParameter("pageName").equals("register"))
{
// do register code here
}
like image 32
Hussain Akhtar Wahid 'Ghouri' Avatar answered Sep 21 '22 16:09

Hussain Akhtar Wahid 'Ghouri'