我有一个 Struts2(版本 2.2.3)网络应用程序。我正在尝试将旧链接重定向到新页面。我知道我可以通过
<action name="old-action" class="MVRActionClass">
<result type="redirectAction">
<param name="actionName">new-action</param>
<param name="namespace">/new-action-namespace</param>
<param name="statusCode">301</param>
</result>
</action>
但这会在最终重定向的 url 中添加一个参数 statusCode=301
。我不希望这种情况发生。所以我实现了一些其他方法,但没有成功。
例如在从操作返回之前,我尝试在响应对象中设置 status
-
@Override
public String execute() {
...
((HttpServletResponse) response).setStatus(301);
return SUCCESS;
}
这没有用。我仍然获得链接的 302 状态。然后我创建了一个拦截器并像这样向它添加了一个 PreResultListener -
public class MyInterceptor extends AbstractInterceptor {
@Override
public String intercept(ActionInvocation invocation) throws Exception {
invocation.addPreResultListener(new PreResultListener() {
@Override
public void beforeResult(ActionInvocation invocation, String resultCode) {
try {
ActionContext actionContext = invocation.getInvocationContext();
HttpServletResponse response = (HttpServletResponse).actionContext.get(StrutsStatics.HTTP_RESPONSE);
response.setStatus(301);
actionContext.put(StrutsStatics.HTTP_RESPONSE, response);
} catch(Exception e) {
invocation.setResultCode("error");
}
}
});
// Invocation Continue
return invocation.invoke();
}
}
}
即使这样也行不通。我仍然获得链接的 302 状态。
我还查看了 redirect type=httpheader
。但我不认为这正是我想要的。因为我需要发送 301 以及 redirectedTo 页面的内容,即新链接。
有人提到将 org.apache.struts2.dispatcher.ServletActionRedirectResult
子类化,然后将 statusCode
添加到禁止列表中。但我不知道如何在工作流中注入(inject)这个自定义 RedirectResult
。
感谢任何帮助。
最佳答案
看起来 statusCode
在结果处理期间没有从参数列表中删除。
要使用您自己的 结果类型,只需将其定义为任何其他结果类型并使用它代替 redirectAction
。这在 Result Configuration docs 中进行了讨论。 .您应该能够覆盖 getProhibitedResultParams()
并将 statusCode
添加到列表中。
IMO statusCode 应该在该列表中。有一个 JIRA ticket for this already .
关于java - 在 Struts2 中如何在没有参数出现在 URL 中的情况下进行永久重定向(状态代码 301),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14666370/