Enum inside a JSP [duplicate]

孤人 提交于 2019-12-20 11:53:04

问题


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

e.g.

package com.example;

public enum Direction {
    ASC,
    DESC
}

so in the JSP I want to do something like this

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

回答1:


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


<%@ 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.




回答2:


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




回答3:


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

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


来源:https://stackoverflow.com/questions/163407/enum-inside-a-jsp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!