I rewrite application from servlets to Struts 2.
Previously to get parameter value I could write:
request.getParameter("name");
Now I should do:
public class MyAction implements ParameterAware {
private Map<String, String[]> parameters;
@Override
public void setParameters(Map<String, String[]> parameters) {
this.parameters = parameters;
}
public String getParameterValue(String name){
return parameters.get(name)[0];
}
// get this parameter
It was much easier when I used servlets!
To make code DRYer I can create class CustomActionSupport extending ActionSupport and put this code there. But why Struts doesn’t do it for me? How can I make my life easier?
I use ParameterAware as documentation says that it’s a preferred way.
The normal use case for Struts2 is to have action properties that correspond to parameters, and let the parameters interceptor set these for you before the action is executed.
Struts2 is trying to hide the fact that your action is invoked as the result of an HTTP request. Trying to work directly with parameters is fighting that paradigm.
Here’s a small example relying on the parameters interceptor. First, define a value object.
Define your Struts2 action to use
Name. The properties of name will be set with HTTP parameters beforeexecute()is called.Now create a form that uses your action:
Now the parameters will be set on your
Nameobject when the form is submitted to theNameAction.You can set up the framework to do a lot more, such as validating parameters, using a IoC container to inject your action with objects, etc.