(從SpringSource forum)優雅地處理過期的HttpSession中訪問Spring WebFlow
當HttpSession
已經過期,在流動用戶重新提交頁面時,他/她被送回流動的開始。我想添加到此行爲中的所有信息都是解釋其發生的原因的消息。 「你是無效的,所以你已經重新啓動...」
什麼是最簡單/最佳實踐的方式來做到這一點?
(從SpringSource forum)優雅地處理過期的HttpSession中訪問Spring WebFlow
當HttpSession
已經過期,在流動用戶重新提交頁面時,他/她被送回流動的開始。我想添加到此行爲中的所有信息都是解釋其發生的原因的消息。 「你是無效的,所以你已經重新啓動...」
什麼是最簡單/最佳實踐的方式來做到這一點?
FlowHandlerAdapter.defaultHandleException()中的默認行爲是「嘗試啓動已終止或已過期流程的新執行」。
它看起來像一個Webflow的方式來處理,這將是提供一個FlowHandler
一個handleException()方法來檢查的instanceof NoSuchFlowExecutionException
,然後像做構建一個重定向URL或放置在會話範圍的東西,以後可以去掉一次使用。
由於WebFlow使用重定向的方式,我認爲任何其他範圍都不允許稍後在新流視圖呈現時使用此標誌或消息。
但是,僅僅檢測Interceptor
甚至Filter
中的新會話似乎同樣有效。正如我在參考論壇主題中所記錄的那樣,我在之前的調查中最終做了什麼。我只是希望有更漂亮的東西。
此外,到新流程開始時,已創建新的會話ID,因此無法從flow.xml中最初檢測到此情況。
樣品過濾器邏輯:
if (request.getRequestedSessionId() != null && !request.isRequestedSessionIdValid()) {
log.info("Expired Session ID: " + request.getRequestedSessionId());
response.sendRedirect("sessionExpired");
}
else {
chain.doFilter(request, response);
}
樣品攔截:
public class SessionExpiredInterceptor extends HandlerInterceptorAdapter
{
private String redirectLocation = "sessionExpired";
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
Object handler) throws Exception
{
if (request.getRequestedSessionId() != null && !request.isRequestedSessionIdValid())
{
response.sendRedirect(redirectLocation);
return false;
}
return true;
}
public String getRedirectLocation() {
return redirectLocation;
}
public void setRedirectLocation(String redirectLocation) {
this.redirectLocation = redirectLocation;
}
}
步驟1: 流量控制器具有默認的HandlerAdapter。要定製你需要編寫自己的自定義處理程序適配器和流量控制器豆如下進行註冊會議例外:
<bean id="flowController" class="org.springframework.webflow.mvc.servlet.FlowController">
.
.<property name="flowHandlerAdapter" ref="customFlowHandlerAdapter"/>
.
</bean>
<bean id="customFlowHandlerAdapter" class="gov.mo.courts.pbw.adapters.CustomFlowHandlerAdapter"
p:flowExecutor-ref="flowExecutor"/>
第2步: CustomFlowHandlerAdapter 在這個類中重寫defaultHandleException方法。這是Webflow在異常情況下調用並重新初始化會話的方法。請注意,新會議已經創建到現在。此時只有異常類型會告訴您前一個會話超時。
public class PbwFlowHandlerAdapter extends FlowHandlerAdapter{
protected void defaultHandleException(String flowId, FlowException e,
HttpServletRequest request, HttpServletResponse response)
throws IOException {
if(e instanceof NoSuchFlowExecutionException){
if(e.getCause() instanceof NoSuchConversationException){
//"use newly created session object within request object to save your customized message."
}
}
super.defaultHandleException(flowId, e, request, response);
}
您應用的第一個視圖頁面應該能夠顯示此消息。
<%
if (session.getAttribute(YOUR_CUSTOM_MSG_KEY) != null) {
%>
<p class="errormessage">
<%=session.getAttribute(YOUR_CUSTOM_MSG_KEY)%>
</p>
<%
//once the message has been shown, remove it from the session
//as a new session has already been started at this time
session.removeAttribute(YOUR_CUSTOM_MSG_KEY);
}
%>
希望這會有所幫助。