通过循环遍历 JSP 访问 ENUM 值

huangapple go评论71阅读模式
英文:

Accessing ENUM Values via a Loop Through a JSP

问题

我有一个枚举,内容如下:

public enum Channels{
CHANNEL1,
CHANNEL2,
CHANNEL3,
CHANNEL4
}

我想通过 JSP 访问这些值,并为每个值显示一个标签。为此,我创建了以下循环:

<c:forEach var="${Channels.values()}" items="channel">
    <label>${channel}</label>
</c:forEach>

每当我运行 JSP 时,它会报错,并且这些值不会被显示。

我还尝试将这些值作为模型属性传递,如下所示:

在控制器中:

model.addAttribute("Channels", Channels.values());

在 JSP 中:

<c:forEach var="${Channels}" items="channel">
    <label>${channel}</label>
</c:forEach>

当我尝试这样做时,加载包含此内容的模态框的 ajax 调用会导致 500 内部服务器错误。

请告诉我如何解决这个问题。

提前感谢!

英文:

I have an enum that would go as follows;

public enum Channels{
CHANNEL1,
CHANNEL2,
CHANNEL3,
CHANNEL4
}

I want to access these values through a JSP and display a label for each. For this purpose, I have created the following loop:

&lt;c:forEach var=&quot;&lt;%=Channels.values()%&gt;&quot; items=&quot;channel&quot;&gt;
    &lt;label&gt;${channel}&lt;/label&gt;
&lt;/c:forEach&gt;

Whenever I run my JSP, it gives me an error and these values do not get displayed.

I also tried passing the values as model attributes as follows:

In the controller:

model.addAttribute(&quot;Channels&quot;, Channels.values());

In the JSP:

&lt;c:forEach var=&quot;${Channels}&quot; items=&quot;channel&quot;&gt;
    &lt;label&gt;${channel}&lt;/label&gt;
&lt;/c:forEach&gt;

The ajax call to load the modal that contains this gives a 500 Internal Server Error whenever I try to do this.

Please let me know how I can fix this issue.

Thanks in advance!

答案1

得分: 1

我找到了解决方案,如下所示:

在我的控制器中,我设置了一个属性,将ENUM的值作为字符串数组传递。

String Channels[] = Arrays.stream(ProductKdsChannels.values()).map(e -> e.toString()).toArray(String[]::new);
model.addAttribute("Channels", Channels);

在JSP中,像往常一样访问这个属性,${Channels}

提示: 确保将方括号[]放在变量名旁边,而不是数据类型。String[] Channels 对我不起作用。

英文:

I found the solution for this as follows;

In my controller, I set an attribute to pass the values of the ENUM as a string Array.

String Channels[] = Arrays.stream(ProductKdsChannels.values()).map(e -&gt; e.toString()).toArray(String[]::new);
model.addAttribute(&quot;Channels&quot; ,Channels);

In the JSP, access the attribute as usual, ${Channels}

Tip: Make sure you put the box brackets [] near the variable name and not the data type. String[] Channels did not work for me.

huangapple
  • 本文由 发表于 2020年10月20日 13:27:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/64438976.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定