How to substring in Struts2?

2019-08-11 01:16发布

问题:

How can I substring a string using Struts2 taglibs?

This is my attempt using JSTL/EL:

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
...
<s:property value="firstName" />
<c:set var="string" value="${firstName} "/>
<c:out value="${fn:substring(string,0,5)} "/>

This does however not work. How can I achieve my requirement?

回答1:

You can reference action properties using JSP EL as ${action.property}.

<c:out value="${fn:substring(action.firstName, 0, 5)} "/>


回答2:

Assuming that firstName is a java.lang.String then:

<s:property value="firstName.substring(0,5)" />


回答3:

The substring function works only on the underlying Java String object and not on the s:set variable we made of it. For example:

Suppose I have a (Action)class which contains a Java variable email. Then I can access this variable in the JSP file like this:

<s:set name="jspEmail" value="%{email}" />

If I want now to substring everything before the @, I have to do this on the Java variable AND NOT on the JSP struts variable. So like this:

<s:set name="namepart" value="%{email.substring(0,email.indexOf("@"))}" />

and then use it like:

<s:property value="%{namepart}"/>