【问题标题】:<h:outputText> how to display content with fixed length?<h:outputText> 如何显示固定长度的内容?
【发布时间】:2011-12-13 10:55:51
【问题描述】:

我有一个这样的字符串:

<p><strong>Make sure you’re paying the right price for your household and trade services with pricing calculators from Australia’s largest online services marketplace, ServiceSeeking.com.au </strong></p>. 

我想用&lt;h:outputText escape="false"&gt; 显示这个字符串的一部分(只是内容,没有HTML 标记)。我试过substring(),但我不知道html标签在哪里结束,所以我的表格坏了。我只想得到大约 100 个字符。我该怎么做?

【问题讨论】:

    标签: java html jsf-2


    【解决方案1】:

    我不确定我是否 100% 正确理解了您的问题,但如果您要显示的所有字符串都大致采用您示例中的格式,那么您可以在没有 html 的情况下显示它们,并以这种方式缩短为 100 个字符:

    <h:outputText value="#{textExtractorBean.extractedText}"/>
    

    这是豆子:

    class TextExtractorBean{
    ...
      getExtractedText(){
        Pattern pattern = Pattern.compile("<([a-z])+>");
        Matcher matcher = pattern.matcher(text);
    
        int firstIdxAfterOpeningTags = 0;
        while(matcher.find()){
            firstIdxAfterOpeningTags = matcher.end();
        }
    
        pattern = Pattern.compile("</([a-z])+>");
        matcher = pattern.matcher(text);
    
        int firstIdxBeforeClosingTags = text.length();
        if(matcher.find()){
            firstIdxBeforeClosingTags = matcher.start();
        }
    
        String extractedText = text.substring(firstIdxAfterOpeningTags,
                firstIdxBeforeClosingTags);
        String shortenedText = extractedText.length() > 0 ? extractedText
                .substring(0,100) : extractedText;
        return shortenedText;
      }
    ...
    }
    

    其中 text 变量包含您的示例中的字符串。

    【讨论】:

      【解决方案2】:

      您可以使用以下 JSF HTML 标记输出文本:

      <h:outputText escape="false" value="Your content here"  />
      

      【讨论】:

        猜你喜欢
        • 2022-01-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-04-08
        • 1970-01-01
        • 2022-01-09
        • 1970-01-01
        相关资源
        最近更新 更多