Here's the thing, I need to not only serve java, but also some javascript files, with my .war. So e,g. if someone goes to the URL:
example.com/js/foo.jar
Then I need that to be properly served as a javascript file. At the same time, if someone goes to:
example.com/bar
I need that to be served by Struts2 as a possible controller.
The methods I've found online of removing the suffix from the url, would cause both URls to be served by struts 2 (and hence give an error for the first foo.js
file even though it exists). Is there a way (such as an interceptor) which will first check if the given .js file exists, before giving an error?
DarkHorse's answer is not entirely accurate. There are two values that are very similar but work very differently:
<constant name="struts.action.extension" value=","/>
<constant name="struts.action.extension" value=""/>
You almost certainly want the first option, which includes a comma. This tells Struts that the action extension is empty. It also means that Struts will not attempt to match any requests that do have an extension, such as *.css, *.js, etc.
The second option tells Struts that there shouldn't be an action extension, but it also says that you want Struts to match every request. The only possible benefit I can think of to this is if you wanted to include file extensions in your action mapping, such as the following:
<action name="robots.txt" class="...">
...
</action>
Also, to exclude requests from the Struts filter is to use the struts.action.excludePattern
property, as described here. Do not rely on an interceptor for this, since interceptors only run once the framework has located a suitable action to map to.
To have URL's without suffix... all you need to do is.. set this in your struts.xml file
<constant name="struts.action.extension" value=""/>
If you want some url's not to served by struts action... write an interceptor where you check the url's suffix.. if it has any redirect them else where thus avoiding your struts actions completely..
EX:
public class RestrictUrl extends AbstractInterceptor implements SessionAware {
Map<String, Object> session;
@Override
public String intercept(ActionInvocation invocation) throws Exception {
HttpServletRequest request = (HttpServletRequest) invocation.getInvocationContext().get(StrutsStatics.HTTP_REQUEST);
HttpServletResponse response = (HttpServletResponse) invocation.getInvocationContext().get(StrutsStatics.HTTP_RESPONSE);
String url = request.getHeader("referer"); // Your url
if(check something in url) {
response.sendRedirect(where you want to go);
}
return invocation.invoke();
}
}
来源:https://stackoverflow.com/questions/19068102/how-to-have-urls-without-a-suffix-e-g-action-in-struts-2