Struts 2에서 동적 URL 리디렉션을 수행하는 방법은 무엇입니까?
문제
내 struts2 앱을 생성 URL로 리디렉션하려고합니다. 이 경우 URL이 현재 날짜 또는 데이터베이스에서 찾은 날짜를 사용하기를 원합니다. 그래서 /section/document
becomes /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
그리고 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();
}
편집 : 누락 된 견적을 추가했습니다.
나는 subclassing struts를 끝냈다 ' ServletRedirectResult
그리고 그것을 우선합니다 doExecute()
전화하기 전에 내 논리를 수행하는 방법 super.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";
}