gpt4 book ai didi

java - 使用 JSTL 编写静态内容

转载 作者:行者123 更新时间:2023-11-29 03:43:37 25 4
gpt4 key购买 nike

正在编写一个程序并尝试从另一个类中打印一个静态整数。奇怪的是我可以用 scriptlet 做到这一点,但不能用 JSTL。查看我刚刚编写的错误检查代码。

Comments: <%=Comments.getCommentCount() %> <br />
Comments: ${Comments.getCommentCount()} <br />
Comments: <c:out value="${Comments.getCommentCount()}" /> <br />
Comments: <c:out value="1" />

这给了我一个 HTML 输出

Comments: 5 <br />
Comments: <br />
Comments: <br />
Comments: 1

如您所见,只有第一行和最后一行代码有效。如何在没有 scriptlet 的情况下打印出这个静态变量?

在我的标题中有

import="org.test.Comments"

评论.java

package org.test;

import java.util.ArrayList;
import java.util.Collections;

public class Comments
{
private String name = "";
private String comment = "";
private static ArrayList<String> allComments = new ArrayList<String>();


public void setNewComment(String name, String comment)
{
this.name = name;
this.comment = comment;
allComments.add(getComment());
}

public static ArrayList<String> getCommentList()
{
Collections.reverse(allComments);
return allComments;
}


public static int getCommentCount()
{
return allComments.size();
}


public String getComment()
{
return String.format("Name: %s <br />Comment: %s <p><hr /></p>", name, comment);
}
}

最佳答案

你不需要在 jSTL 中调用 getter。就这样做

<c:out value="${Comments.commentCount}" /> 

假设您的变量名称是 commentCount而不是 CommentCount .

即使没有 <c:out> 也能正常工作

Comments: ${Comments.commentCount} <br />

但使用 <c:out>会更好,以避免跨站点脚本,如 here 所述

更新

在您提到的类中,没有名为 commentCount 的字段。所以这是行不通的。您可以使用 jsp fn 标签直接在 jsp 中获取集合的大小。

在标题中包含这个

  <%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>

然后这样做:

  <c:out value="${fn:length(allComments)}" /> 

 Comments: ${fn:length(allComments)} <br />

这应该有效。

关于java - 使用 JSTL 编写静态内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12047672/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com