开发者

Struts 2 dynamic parameter binding

The default stack has 开发者_StackOverflow社区the parms interceptor who binds the parameters to the setters found in the action who is being invoked. That works fine when you know the name of the parameter. For example if a request parameter is "employee.name" that could be binded to a property of my action which has a property "employee" with a property "name". In order to get it to work I need to know which name the request parameter name would be and put a setter in my action called setEmployee() of an object type Employee or it could be a Map too.

What if I want to let the action bind that param to another property that I don't know which one will be. Let's say that the action receive as a parameter the name on which the request parameter will be set.

<s:action name="showEmployee" executeResult="true">
   <s:param name="employeePrefix">xyz.wz.empl</s:param>
</s:action>

That would mean to the action to bind all the parameters of the employee to xyz.wz.empl. For example let's say the request parameter has the following: xyz.wz.empl.name=Alfredo xyz.wz.empl.lastName=Osorio

I would like to bind that to a property of my action, let's say a Map employee, but that won't work because the request parameter is xyz.wz.empl. How can I bind that dynamic parameter to the invoked action using the parameter that was sent to the action (employeePrefix).

I could ask for the request parameters

ActionContext.getContext().getParameters()

and do the conversion myself but I think there must be another way to explicitly call something from the Struts 2 framework to the conversion, in the way that com.opensymphony.xwork2.interceptor.ParametersInterceptor does.

Thank You.


This is not an ideal solution in my opinion but it will do what you need.

  1. Your Struts 2 Action will need to implement SessionAware and ParameterAware interfaces.
  2. Create a private field that is a map called 'parameters' and create a getter/setter for it.
  3. Now when you call getParameters() you will have a map of your name/value pairs.

Now for this next portion you will need to use reflection.

So for example you will need to do this:

Map myParams = getParameters()
Employee e = new Employee()

Class clas = null;
try {
    clas = Class.forName("Employee");
    Field fieldlist[] = clas.getDeclaredFields();
    for (int i = 0; i < fieldlist.length; i++) {
        Field fld = fieldlist[i];
        if(myParams.containsKey(fld.getName()))
            fld.set(e, myParams.get(fld.getName())
    }

} catch (ClassNotFoundException ex) {
// handle exception case
}

This should map all parameters in that map to a field in the employee object if it exists in the map. This can be of course ported out to a separate method that would belong in something like a Util class where you pass in the class you want to reflect on.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