如何在JSTL中正确分割字符串? [英] How to correctly split strings in JSTL?

查看:165
本文介绍了如何在JSTL中正确分割字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用JSTL在jsp页面内拆分用"/"分隔的字符串?

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

我有以下格式的字符串: **

I have a string in this format: **

"2010年11月23日"

"23/11/2010"

* .有时,字符串可能是这样的:*

"2010年1月1日"

"1/1/2010"

* . 为了将字符串分成三个不同的子字符串,我需要做一些事情: *

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

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

"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.

提前谢谢!

推荐答案

您可以使用

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]}" />

确保日期格式事先经过验证:)如果它是java.util.Date而不是java.lang.String,则会更容易.然后,您可以使用 <fmt:formatDate> 首先将其格式化为可靠且固定的字符串格式.否则,您需要通过

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().

还要注意的重要一点是,该函数将正则表达式作为参数,而不仅仅是纯字符序列.因此,如果您想分割表示正则表达式中特殊字符的字符,则需要用反斜杠将其转义.另请参见如何在Java中拆分字符串,以获取有关一般准则的信息应用于fn:split().

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().

这篇关于如何在JSTL中正确分割字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