Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
774 views
in Technique[技术] by (71.8m points)

jsp - How to correctly split strings in JSTL?

How can I split strings separated by "/" inside a jsp page using JSTL?

I have a string in this format: **

"23/11/2010"

*. Sometimes, the string could be like this: *

"1/1/2010"

*. I need to do something in order to split the string in three different substrings: *

"23", "11", "2010".

** This is because I need to put each one of them inside three different text fields, like these:

<input type="text" value="23">/
<input type="text" value="11">/
<input type="text" value="2010">

I could not find any working example yet.

Thanks in advance!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use the fn:split() function for this.

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
...
<c:set var="dateParts" value="${fn:split(dateString, '/')}" />
...
<input type="text" name="day" value="${dateParts[0]}" />
<input type="text" name="month" value="${dateParts[1]}" />
<input type="text" name="year" value="${dateParts[2]}" />

Be sure that the date format is validated beforehand :) It would be easier if it was a java.util.Date, not a java.lang.String. You could then use <fmt:formatDate> to format it to a reliable and fixed string format first. Otherwise you'd need to add checks on array length by fn:length() and to prevent potential XSS attack holes by fn:escapeXml().

Also important to note is that the function takes a regular expression as argument and not just a plain character sequence. So in case you'd like to split on characters which represent special characters in regex, then you'd need to escape them with backslashes. See also How to split a string in Java for general guidelines which also apply to fn:split().


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...