2

I have a property which is a String in jsp file and I want to display it. If the property's length is longer than 30 chars, I want to show only first 30 chars. I've used the following code:

<s:if test="%{title.length > 25}">
<s:property value="title.substring(0,25)" />
</s:if>
<s:else>
<s:property value="title" />
</s:else>

However, it always shows the title with the full length. I guess the if condition is wrong. How to fix it?

0

2 Answers 2

3

You can do this in several ways but here are two of them

From Java

You can create a function called getTrimmedTitle in your action class like this:

public String getTrimmedTitle(){
    if (testing.length()>25)
        return testing.substring(0,25);
    else return testing;
}

Then in your jsp have only this:

<s:property value="trimmedTitle" />

From JQuery

You can add an id e.g., "title" to the field you want to edit and write a simple function like this:

<script type="text/javascript">
    $(document).ready(function(){
        $("#title").val($("#title").val().substr(1,25));
    });
</script>

That will run every time you load your page.

3
  • Thank you, the solution works for me, but I guess we cannot do it with struts2 tags?
    – lenhhoxung
    Dec 14, 2015 at 13:19
  • I am not 100% sure but I don't think there is such an option. There is no attribute available to restrict length for the s:property tag you use. If you use another tag like s:textfield and set maxLength that won't help either as it restricts further input greater than the maxLength value, it won't trim your String. So maybe its better to control output as shown above, I prefer the first option.
    – jedidog
    Dec 14, 2015 at 13:44
  • @nkal There is such a way, see my answer.
    – Naros
    Dec 14, 2015 at 15:53
2

To do this from a Struts2 Tag:

<s:if test="%{title.length() > 25}">
  <s:property value="title.substring(0, 25)"/>
</s:if>
<s:else>
  <s:property value="title"/>  
</s:else>

or

<s:property value="%{title.length() > 25 ? title.substring(0,25) + '...' : title}"/>
2
  • Nice answer :), but now I prefer the solution with backend code (java) because it allows me to better customize the title, such as adding "..."
    – lenhhoxung
    Dec 14, 2015 at 17:24
  • 1
    @lenhhoxung Can also do that via a property tag if you really wanted as well. It's just merely a matter of taste.
    – Naros
    Dec 14, 2015 at 18:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.