繁体   English   中英

防止直接访问jsf 2中的xhtml文件

[英]Prevent direct access to xhtml files in jsf 2

我想防止直接访问项目中的* .xhtml文件。 在页面中,有commandLinks调用某些bean的某些方法。 这些bean将视图名称作为字符串返回。

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

如果用户将以下内容写入浏览器的地址栏,则我不希望用户看到xhtml文件。

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

要么

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

因为在某些bean中,我填充了这些xhtml视图。 但是,如果用户直接访问xhtml文件,则用户将看到这些视图而没有填写的信息。

当我在web.xml文件中使用时,访问被拒绝。 但是,在这种情况下,当Bean返回值“ campaign.xhtml?faces-redirect = true”时,它也无法显示该视图。 该bean的访问也被拒绝。

我该怎么做才能避免这种情况?

谢谢。

法鲁克·库斯坎(FarukKuşcan)

用户看到这些视图而没有填写信息。

只要检查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>

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

在您的情况下,您需要将一些模式映射到您的xhtml文件,以便通过该模式从URL访问它们,同时将限制对.xhtml扩展名的访问。 因此,在您的web.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";

这样,您将能够通过命令链接将用户重定向到所需的页面,但是当用户键入时

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

要么

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

对URL的访问将被拒绝。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM