在JSTL中将字符串转换为Title case

10 java string jstl

有没有办法使用JSTL标签将字符串转换为Title case?

提前致谢.

McD*_*ell 15

在服务器上转换字符串的另一种方法是让CSS完成工作:

text-transform: capitalize
Run Code Online (Sandbox Code Playgroud)

  • 在某种程度上,这不是一个非常好的答案"我怎么能在JSTL中做到".我喜欢罗曼塔兹的解释,因为它更好地涵盖了某人如何在JSTL中做到这一点. (3认同)
  • 这仅适用于CSS的某些输入.例如,如果我的输入数据是ALL UPPERCASE,则大写不起作用,它会将我的文本保留为大写格式.EX:有人在所有大写字母中输入姓氏.我想用正确/标题大小写显示这个名字,然后不使用CSS,名称将显示全部大写. (3认同)

Rom*_*las 8

一个主意:

在一个类中,创建一个简单的方法,使用来自Apache Commons Lang的WordUtils来操作你的String:

import org.apache.commons.lang.WordUtils;

...

public static String titleCase(String input){
   return WordUtils.capitalize(input);;
}
Run Code Online (Sandbox Code Playgroud)

现在,创建自己的标记(在function.tld中):

<?xml version="1.0" encoding="UTF-8" ?>
<taglib xmlns="http://java.sun.com/xml/ns/j2ee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd"
  version="2.0">
  <description>functions library</description>
  <display-name>functions</display-name>
  <tlib-version>1.1</tlib-version>
  <short-name>xfn</short-name>
  <uri>http://yourdomain/functions.tld</uri>
  <function>
    <description>
      Title case a String
    </description>
    <name>titleCase</name>
    <function-class>Functions</function-class>
    <function-signature>java.lang.String titleCase(java.lang.String)</function-signature>
    <example>
      ${xfn:titleCase(string)}
    </example>
  </function>
</taglib>
Run Code Online (Sandbox Code Playgroud)

ps:我从这篇文章中得到了很大的启发,给出了答案.


小智 8

在JSTL中它不是太难了......

${fn:toUpperCase(fn:substring(user.firstName, 0, 1))}${fn:toLowerCase(fn:substring(user.firstName, 1, -1))}
Run Code Online (Sandbox Code Playgroud)