Search code examples
javaservletsstruts2

Why Struts 2 doesn't provide easier method for retrieving request parameters?


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.


Solution

  • 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.

    public class Name {
    
      private String firstName;
      private String surname;
    
      public void setFirstName(String s) {
        this.firstName = s;
      }
    
      public void setSurname(String s) {
        this.surname = s;
      }
    
      /* Some interesting operations on Name... */
    
    }
    

    Define your Struts2 action to use Name. The properties of name will be set with HTTP parameters before execute() is called.

    public class NameAction extends Action {
    
      private final Name name = new Name();
    
      public Name getName() {
        return name;
      }
    
      public String execute() {
        /* Use "name" to do something interesting; its properties are set. */
      }
    
    }
    

    Now create a form that uses your action:

    <s:form action="name">
      <s:textfield name="name.firstName" label="First name" />
      <s:textfield name="name.surname" label="Last name" />
      <s:submit/>
    </s:form>
    

    Now the parameters will be set on your Name object when the form is submitted to the NameAction.

    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.