2010-11-04 18 views
6

Id作爲Url參數傳入。我試圖確保id是一個數字。如果不是重定向到主網頁FacesContext.getCurrentInstance()。getExternalContext()。重定向不立即重定向

if(facilityId != null){ 
    try{ 
     Long.parseLong(facilityId); 
    }catch(NumberFormatException e){ 
     try { 
      FacesContext.getCurrentInstance().getExternalContext().redirect("DisplayList.jsf");      
     } catch (IOException ex) {} 
    } 
    facility = documentSBean.findFacilityById(Long.parseLong(facilityId)); 
    ... 
} 

所以如果我通過在這樣的

www....?facilityId=3?sdfasfda 

一個id我趕上3?sdfasfda不是一個數字,並獲得了重定向語句,但它不重定向正確的方式,它執行接下來的幾條線,試圖將3?sdfasfda轉換爲Long,因此收益率爲NumberFormatException。那麼是否有辦法立即強制重定向,或者有其他方法來解決這個問題。希望在catch之後有一個else:D:D。以上代碼是我@PostConstruct init()方法內

回答

18

是,簡單地從方法return

FacesContext.getCurrentInstance() 
    .getExternalContext().redirect("DisplayList.jsf"); 
return; 

當你調用redirect(..)出現這種情況的唯一的事情是,一個特殊的頭(Location)在響應對象設置。但調用方法的流程仍在繼續,除非您調用重定向後您的return

+0

ai ya。爲什麼我沒有想到這一點。謝謝:D。你知道爲什麼重定向有延遲嗎? – 2010-11-04 22:47:55

+0

當你返回時不會有延遲。 – Bozho 2010-11-04 22:49:36