Search code examples
javaconfigurationstruts2ognl

How to pass a parameterised method to a Struts 2 action's method attribute?


I'm going to do search data from database using like expression. My method looks like this:

public List<Item> getData(String qString){
   return itemJpa.getSuggestedData(qString);
}

My purpose is when I input a query string to the qString variable, I need to get the data in the list. I'm doing this using Struts2. I need to map this method to the struts action's method attribute. Such as

<action name="DummyDB" class="com.shopping.op.welcome.DummyDB" method="**In Here**"></action> 

Is it possible? If it is how can I do this?


Solution

  • You can't map an action to a method that has parameters in signature, or return result other than String. What can you do is create another method for example doData()

    private List<Item> data;
    //getter and setter
    
    public String doData() {
      data = getData(qString);
      ...
      return Action.SUCCESS;
    }
    
    <action name="DummyDB" class="com.shopping.op.welcome.DummyDB" method="doData">
     <result>/jsp/whateveryoudo.jsp</result>
    </action>
    

    In addition to it you need to know that a class you mapped to the action should be a qualified java bean which have a default no-arg constructor or doesn't have constructors at all (in this case the implicit default constructor is used). Struts will instantiate the bean when you make a request to the action mapped by this action config. So, to get it able to do you should follow these simple rules.