Solved

ImageButtonBean not working; JSP, STRUTS, very baffled.

Posted on 2004-10-26
1,064 Views
Last Modified: 2012-06-21

I have read up on the use of the ImageButtonBean and while it seems to be a unpreferred method, it is what my company is using so, to comply with our standards, I too, must use it. The button that is pushed is simply not detected. I have no idea what I am doing wrong. Here is my code; let me know if you see anything. Something that this code works on our test system but not on our local machines. I need to have it working in the test environment on my machine to debug it; otherwise, it will take a very long time to finish. Please, any help would be appreciated.

<!-- ----------Menu ActionForm ----------------------------------- -->

/*
 * Created on Oct 22, 2004
 *
 * To change the template for this generated file go to
 * Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments
 */
package gov.wi.state.dpi.checkDigit.Forms;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.*;
import org.apache.struts.validator.*;
import org.apache.struts.util.ImageButtonBean;

/**
 * @author jbaisden
 *
 * To change the template for this generated type comment go to
 * Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments
 */
public final class MenuForm extends ValidatorForm implements Serializable{
      
            private String currentPage=null;
            private String previousPage=null;
            private boolean blnManualInput=false;
            private boolean blnFileUpload=false;
            private ImageButtonBean imgMenuButton = new ImageButtonBean();
            private ImageButtonBean imgExitButton = new ImageButtonBean();
            private ImageButtonBean imgHelpButton = new ImageButtonBean();
            //System.out.println("Inside of Menu Form");
            
      public void setimgMenuButton(Object button) {            
            System.out.println("Inside of setimgMenuButton.");
            if (button instanceof String) return;
                  this.imgMenuButton = (ImageButtonBean) button;
            }
      
            public ImageButtonBean getimgMenuButton()
            {
                  return this.imgMenuButton;
            }
            //public void setimgclearButton(ImageButtonBean button) {
                        //this.imgclearButton = button;
            public void setimgExitButton(Object button) {      
                  System.out.println("Inside of setimgExitButton.");      
                  if (button instanceof String) return;
                        this.imgExitButton = (ImageButtonBean) button;
                  }
            public ImageButtonBean getimgExitButton()
                  {
                        return this.imgExitButton;
                  }

            public void setimgHelpButton(Object button) {            
                  System.out.println("Inside of setimgHelpButton.");
                  if (button instanceof String) return;
                        this.imgHelpButton = (ImageButtonBean) button;
                  }
                  
            public ImageButtonBean getimgHelpButton()
                  {
                        return this.imgHelpButton;
                  }
                        
            public String getSelected() {
                        if ( this.getimgMenuButton().isSelected()) {
                              return "menu";
                        } else if (this.getimgExitButton().isSelected()) {
                              return "exit";
                        } else if (this.getimgHelpButton().isSelected()) {
                              return "help";
                        }
                        
                        else return null;
            }
            
            /**
             * @return
             */
            public String getCurrentPage() {
                  return currentPage;
            }

            /**
             * @param string
             */
            public void setCurrentPage(String string) {
                  currentPage = string;
            }

            /**
             * @return
             */
            public String getPreviousPage() {
                  return previousPage;
            }

            /**
             * @param string
             */
            public void setPreviousPage(String string) {
                  previousPage = string;
            }      
            
            public void reset(ActionMapping mapping, HttpServletRequest request) {
                        ImageButtonBean imgMenuButton = new ImageButtonBean();
                        ImageButtonBean imgHelpButton = new ImageButtonBean();
                        ImageButtonBean imgExitButton = new ImageButtonBean();
                        // Reset values are provided as samples only. Change as appropriate.
                        System.out.println("Reset was called in MenuForm.");
                  }
                  
//      public ActionErrors validate(ActionMapping mapping, HttpServletRequest request)
//                  {
//                        if (this.imgclearButton.isSelected() || this.imgsearchButton.isSelected())
//                        {return (new ActionErrors());}
//                        else {return (super.validate(mapping,request));}
//
//                  }

}

<!-- ------------------------------------MENU ACTION---------------------------------- -->
/*
 * Created on Oct 22, 2004
 *
 * To change the template for this generated file go to
 * Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments
 */
package gov.wi.state.dpi.checkDigit.Actions;

import gov.wi.state.dpi.checkDigit.Forms.MenuForm;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

