Roman C Roman C - 1 year ago 53
Java Question

Can I map an action method that returns Object in Struts 2

I've used Struts2 to map actions to the methods that return

String
. Can I use other types? What types are possible to use?

I found that code using a REST plugin

// Handles /orders/{id} GET requests
public HttpHeaders show() {
model = orderManager.findOrder(id);
return new DefaultHttpHeaders("show")
.withETag(model.getUniqueStamp())
.lastModified(model.getLastModified());
}


It shows that it maps to method
show
that returns
HttpHeaders
. And it's not a
String
. How it works?

Answer Source

The framework has features that allows to return not only String. You can return an instance of the Result directly from the action method instead of a String. For example

public Result method() {
  //todo implementation is here  
}

If needed to return multiple types you can set return type as Object.

public Object method() {
    Object resultCode = "success";
    if (something) {
        resultCode = new StrutsResultSupport();
    }
    return resultCode ;
}

About the rest method HttpHeaders is a interface that doesn't extend Result, so it shouldn't be used as a result type.


to be continued