【问题标题】:Prettyfaces URL validationPrettyfaces URL 验证
【发布时间】:2015-05-14 16:41:06
【问题描述】:

如果对象不存在,我想用漂亮的面孔验证我的 url 并获得 HTTP 404。我的 URL 应该类似于 /code/788?date=13.12.2015

我的 Prettyfaces 配置看起来像:

<url-mapping id="code">
    <pattern value="/code/#{/[0-9]+/ code: prettyUrlCheckBean.newCode}" />
    <query-param name="date">#{navigationBean.calendarDateAsString}</query-param>
    <view-id value="/content/codes.jsf"/>
    <action>#{prettyUrlCheckBean.checkEntryUrlWithNewCode}</action>
</url-mapping>

目前,该操作将从 bean 中获取参数,查看代码在给定日期是否存在于数据库中,然后重定向到主页(使用会话中设置的参数)或 404 页面。但是 HTTP 代码将是 302200,而不是直接的 404

我在模式和查询参数中都尝试了验证器,但无论哪种情况,我都无法访问 URL 的其他部分,因此无法验证对象是否存在。

我的 Prettyfaces 版本是 2.0.12.Final。

【问题讨论】:

    标签: jsf prettyfaces


    【解决方案1】:

    我认为执行此类验证的最简单方法是在 action 方法中进行。那里你有你需要的所有信息,并且在验证错误的情况下发送 404 是直截了当的。我总是为此使用一个小的帮助类:

    public class FacesRequests {
    
      public static void sendForbidden() {
        sendStatusCode( 403 );
      }
    
      public static void sendNotFound() {
        sendStatusCode( 404 );
      }
    
      private static void sendStatusCode( int status ) {
    
        FacesContext context = FacesContext.getCurrentInstance();
    
        try {
          HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse();
          response.sendError( status );
          context.responseComplete();
        }
        catch( IOException e ) {
          throw new IllegalStateException( "Could not send error code", e );
        }
    
      }
    
    }
    

    比你基本上可以做这样的事情:

    public String myActionMethod() {
    
      boolean valid = ...;
      if( !valid ) {
        FacesRequests.sendNotFound();
        return null;
      }
    
      // business code here
    
    }
    

    【讨论】:

    • 谢谢!效果很好!返回 null 很重要(如您的示例所示),否则我会收到 java.lang.IllegalStateException: Cannot call sendRedirect() after the response has been commited。
    猜你喜欢
    • 1970-01-01
    • 2012-04-13
    • 2014-07-31
    • 2017-07-29
    • 2011-12-21
    • 2010-09-22
    • 2012-05-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多