How to change default JSP/template location with S

2019-01-20 01:39发布

问题:

I'm working on a new Java EE application that uses Struts2 in Eclipse. I want to keep the JSP files in the source folder (src/main/jsp) and not in WebContent. When deployed, the all source files get copied over to WebContent/WEB-INF/classes. This also has the bonus effect of making the jsp files inaccessible directly (I want everything to require action intervention). This means that to make results display, I have to do this:

<result name="SUCCESS">WEB-INF/classes/index.jsp</result>

Is it possible to set the default location of the jsp files so that just index.jsp is sufficient to reference them? Ideally the files would also sit in WEB-INF/jsp and not get mixed with the classes.

I saw that spring has this feature. I'm hoping for the same thing for Struts2.

回答1:

You can create a constant configuration parameter, e.g.

<constant name="struts.result.path" value="/WEB-INF/classes" />

Then inject this constant into custom dispatcher result. Add this to your default package:

<result-types>
    <result-type name="dispatcher" default="true" class="struts.results.MyServletDispatcherResult" />
</result-types>

The implementation is easy, you just add a prefix to the location of the result when it's configured.

public class MyServletDispatcherResult extends ServletDispatcherResult {

    private String resultPath;

    public String getResultPath() {
        return resultPath;
    }

    @Inject(value = "struts.result.path", required = false)
    public void setResultPath(String resultPath) {
        this.resultPath = resultPath;
    }

    @Override
    public void setLocation(String location) {
        super.setLocation(resultPath+location);
    }

    public MyServletDispatcherResult() {
        super();
    }

//    @Inject
//    public MyServletDispatcherResult(String location) {
//
//        super(resultPath+location);
//    }
}

Then you can use ordinary locations in the results, e.g.

<result name="SUCCESS">/index.jsp</result>