Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/340.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 无法使用#strings.substring显示部分文本_Java_Spring_Spring Boot_Thymeleaf - Fatal编程技术网

Java 无法使用#strings.substring显示部分文本

Java 无法使用#strings.substring显示部分文本,java,spring,spring-boot,thymeleaf,Java,Spring,Spring Boot,Thymeleaf,我将Spring Boot与Thymeleaf一起使用,并将post对象传递给视图解析器。我只想显示post.content字段的某一部分,意思如下 example: This is the column from the database. ____ --------------- content column --------------- text text text t ext text text --------------- 因此,我只想在.html页面中显示一定数量的字符,如下

我将Spring Boot与Thymeleaf一起使用,并将post对象传递给视图解析器。我只想显示post.content字段的某一部分,意思如下

example:
This is the column from the database.
____
---------------
 content column
---------------
text text text t
ext text text
---------------
因此,我只想在.html页面中显示一定数量的字符,如下所示:

Your text: text text te... 'read more' 
我试过了

<p id="postcontent" th:utext="${#strings.substring(${post.content},0,12)}"></p>
现在的问题是,如果字符串小于所需的长度,我会得到一个

原因:java.lang.StringIndexOutOfBoundsException:字符串索引输出 射程:17


有办法解决这个问题吗?假设这种情况永远不会发生,因为不会有长度如此短的帖子内容,但我想有一种方法来管理此异常。

要理解错误,您必须知道字符串是什么

java中的字符串是字符数组:

char[] example = {'H', 'E', 'L', 'L', 'O');
您可以以类似于why to数组的方式操作字符串。数组的第一个索引为0,最大索引长度为-1

现在假设上面的示例是String的一个实例,您可以:

example.subString (0, 3) // Return value would be "HEL". 

example.subString (0, 10) // StringIndexOutOfBoundsException
为了防止这种情况发生,你必须使用先到的方法。您的上限为17或由字符串长度定义的上限

example.subString (0, Math.min(17, example.length()));
虽然Thymeleaf中没有内置函数,但您可以使用特殊的T(…)操作符来调用静态方法(允许您在Thymeleaf中使用Java的Math.max(…)



如评论中所述,有一种更为特殊的方法来实现您的目标:


请编辑更新您的问题,并提供您从thymeleaf收到的错误。@Marcinek您好,我已经进行了修改并找到了正确的语法,但现在我遇到了另一个问题。您是否正在寻找:@Marcinek不完全,我想知道是否有办法用thymeleaf在前端解决这个问题。检查字符串的长度。@helloApp也许缩写()比子字符串()更有效?@Alexandre Levieux和Marcinek谢谢!缩写正是我所需要的,无论字符串有多长,它都能完美地工作!
example.subString (0, 3) // Return value would be "HEL". 

example.subString (0, 10) // StringIndexOutOfBoundsException
example.subString (0, Math.min(17, example.length()));
<div th:with="maxNumber=${T(Math).min(8,12)}">
   <p th:text=${maxNumber}></p>
</div>