Struts 2で動的URLリダイレクトを行う方法は?
質問
Struts2アプリで生成されたURLにリダイレクトしようとしています。この場合、URLに現在の日付、またはデータベースで検索した日付を使用する必要があります。したがって、 / section / document
は / section / document / 2008-10-06
これを行う最良の方法は何ですか?
解決
次のようにします:
Struts.xmlで、次のような動的な結果が得られます。
<result name="redirect" type="redirect">${url}</result>
アクション内:
private String url;
public String getUrl()
{
return url;
}
public String execute()
{
[other stuff to setup your date]
url = "/section/document" + date;
return "redirect";
}
実際にこの同じテクノロジーを使用して、OGNLを使用してstruts.xmlの変数に動的な値を設定できます。 RESTfulリンクなどを含む、あらゆる種類の動的な結果を作成しました。クールなもの。
他のヒント
annotations
とConventionプラグインを使用して、struts.xmlでの構成の繰り返しを回避することもできます。
@Result(location="${url}", type="redirect")
$ {url}は、「getUrlメソッドの値を使用する」という意味です
ActionClass
で直接リダイレクトしたい場合:
public class RedirecActionExample extends ActionSupport {
HttpServletResponse response=(HttpServletResponse) ActionContext.getContext().get(ServletActionContext.HTTP_RESPONSE);
url="http://localhost:8080/SpRoom-1.0-SNAPSHOT/"+date;
response.sendRedirect(url);
return super.execute();
}
編集:欠落している引用を追加しました。
Strutsの ServletRedirectResult
をサブクラス化し、 super.doExecute()
を呼び出す前にロジックを実行する doExecute()
メソッドをオーバーライドしました。次のようになります:
public class AppendRedirectionResult extends ServletRedirectResult {
private DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
@Override
protected void doExecute(String finalLocation, ActionInvocation invocation) throws Exception {
String date = df.format(new Date());
String loc = "/section/document/"+date;
super.doExecute(loc, invocation);
}
}
これが最善の方法かどうかわかりませんが、機能します。
注釈を使用して別のアクションにリダイレクトできます-
@Result(
name = "resultName",
type = "redirectAction",
params = { "actionName", "XYZAction" }
)
どのアクションが関係しているかに関係なく、インターセプターから直接リダイレクトできます。
struts.xmlで
<global-results>
<result name="redir" type="redirect">${#request.redirUrl}</result>
</global-results>
インターセプター内
@Override
public String intercept(ActionInvocation ai) throws Exception
{
final ActionContext context = ai.getInvocationContext();
HttpServletRequest request = (HttpServletRequest)context.get(StrutsStatics.HTTP_REQUEST);
request.setAttribute("redirUrl", "http://the.new.target.org");
return "redir";
}
所属していません StackOverflow