2012-10-31 50 views
0

我想阻止直接訪問我的項目中的* .xhtml文件。在頁面中,有一些調用一些bean的某些方法的commandLinks。這些bean以字符串的形式返回視圖的名稱。防止直接訪問jsf 2中的xhtml文件

return "campaign.xhtml?faces-redirect=true"; 

如果用戶向瀏覽器的地址欄寫入以下內容,我不希望用戶看到xhtml文件。

http://localhost:8080/myApp/faces/campaign.xhtml 

http://localhost:8080/myApp/faces/campaign.xhtml?faces-redirect=true 

,因爲在某些豆類,我填補這些XHTML意見。但是,如果用戶直接訪問xhtml文件,用戶將看到這些視圖,而沒有填充的信息。

當我在web.xml文件中使用時,訪問被拒絕。但是,在這種情況下,當bean返回值「campaign.xhtml?faces-redirect = true」時,它也不能顯示視圖。該訪問也被拒絕。

我能做些什麼來防止這種情況發生?

謝謝。

法魯克Kuşcan

回答

5

用戶看到沒有填寫這些信息的意見。

只要檢查preRenderView事件偵聽器是否填充信息。如果沒有,重新導向回來。

<f:event type="preRenderView" listener="#{bean.init}" /> 

public void init() throws IOException { 
    if (information == null) { 
     ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext(); 
     externalContext.redirect(externalContext.getRequestContextPath() + "/otherpage.xhtml"); 
    } 
} 

您,如有必要,如果你居然還使用<f:viewParam>與驗證與FacesContext#isValidationFailed()結合起來。例如。

<f:viewParam name="id" value="#{bean.information}" required="true" /> 
<f:event type="preRenderView" listener="#{bean.init}" /> 

public void init() throws IOException { 
    FacesContext context = FacesContext.getCurrentInstance(); 
    if (context.isValidationFailed()) { 
     ExternalContext externalContext = context.getExternalContext(); 
     externalContext.redirect(externalContext.getRequestContextPath() + "/otherpage.xhtml"); 
    } 
} 

更新:在JSF 2.2,你可以使用<f:viewAction>這一點。

<f:viewAction listener="#{bean.check}" /> 
public String check() { 
    if (information == null) { 
     return "otherpage?faces-redirect=true"; 
    } else { 
     return null; 
    } 
} 
-1

你的情況,你需要某種模式映射到你的XHTML文件,以通過該模式從URL訪問它們,而在同一時間訪問.xhtml擴展將受到限制。所以在你的網站。XML:

<servlet> 
    <servlet-name>Faces Servlet</servlet-name> 
    <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>   
    <load-on-startup>1</load-on-startup> 
</servlet> 

    <servlet-mapping> 
     <servlet-name>Faces Servlet</servlet-name> 
     <url-pattern>*.someExtension</url-pattern> 
    </servlet-mapping> 

    <security-constraint> 
    <display-name>Restrict access to XHTML Documents</display-name> 
    <web-resource-collection> 
     <web-resource-name>XHTML</web-resource-name> 
     <url-pattern>*.xhtml</url-pattern> 
    </web-resource-collection> 
    <auth-constraint/> 
    </security-constraint> 

這是你的bean應該返回什麼:

return "campaign.someExtension?faces-redirect=true"; 

這樣,您就可以將您重定向通過commandLinks希望用戶對頁面,但是當用戶鍵入

http://localhost:8080/myApp/faces/campaign.xhtml 

http://localhost:8080/myApp/faces/campaign.xhtml?faces-redirect=true 

到URL的訪問將被拒絕。

+0

我非常強烈地認爲這不是問題。否則,BalusC會將其標記爲重複項,並且沒有給出他所做的答案。 – Kukeltje