英文:
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:
<c:forEach var="<%=Channels.values()%>" items="channel">
<label>${channel}</label>
</c:forEach>
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("Channels", Channels.values());
In the JSP:
<c:forEach var="${Channels}" items="channel">
<label>${channel}</label>
</c:forEach>
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 -> e.toString()).toArray(String[]::new);
model.addAttribute("Channels" ,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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论