Working with multiple buttons on a jsp form....!

Hi guys...!
I have a jsp form, which has 3 buttons (submit, update, cancel), and I also have a java Servlet that processes that form.
In my java Servlet, i have a method called submitData(). I also want to have a method called updateData(), which will be called when the user clicks on the update button.
These are the codes in my jsp form:
<SCRIPT language="JavaScript" type="text/javascript">
               function submitFunction (i) {
                    if (i==1) {
                         document.theForm.action="/MyWebApp/FormServlet";
                    if (i==2) {
                         document.theForm.action="/MyBugWebApp/FormServlet";
                    if (i==3) {
                         document.theForm.action="/MyWebApp/DisplayForm.jsp";
                    document.theForm.submit()
          </SCRIPT>
<form name="theForm">
<input type="button" value="Submit" onClick="submitFunction(1)"></input>
<input type="reset" value="Reset"></input>
<input type="button" value="Cancel" onClick="submitFunction(3)"></input>
<input type="button" value="Update" onClick="sumbitFunction(2)"></input>
</form>
As u can see, both the submit and the update button use the same java servlet file. But inside that java servlet file, I want to have methods that will be called inside my doPost() method when the user clicks on update or submit.
I've tried to pass a value through the httpRequest but it doesn't work... This is what I did.
In my javaScript, I added this value in the action attribute:
document.theForm.action="/MyWebApp/FormServlet?id=submit";
document.theForm.action="/MyWebApp/FormServlet?id=update";
I did that because I wanted to be able to retrieve the value of the "id" in my servlet and check which type of action was sent and then call the appropriate function in my servlet.
But, it doesn't work. It returns "null" as the value for "id"
Does anyone know how to do this task??...or what am I doing wrong in my code???
Thanks...

So there are really two solutions to this:
1) Use <input type="submit" instead of buttons. Give all three buttons the same name but different values. Then the button used to submit will be added to the list of parameters.
2) Add a hidden input to the form, and when the form determines which button was pushed, set a different value for the hidden input field. For example of both, take a look at this code:
<html>
  <head>
    <script type="text/javascript">
      function formSubmit(i)
        var toSubmit = document.getElementById("myForm")
        if (i == 1) toSubmit.doThis.value="one"
        if (i == 2) toSubmit.doThis.value="two"
        if (i == 3) toSubmit.doThis.value="three"
        toSubmit.submit()
    </script>
  </head>
  <body>
    <form id="myForm" action="" method="get">
      <input type="hidden" name="doThis" /><br />
      <input type="submit" name="whatToDo" onclick="formSubmit(1)" value="Submit" />
      <input type="submit" name="whatToDo" onclick="formSubmit(2)" value="Cancel" />
      <input type="submit" name="whatToDo" onclick="formSubmit(3)" value="Update" />
    </form>
  </body>
</html>For method one, if the servlet did:
String whatToDo = request.getParameter("whatToDo");
if ("Submit".equals(whatToDo)) {
  //doSubmit();
} else if ("Update".equals(whatToDo)) {
  //doUpdate();
} else if ("Cancel".equals(whatToDo)) {
  //doCancel();
} else if ("Reset".equals(whatToDo)) {
  /doReset();
} else {
  //error situation
}Or you could instead look at the hidden value:
String doThis = request.getParameter("doThis");
if ("1".equals(doThis)) { ... }I personally like the submit button with the same names and different values, since the second method breaks if the user has javascript disabled.

Similar Messages

  • Multiple submit buttons in a jsp form?

    I've been doing some research and found out that multiple buttons in a JSP form are possible by two ways:
    - We can obtain the value of the submit button to know which one was clicked in the parameters of the request using the name of the buttons (which should be the same for all the submit buttons).
    - We can change the submit destination using Javascript (Horrible solution since I want my web site to be safe to be used even if Javascript isn't active in clients browsers. I will use it of course since we can do amazing things with it but I want my website to be able to work without it also)
    WHAT annoys me is the fact that the value of a submit button is also his text, so if I change the text of the submit button, I will always have to check the servlet to do the corresponding change.
    Is there a third choice to be able to use multiple buttons?
    Olivier Voutat

    It seem rather convoluted at first but it's really good. I've not worked with JSF so I've no idea how that compares but from what I know, Craig McClanahan, who came up with Struts, worked on JSF also, so I guess it could only improve on Struts.
    EDIT: Here's a search result on Google'ing his name: http://www.theserverside.com/news/thread.tss?thread_id=29068
    But like I said, you don't have to use Struts ( which only uses standard JSP/ Servlets stuff anyway ), you simply use one of the ideas from it.
    For example; you have a properties file, say "/WEB-INF/properties/myProps.properties" with these entries:
    #USERS MODULE
    users.button.save=Save User
    users.button.search=Search User By Name
    users.button.delete=Delete UserThis would be a key: users.button.save to the value Save User
    Now, in your JSP, you use JSTL <fmt> tags:
    <fmt:setBundle basename="properties.myProps"/>
    //set the resource bundle you want to use
    //and create buttons with the proper values
    <input name="myButton" type="submit"><fmt:message key="users.button.save"/></input>
    <input name="myButton" type="submit"><fmt:message key="users.button.search"/></input>This would create buttons with text "Save User" and "Search User By Name" respectively
    Now, finally, in your servlet:
    //create a map of the properties,
    //possibly on app startup using a ServletContextListener
    //and put it in the servlet context for access everywhere
    HashMap myProps = (HashMap)getServletContext.getAttribute("myPropertiesMap");
    String buttonClicked = request.getParameter("myButton");
    if ( buttonClicked.equals((String)myProps.get("users.button.save")) )
    //perform save action
    else if ( buttonClicked.equals((String)myProps.get("users.button.search")) )
    //perform search action
    //etcYou'll obviously want to optimize this. Perhaps make a method that handles the comparison so you can have neater if conditions. But you get the idea, right?
    Edited by: nogoodatcoding on Oct 4, 2007 8:12 PM

  • Working with Multiple Files in Workspace Layout

    If I was working with multiple files in the workspace layout, they each used to be available for selection from a tab.  Now I can either cascade the files horizontally or vertically - but not have them appear in a tab across the top of the workspace layout.
    Does anyone know how to set the workspace to present multiple files in tabs?  I have CS3.

    Tanya,
    This may not help, but the times when that happens to me is when I go too fast and some operations haven't finished. I then try to select a file that hasn't completed and the file I select is in the process of having the data updated. The worst is when it is trying to render as I am doing something.
    I hope this helps some.
    Mel

  • Working with  multiple layers in CS 3 ?

    In order to work with multiple layers in cs3, I first need to open few images to work with,and when I open few images it only shows last image that I opened.Frist images can't be seen in workspace, and when I open new document I can't see not even one photo I opened?

    try tapping the F key a few times until you get to the screen mode that allows you to see all image windows.

  • Does WRT54GP2 work with multiple ViOP providers ?

    My question is, Does WRT54GP2 router work with multiple ViOP providers ? Can I use it with a ViOP provider other then Vonage ?
    Thanks, John

    Yes you definately can , all you need is a VOIP adapter that supports SIP . It's a standard protocol and is supported by all routers and VOIP providers

  • Reg:working with multiple windows in webdynpro-abap

    Hi ,
    How can we create multiple windows and how can we link them...
    suppose we have 3 fields on first screen .how to move the data from the first screen to second screen..
    Thanks & Regards
    Suman Puthadi

    Hi
    As per your Subject you are looking for "working with multiple windows in webdynpro-abap" and for abap there is a different forum. Web Dynpro ABAP
    Hope its clear to you...
    Even you can read this post when ever you get time Read before posting
    Regards
    Ayyapparaj

  • Problem when working with multiple sequences

    Dears,
    In order to make life easier (I am currently working on a rather long project), I work with multiple sequences, one per chapter.
    My problem: I named one sequence "assembly sequences" in order to add the various sequences. I dropped the sequence no 1, then no 2. All works fine, beside that when playing the sequence no 2, I see two black lines on top and bottom of the screen for the all length of the sequence. Which is not the case when I click on the sequence itself and play it independently.
    Any idea how to solve this ?
    Thanks
    Nic

    Thanks, what happened is that :
    1st sequence is like this : Frame size 720x576 pixels, video rate 25fps, Compressor DV-Pal. And I think it is the one appropriate for me and my country.
    2nd sequence is like this : Frame size 720x480 pixels,
    video rate 29.97 fps, Compressor DV-DVPRO-NTSC.
    I think I should change the second sequence setting, but can I do it after all the work I have done, and continue making a 3rd, 4th and so on ?
    Tx for your precious help,
    Nicolas

  • Why is scrolling not working with multiple youtube embeds layed out vertically in a stack on one page?

    Why is scrolling not working with multiple youtube embeds layed out in a stack on one page?

    Hi ,  
      This is a sort of performance issue , because your program takes more than the max time set for the program to execute in foreground.
    There are many stuff in program which will hamper your performance.
    I will list down a few
    1. SELECT *
    FROM konp
    INTO CORRESPONDING FIELDS OF TABLE konp_itab
    FOR ALL ENTRIES IN a363_itab
    WHERE knumh EQ a363_itab-knumh
    in this statement you are using for all entries a363_itab , but before this statement you are not checking if the table has any entry or not , please do remember that for all entries has this characterstic , that if you internal table does not contain any record , then all the records are selected from the database table. So in this case if you table a363_itab is empty , so what you want is no data must be seelcted from table konp , but what will happen is all the records in KONP will be seelcted.
    2. While retreiving data you are using seelct * even though you do not require all the fields , an example is
    <b>SELECT *
    FROM mkpf
    INTO CORRESPONDING FIELDS OF TABLE mkpf_itab
    FOR ALL ENTRIES IN mseg_itab
    WHERE mblnr EQ mseg_itab-mblnr.</b>
    in this your internal table contains only 2 fields
    <b>mblnr LIKE mkpf-mblnr, "Number of Material Document
    bldat LIKE mkpf-bldat, "Document Date in Document</b> , but to get these 2 fields you are selecting all the fields of the table.
    3. In select you are using into corresponding fields of table , it is not a good practice., so please avoidd it.
    Please understand that you must try to reduce the access to your database tables and try to keep it minimal , because this same thing may happen becasue data in DEV is very less compared to the volume of data in production , so a program working in DEV will take much more time in PRD if not written properly and may result in timeouts , as in your case.
    Please try to make chanegs to the prorgam and see if it works.
    In case you have more queries , please do revert back.
    Regards
    Arun
    *Reward points if replay is helpful

  • Maintain performance while working with multiple shape layers (~50 )

    Hey guys, I've been working on some projects lately where I need to animate a lot of shape layers cascading, arraying, with various animation properties. When I get to the point of using 30-60 or so shape layers, and they're all doing some kind of scale, position, etc. animations, my computer slows to a complete crawl. This then forces me into using a single shape layer and the repeater functions. These can work well sometimes, and don't hamstring the flexibility too much, UNTIL you need to incorporate varying colors. At that point, I usually switch my shape layers to masks and place a layer below with varying colors as needed. The shape animations then reveal those colors, but this doesn't work for a complex object that in itself requires many colors. Sooo...
    What kind of workflows do you all have for working with multiple semi-complex objects at once? I figure I must be missing something, because this has gotten really limiting. Is everyone just working with 256GB of RAM?
    FYI, my computer specs are:
    2 x 2.66 GHz 6-Core Intel Xeon
    32 GB 1333 MHz DDR3 ECC
    ATI Radeon HD 5870 1024 MB
    OS X 10.9.4 (13E28)
    Thanks!!

    Pre-comping can speed up your previews if you are using disk cache, but nothing will speed up  your first ram preview or a ram preview after a keyframe change except a better optimized system. All it takes to slow things down is one effect or a footage file that causes AE to start consuming memory and processor power.
    As a test I just created a gradient filled rectangle, added rotation keyframes, duplicated the layer so I have 64 copies on my Mac Mini and tried a ram preview compared with the same comp with only 1 layer. Almost no difference in the time it took to preview 10 seconds. Threw in a scale transform for all layers and again, not much difference between one shape layer and 64. To make things much harder I change the rectangle to a Polystar and animated everything in the Polystart transform properties, set up a composition with 128 duplicates and a comp with one layer. 2.5 seconds for a ram preview at quarter rez for a single layer, 10 seconds for a ram preview for 128 layers. That's more than acceptable to me for a two year old Mac Mini with 16 gb of ram. Increasing the zoom factor to 50% with Resolution set to Auto doubled the ram preview time which was still acceptable.
    This makes me wonder what else is going on in your composition. Any effects or other things going on? Have you optimized your system for maximum performance? There are links with suggestions for doing that all over this site as well as the Adobe recommendations found here: Optimizing After Effects Performance

  • When working with multiple artboards, are there separate layers panels for each artboard?

    Just started working with multiple artboards in ai but have read nothing about the layers panel, whether you use one layers panel for all the artboards or if the layers panel is duplicated so there is one for each artboard.

    I don't really understand your problem, but I've had headaches with managing a GUI before (as many programmers have, I'm sure).
    My best advice, if the scheme your using to build and manage a GUI is too confusing for you, the programmer, to easily understand/manage, change the scheme. Even if this means recoding a good deal of your program (though, hopefully, you've kept the GUI as seperate from your functional code as possible) it should be worth it.
    Perhaps a clearer explination of your problem would help better illustrate your problem?
    -Rejun

  • How do icloud and itunes match work with multiple libraries?

    How do icloud and itunes match work with multiple libraries?

    This forum is for troubleshooting compatibility issues between Macs and Windows, not iTunes. You'll probably want to repost your question in the iTunes discussions:
    http://discussions.apple.com/category.jspa?categoryID=150

  • Working with two buttons in jsp

    hi
    My working with jsp's in struts.
    I have a jsp with two buttons "Save" and "Delete".
    My requirement is, on clicking either the "save button" or "Delete button" in jsp, it should call the corresponding code in the Action class.
    wht is the logic required to call the corresponding code in the Action class ?
    Thanks

    hi
    Thanks nani and jHyena for ur reply , but its not working, can u tell me where i went wrong, how to set them in jsp and action class.
    This is my Action class
    public class EditUserDetailsAction extends Action {
          * Generated Methods
          * Method execute
          * @param mapping
          * @param form
          * @param request
          * @param response
          * @return ActionForward
         public ActionForward execute(ActionMapping mapping, ActionForm form,
                   HttpServletRequest request, HttpServletResponse response) throws DaoException {
                   System.out.println("---------------in execute() befor try/catch-----------");
    //**************************the problem is here calling in if()/else, how should i call i?**************      
          if() {
                    try{
                        EditUserDetailsForm editUserDetailsForm = (EditUserDetailsForm) form;
                        System.out.println("------------ execute()-----------------");
                        DaoImplementer daoImpl = new DaoImplementer();
                        Integer editUid       = (Integer) editUserDetailsForm.getUser_Id();
                        String editName       = (String)  editUserDetailsForm.getName();
                        String editTitle      = (String) editUserDetailsForm.getTitle();
                        String editEmail      = (String) editUserDetailsForm.getEmail();
                        Integer editTelephone = (Integer) editUserDetailsForm.getTelephone();
                        String  editUserName  = (String) editUserDetailsForm.getUserName();
                        String editPassword   = (String) editUserDetailsForm.getPassword();
                        daoImpl.registerUser(editUid, editName, editTitle, editEmail, editTelephone, editUserName, editPassword);
                        System.out.println("------------sent to model components---------------");
                        System.out.println("----------forwarding to edituserdetail.jsp----------");
                        return mapping.findForward("editUserDetails");
                   catch (Exception e) {
                        System.out.println("@@@ ---Exception in EditUserDetailsAction class--@@@@");
                        throw new DaoException("Error adding userDetails: ",e);
                   return mapping.findForward("addUserDetails");
    Here is the jsp
    <html:html locale="true">
      <head>
        <html:base />
        <title>editUserDetails.jsp</title>
        <script type="text/javascript">
             function save_display(){
                  var x = confirm("Save: Are you sure ?")
                  if( x == true ){
                       confirm("Save: OK")
                  else{
                       text("Save: Cancelled")
             function delete_display(){
                  var y = confirm("Delete: Are you sure ?")
                  if( y == true ){
                       confirm("Delete: OK")
                  else{
                       alert("Delete: Cancelled")
             function funSave(){
                  document.form[0].ID.value = id;
                  form[0].ID.value.action="<%=request.getContextPath()%>/division/editDesignation.app?save=save";
                   form[0].ID.value.method="post";
                   form[0].ID.value.submit();
             function funDelete(){
                  function funSave(){
                        document.form[0].ID.value=id;
                        form[0].ID.value.action="<%=request.getContextPath()%>.app?save=save";
                        form[0].ID.value.method="post";
                        form[0].ID.value.submit();
        </script>
         <meta http-equiv="pragma" content="no-cache">
         <meta http-equiv="cache-control" content="no-cache">
         <meta http-equiv="expires" content="0">   
         <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
         <meta http-equiv="description" content="This is my page">
         <!--
         <link rel="stylesheet" type="text/css" href="styles.css">
         -->
      </head>
      <body>
      <html:javascript formName="editUserDetailsForm"/>
      <html:form action="/editUserDetails" onsubmit="return validateEditUserDetailsForm(this);">
                   user_Id : <html:text property="user_Id"/><html:errors property="user_Id"/><br/>
                      name : <html:text property="name"/><html:errors property="name"/><br/>
                     title : <html:text property="title"/><html:errors property="title"/><br/>
                telephone : <html:text property="telephone"/><html:errors property="telephone"/><br/>
                     email : <html:text property="email"/><html:errors property="email"/><br/>
                 userName : <html:text property="userName"/><html:errors property="userName"/><br/>
                 password : <html:password property="password"/><html:errors property="password"/><br/>
                           <html:submit property="save" value="Save"  onclick ="funSave()"/>
                           <html:cancel property="delete" value="delete" onclick="funDelete()"/>
      </html:form>
      </body>
    pls let me know how to set the hidden variables within the  above jsp .
    and  in Action class how to call it.
    I would be very thankful to u guys.
    Thanks

  • H:inputtext not working with multiple forms in JSF2.2

    h:inputText is not working in the latest JSF2.2 with multiple forms. I have 2 forms
    form1 have: one command button and one input text
    form2 has: one input text and one output label
    on click of command button in form1, i am rendering the form2(both outputlabel and input text).
    but only output label is rendered properly with correct values (corresponding getter method gets called and value is displaying) but the input text is not calling the corresponding getter method hence showing null.
    Note: we noticed this issue only if we use multiple forms, within single form its working fine. also it worked fine in JSF2.0
    Version used: JSF api - 2.2 (com.sun.faces) JSF impl - 2.2 (com.sun.faces)
    let me know if anyone have solution to handle this.
    the forms are not nested and both the beans are in View scope.  
    <h:form id="form1" prependId="false">
    <a4j:commandLink id="actionEdit" title="Click" action="#{bean.action}" 
    render="paymentInstructionDetail" styleClass="iconLarge edit" />
    </h:form>
    <h:form id="form2" prependId="false">
      <a4j:outputPanel ajaxRendered="true" id="paymentInstructionDetail">
      <h:inputText value="#{bean1.amount}" id="sample"/>
      <h:outputLabel value="#{bean1.amount}" id="sampleLabel"/>
     </a4j:outputPanel>
    </h:form>

    Your link doesn't work. Do you mind reporting it?

  • Print to pdf often doesn't work with multiple pages?

    When I try to print to pdf, it often doesn't work right.
    I can select, for example, multiple Excel worksheets to print. It looks fine with 4 pages in Preview, but when I select save as .pdf, it only prints 2 of the 4 pages, and it prints those in 2 separate documents rather than a single .pdf document with multiple pages.
    Is there a way to do this? Is this an Apple error or Microsoft error? Since it looks fine in Preview, my guess it is an Apple error?
    Mark

    It sounds like this is the problem with the way Apple handles multiple orientations in a pdf document. You can use Acrobat to print the files - it handles multiple orientations correctly. There was a previous thread on this:
    http://discussions.apple.com/message.jspa?messageID=1983431#1983431

  • Couldnt work with multiple key fields in keyword search

    Hi,
    I have some issue while working keyword search uder free form search in datamanager. in my repository i have two keyfields name(default field) and nation(lookup flat). but while working with keyword search if i pass any value that is comparing with only the values under keyfield name not comparing with other keyfield nation values. i am working with MDM 5.5 sp6. It would be appreciable if any one solve this issue.
    Regards
    Ravi

    Hi Ravi,
    If you want to perform Keyword search for Nation field as well without changing it's field type; then plz follow these steps:
    1. Set the Keyword property for Nation Field as Normal in Main table.
    2. Now go to the lookup table to which Nation field is looking into (say the Lookup table name is Nations).
    3. Now set the Keyword property for Nation field as Normal in the lookup table (Nations table) as well.
    4. Go back to Main table and now perform Keyword search. This time it will perform the search on both the fields (i.e., Name as well as Nation).
    Please let us know, if problem still persists.
    Regards,
    Varun

Maybe you are looking for

  • Picking the right values from tables - SQL (select statement)

    Hi everyone, I'm facing the litlle(?) problem in Oracle environment. Let me explain: I have two tables. TABLE 1 Id1 | Val1 | Id2 | Val2 A | 44 | B | 36 B | 36 | A | 44 TABLE 2 Id | Name A | New York B | Seattle I need to get from those tables, using

  • Unistalling vista in parallels and installing xp in boot camp

    okay i have a macbook, running leopard. i currently have parallels running vista but i want to remove both and install boot camp and xp with a disk my friend has. i got my computer from macmall and so they installed vista and parallels. can i remove

  • No Remote Desktop connection without VPN

    Not sure if this belongs here, my appoligies in advance.  I have a remote user with an ASA 5505 device that shoyld be able to connecte to a Remote PC using RDP, but is only able to do so if she 1st connects to the Check point VPN client.  I can't com

  • User/connection list

    is it possible to get a list from the router to see what is connected to it? (wrt54G) i see the dhcp list..but it lists only 2 computers and i can communicate with a gaming adapter that is out there but does not show up on the list. 

  • "Command Complete" notification

    I just switched from Toad and it had a neat feature where the toad icon in my task bar would flash when a command was complete, is there anything similar in sql developer 4?