/**
 * @author jbaisden
 *
 * To change the template for this generated type comment go to
 * Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments
 */
public final class MenuAction extends Action {
      
      public ActionForward execute( ActionMapping mapping,
                                                  ActionForm form,
                                                  HttpServletRequest request,
                                                  HttpServletResponse response) {
                                                        
                  MenuForm menForm = (MenuForm)form;
                  String blah;
                  blah = menForm.getSelected();
                  System.out.println("BLAH is: " + blah);
                  System.out.println("Selected Button is: " + menForm.getSelected() ) ;
                  System.out.println("Inside of Menu Action");
                  System.out.println("mapping path: " + mapping.getPath() );
                  System.out.println("mapping forward: " + mapping.getForward() );
                                                  
                  return (mapping.findForward("success"));
                  
                  
                  
      }
                                                 
                                                 
}


<!-- ---------------------------------------Menu.jsp ---------------------------------------------- -->


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<%@ taglib uri="/tags/struts-logic" prefix="logic" %>
<%@ taglib uri="/tags/struts-html" prefix="html" %>
<%@ taglib uri="/tags/struts-bean" prefix="bean" %>

<html:html>
<HEAD>

<%@ page
language="java"
contentType="text/html; charset=ISO-8859-1"
%>

<META http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<META name="GENERATOR" content="IBM WebSphere Studio">

<META http-equiv="Content-Style-Type" content="text/css">
<LINK href="../theme/Master.css" rel="stylesheet"
      type="text/css">
<TITLE>PAGE TITLE</TITLE>
</HEAD>

<BODY>


<TABLE WIDTH="100%" BORDER="0" cellpadding="0" cellspacing="0">
<TR>
      <TD colspan=3 align="center">
            PAGE HEADER
            <hr width = "100%" color = "#69003c" align="center">
      </TD>
</TR>
<TR bgcolor = "LightGrey">
      <TD align="left" valign="middle" >
               PAGE HEADER
      </TD>
      
      <TD align="center" valign="middle">
            (* Required Field)
      </TD>
      
      <TD align="right" valign="middle">
      
      
            <html:form action="Menu.do" >
                  <html:image property="imgExitButton"
                      src="images/icons/exitdoorR.gif"
                      value="imgExitButton" />
                      
                  <html:image property="imgMenuButton"
                      src="images/icons/mainmenu.gif"
                     value="imgMenuButton"  />
            
                  <html:image property="imgHelpButton"
                      src="images/icons/helpR.gif"
                      value="imgHelpButton" />
            </html:form>
            
            
      </TD>
</TR>
</TABLE>
</BODY>
</html:html>

