java 在 JSTL 中将字符串转换为标题大小写

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/482925/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 12:35:43  来源:igfitidea点击:

converting strings to Title case in JSTL

javastringjstl

提问by McDowell

Is there any way to convert a string to Title case, using JSTL tags?

有没有办法使用 JSTL 标签将字符串转换为标题大小写?

Thanks in Advance.

提前致谢。

回答by McDowell

An alternative to transforming the string on the server is to let CSS do the work:

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

text-transform: capitalize

回答by Romain Linsolas

An idea:

一个想法:

In a class, create a simple method that uses the WordUtils from Apache Commons Lang that will manipulate your String:

在一个类中,创建一个简单的方法,该方法使用来自 Apache Commons Lang 的 WordUtils 来操作您的字符串:

import org.apache.commons.lang.WordUtils;

...

public static String titleCase(String input){
   return WordUtils.capitalize(input);;
}

And now, create your own tag (in a function.tld) :

现在,创建您自己的标签(在 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>

ps: I was quite inspired from this postto give my answer.

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

回答by jonnad

It's not too super hard in JSTL...

在 JSTL 中并不太难...

${fn:toUpperCase(fn:substring(user.firstName, 0, 1))}${fn:toLowerCase(fn:substring(user.firstName, 1, -1))}