Java JSP 中的枚举

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/163407/
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-08-11 09:57:54  来源:igfitidea点击:

Enum inside a JSP

javajspjstl

提问by talg

Is there a way to use Enum values inside a JSP without using scriptlets.

有没有办法在不使用 scriptlet 的情况下在 JSP 中使用枚举值。

e.g.

例如

package com.example;

public enum Direction {
    ASC,
    DESC
}

so in the JSP I want to do something like this

所以在 JSP 中我想做这样的事情

<c:if test="${foo.direction ==<% com.example.Direction.ASC %>}">...

采纳答案by JeeBee

You could implement the web-friendly text for a direction within the enum as a field:

您可以将枚举中的方向的 Web 友好文本实现为字段:


<%@ page import="com.example.Direction" %>
...
<p>Direction is <%=foo.direction.getFriendlyName()%></p>
<% if (foo.direction == Direction.ASC) { %>
<p>That means you're going to heaven!</p>
<% } %>

but that mixes the view and the model, although for simple uses it can be view-independent ("Ascending", "Descending", etc).

但这混合了视图和模型,尽管对于简单的使用,它可以独立于视图(“升序”、“降序”等)。

Unless you don't like putting straight Java into your JSP pages, even when used for basic things like comparisons.

除非您不喜欢将 Java 直接放入 JSP 页面,即使用于比较等基本内容也是如此。

回答by Arnoud

You can simply check against the enum value as a string:

您可以简单地将枚举值作为字符串进行检查:

<c:if test="${foo.direction == 'ASC'}">...

回答by Mohammed Aslam

It can be done like this I guess

我想它可以像这样完成

<c:set var="ASC" value="<%=Direction.ASC%>"/>
<c:if test="${foo.direction == ASC}"></c:if>

the advantage is when we refactor it will rename here too

优点是当我们重构时它也会在这里重命名