Please help...
0
Question by:jbaisden
    26 Comments
     
    LVL 8

    Expert Comment

    by:kiranhk
    everything seems to be correct.

    just try taking out the value from the below tags and try it out.

    <html:image property="imgExitButton"
                       src="images/icons/exitdoorR.gif"
                       value="imgExitButton" />
                       
                   <html:image property="imgMenuButton"
                       src="images/icons/mainmenu.gif"
                      value="imgMenuButton"  />

    http://www.jguru.com/faq/view.jsp?EID=893423

    http://technology.amis.nl/blog/index.php?p=139
    0
     
    LVL 8

    Expert Comment

    by:kiranhk
    0
     
    LVL 8

    Expert Comment

    by:kiranhk
    0
     

    Author Comment

    by:jbaisden
    I tried doing this without the value attributes in the html:image tags, but to no avail. I have come across 3 out of the 4. The last of which I am having trouble deciphering per se. Is there any way you could elaborate on what he is saying about the image button bean. I am comparing my MenuForm code with his LogonImageButtonBeanForm and am finding minor differences (he extends ActionForm, I extend ValidatorForm). I may try copying and pasting his code to see if it works any better. Any how, still stuck on this at the moment. Thanks for the quick reply.
    0
     
    LVL 8

    Expert Comment

    by:kiranhk
    did you try changing your set image buttons method in ur form like

         public void setImgMenuButton(Object button) {          
              System.out.println("Inside of setimgMenuButton.");
              if (button instanceof String) return;
                   this.imgMenuButton = (ImageButtonBean) button;
              }
         
              public ImageButtonBean getImgMenuButton()
              {
                   return this.imgMenuButton;
              }
              //public void setImgclearButton(ImageButtonBean button) {
                        //this.imgclearButton = button;
              public void setImgExitButton(Object button) {    
                   System.out.println("Inside of setimgExitButton.");    
                   if (button instanceof String) return;
                        this.imgExitButton = (ImageButtonBean) button;
                   }
              public ImageButtonBean getImgExitButton()
                   {
                        return this.imgExitButton;
                   }

              public void setImgHelpButton(Object button) {          
                   System.out.println("Inside of setimgHelpButton.");
                   if (button instanceof String) return;
                        this.imgHelpButton = (ImageButtonBean) button;
                   }
                   
              public ImageButtonBean getImgHelpButton()
                   {
                        return this.imgHelpButton;
                   }
                       
    0
     

    Author Comment

    by:jbaisden
    I don't see how that is different than the code I already have but I tried copying and pasting it any how. It still is not working. hmm...
    0
     
    LVL 8

    Expert Comment

    by:kiranhk
    ok. r u getting the Sytem.out.println what u r printing. i mean to make sure the methods are getting called or not
    0
     

    Author Comment

    by:jbaisden
    I put System.out.println statements in the sets and gets as well as break points. It seems the get statements are being called, but the set statements aren't. I thought that took place behind the seens (not that I have any documentation that says this, it was just an assumption I had made be it right or wrong).
    0
     

    Author Comment

    by:jbaisden
    Another issue that seems tied to this one (and the answer to this one determines whether I should even pursue this one further) is the matter of having all jsp's go through the same action page (when they click the link that goes to the menu page). I was looking in the struts-config.xml and noticed the setup of the action path, namely the attribute where you list what page is posting the form data, the input attribute. I need more than one page to be able to post its data to the MenuAction. Of course both pages won't post at the same time, but I need the MenuAction to be kicked off by either jsp. Is this even possible? How would I declare this in the struts-config.xml?

    0
     
    LVL 8

    Expert Comment

    by:kiranhk
    basically your input attribute is for redirecting back to the same page whenever there is error in the form data validation. if you give the input attribute then struts will take care of going back to the same page with the errors listed.
    in your case if you dont seem to  have any kind of data validation being done for the requests.
    //                    if (this.imgclearButton.isSelected() || this.imgsearchButton.isSelected())
    //                    {return (new ActionErrors());}
    //                    else {return (super.validate(mapping,request));}


    so this means you can easily put different action mappings in your Struts-config.xml but have the same form/action class for all and also you can have the input attribute different to take the user to different pages
    0
     

    Author Comment

    by:jbaisden
    Another thing of note is that when the code reaches MenuAction, the form that is passed into the Execute method has null values for all 3 of my buttons. I suppose it would make sense that all 3 buttons would remain null after the form was cast to a type of MenuForm; however, this still makes me wonder why is my data not being posted? Why are the buttons always null? Any help would be greatly appreciated.

    0
     

    Author Comment

    by:jbaisden
    As for my validation -- it is being done on the Action side, probably not the way STRUTS intended, but I'm new at this. Validation code was just recently added a few moments ago.
    0
     
    LVL 8

    Expert Comment

    by:kiranhk
    your code seems to be ok.
    did u take out the value attribute from the html:image tag and also have the form methods like i posted. if not test this together. take out the value attribute and replace your methods.

    In your earlier code your setter methods had the method name set appended to the variable name. but struts checks for set appended to the variable name with the first letter in caps like setImgHelpButton() and not setimgHelpButton()
    check this out and see
    0
     
    LVL 8

    Expert Comment

    by:kiranhk
    any luck with your problem
    0
     

    Author Comment

    by:jbaisden

    I have made a good deal of lead way. I am abandoning the ImageButtonBean for the moment, but will come back to it later. I have found a way to detect what button was pressed thanks to mcgrady's code (and your post):

    Enumeration myEnum;

    myEnum = request.getParameterNames();
                                                                
    while(myEnum.hasMoreElements()){
          strButtonSelected = (String)myEnum.nextElement();
          System.out.println("next element is: " + strButtonSelected );
          
    }

    if(strButtonSelected.startsWith("imgMenuButton")) {
     //do something
    ;
    }

    That code seems to work just fine. I am not taking the ImageButtonBean code out, it is just getting bypassed at the moment. There were some other issues with this project, but that would be another thread for the most part. However, one last thing I need to get working (which seems tied in to this topic ) is getting <form:link> tags to post to an Action (MenuAction). They won't submit any useful or needed data, but it would forward control of the web app to the MenuAction so it can do some clean up in between pages. I have an idea on how to do this, but have not tried it yet. I am going to put a hidden field on the form with a dummy value. This should hopefully get the page to post some form data and in turn fire off the Action page. Have you tried anything like this before? Any how, I will keep you informed of my progress. Thanks for your help so far.

    BTW: Using your code for the ImageButtonBean and taking out the value attribute for the <html:image> tags in my form didn't seem to solve the ImageButtonBean problem. I am wondering if this is environment specific because a coworker had the same problem as I am having, but she put the code on our test server and it worked fine. Very odd I say.
    0
     
    LVL 8

    Expert Comment

    by:kiranhk
    I am not clear with your question? what is <form:link> u r telling abt.
    but html:link can call any Action.
    0
     

    Author Comment

    by:jbaisden
    sorry i meant html:link.  Here is my code:

    <html:form action="Menu.do">
         <html:hidden value="1" property="dummyField" />
         <html:link href="ManualInput.jsp" >
          <bean:message key="mm.manualentryhref" />
         </html:link>
         <html:link href="FileUpload.jsp"  >
          <bean:message key="mm.fileuploadhref" />
        </html:link>
    </html:form>

    I want either link to send control to Menu.do and then goto ManualInput.jsp or FileUpload.jsp respectively. Did I make that clear enough this time around? Let me know if you need more information.
    0
     
    LVL 8

    Expert Comment

    by:kiranhk
    For a html link the browser doesnt send any form information. Even if you put a hidden value, a click on a href/html:link will not be able to pass your hidden value. If indeed you want to pass any value you can do so usig the property attribute of the html:link
    If you want to pass only 1 param to  then

    <html:link paramId="articleId" paramName='<bean:write name='printuserlist' property='key'/>' forward="showDetail"><bean:write name='printuserlist' property='key'/></html:link>

    If you want to pass multiple values then you can use this

    that you can do by this

    <%
        java.util.HashMap params = new java.util.HashMap();
          params.put("category",category);
          params.put("keywords",keywords);
          pageContext.setAttribute("paramsName", params);
    %>

    <html:link  name="paramsName" scope="page"  page="/searchItems.do">
         <bean:write name="item" property="attribute4" />
    </html:link>
    0
     
    LVL 8

    Expert Comment

    by:kiranhk
    0
     

    Author Comment

    by:jbaisden
    Does the ParamName have to be a bean? Can it be static text?
    0
     
    LVL 8

    Accepted Solution

    by:
    yes, it can be. just check out the struts link which i sent
    0
     

    Author Comment

    by:jbaisden

    I did check it out but I am having a little trouble parsing through what it is saying. You just said ParamName could be static text. Does that still have to refer to a java bean? And if it does, then the value pulled from the bean is the value submitted with the form under the name given for the paramId attribute, correct? So in the form's action page I would find this parameter under the name of 'myParam' if the link were as follows:

    <html:link paramId="myParam" paramName='<bean:write name='nameOfABean' property='propertyOfABean'/>' </html:link>

    I tried the following:

    <html:link href="ManualInput.jsp" paramId="link1" paramName="ManualInput" >
    and received a [Servlet Error]-[Cannot find bean ManualInput in any scope]: javax.servlet.jsp.JspException: Cannot find bean ManualInput in any scope.

    I have read the documentation you gave, but I am having trouble understanding it. I am more example oriented as you can see from my posts.
    0
     
    LVL 8

    Expert Comment

    by:kiranhk
    download the example code from this. then check out the links section you will be able to understand
    http://www.ninsky.com/struts/
    0
     

    Author Comment

    by:jbaisden

    Thanks for the examples. That got me to where I needed to be. This pretty much concludes my question(s). You have been a grand help kiranhk! Thanks for stayin with it.

    FYI,

    I defined a bean in the jsp and gave that bean the value of the URL for the respective link.

    I did this for each link and had the link's href pointed to my menu action page.

    I will post the code when my computer is done processing some stuff that is eating the CPU. Anyhow, thanks for everything!

    Sincerely,

    Jason
    0
     
    LVL 8

    Expert Comment

    by:kiranhk
    Great!!!! Congrats. You know its always good to hear/see that things get concluded in Good Manner(like they say they lived happily every after!!!! untill the next problem popped up !!!!) especially when u r also part of the team working on it. I was very glad and happy that my comments helped you in solving your problem.

    sure take your time abt the code. someday somebody else might come up with the same problem and they will be able to see this thread and get some help from this like we always do from other threads.

    Kiran
    0
     

    Author Comment

    by:jbaisden
    Alright, here is the code that I used. This came from a number of sources--all of which there are links to on this thread. It was micheal mcgrady's solution (or a part of it) that worked out the best.

    First of all declare your image buttons as ImageButtonBeans in your ActionForm page. Once that has been done, you can declare them using the <html:image...> in the jsp you need them, like so:

    <html:form action="Menu.do" >
         <html:image property="imgExitButton"
                            src="images/icons/exitdoorR.gif"
                          />
       
         <html:image property="imgMenuButton"
                      src="images/icons/mainmenu.gif"
                          />
                
         <html:image property="imgHelpButton"
                  src="images/icons/helpR.gif"
                           />
    </html:form>

    In the Action page the form is being submitted to use the following code:

    Enumeration myEnum;
    myEnum = request.getParameterNames();
                      
    while(myEnum.hasMoreElements()){
          strButtonSelected = (String)myEnum.nextElement();
          System.out.println("next element is: " + strButtonSelected );                        
                      }

    Note that the value stored in strButtonSelected will be: nameOfImageButton + ".y". There will also be a ".x" value as well. The code I used to test to see if my Menu button was pressed is this:

    if(strButtonSelected != null) {
           if(strButtonSelected.startsWith("imgExitButton")) {
                      //Exit button was pressed            
                      request.getSession().invalidate();                        
                                  }
           else {
                      //Help button was pressed
                ;
           }                  
                             
    } // end if(strButtonSelected != null) {

    To remind the reader, the whole reason for doing this is because the code in MenuForm (see above) was not working. When getSelected was called on the form, nonthing was selected--all button properties were null. My coworker had the same experience; however, when we moved it to the test server it worked fine so it may have something to do with the user environment.

    To figure out what hyperlink was selected I used the following code:

    <html:form action="Menu.do">
    <bean:define id="ManualInputLink" value="ManualInput"/>
    <html:link href="Menu.do" paramId="linkClicked" paramName="ManualInputLink" >
          <bean:message key="mm.manualentryhref" />
    </html:link>

    <bean:define id="FileUploadLink" value="FileUpload"/>
    <html:link href="Menu.do" paramId="linkClicked" paramName="FileUploadLink">
          <bean:message key="mm.fileuploadhref" />
    </html:link>
    </html:form>

    This appended '?linkClicked=ManualInput or ?linkClicked=FileUpload to the URL.

    To get the value from the URL I did the folliowing:

          if( request.getParameter("linkClicked") != null )
                strLinkValue = request.getParameter("linkClicked").toString();                  

          if(strLinkValue != null)
                strForward = strLinkValue;

    I had defined forwards for the Menu.jsp page so that I could use

    return (mapping.findForward(strForward));

    to forward the page to where it needed to go.

    That is the gist of it. I hope it helps someone. I have a feeling that what I did above is a bit loopy (I.E. probably not a best practice). This is my first STRUTS web app that I am building by myself for my company so you have to learn somewhere.
    0

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    Course: From Zero to Hero with Nodejs & MongoDB

    Interested in Node.js, but don't know where to start or how to learn it properly? Confused about how the MEAN stack pieces of MongoDB, Expressjs, Angularjs, and Nodejs fit together? Or how it's even possible to run JavaScript outside of the browser?

    Suggested Solutions

    Finding a job can be stressful - searches, resume tweaks, and networking events can be super boring. Luckily we're here to help you land your dream job!
    With the shift in today’s hiring climate (http://blog.experts-exchange.com/ee-blog/5-tips-on-succeeding-in-the-new-gig-economy/?cid=Blog_031816), many companies are choosing to hire freelancers to get projects completed efficiently and inexpensively…
    Need more eyes on your posted question? Go ahead and follow the quick steps in this video to learn how to Request Attention to your question. *Log into your Experts Exchange account *Find the question you want to Request Attention for *Go to the e…
    Internet Business Fax to Email Made Easy - With eFax Corporate (http://www.enterprise.efax.com), you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, fr…

    884 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    17 Experts available now in Live!

    Get 1:1 Help Now