Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enum inside a JSP [duplicate]

Tags:

java

jsp

jstl

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 %>}">...
like image 843
talg Avatar asked Oct 02 '08 16:10

talg


People also ask

Can enum have duplicates?

CA1069: Enums should not have duplicate values.

Can two enum values be the same?

Two enum names can have same value. For example, in the following C program both 'Failed' and 'Freezed' have same value 0.

Can you use == for enums?

Because there is only one instance of each enum constant, it is permissible to use the == operator in place of the equals method when comparing two object references if it is known that at least one of them refers to an enum constant.

Can you inherit enum?

Inheritance Is Not Allowed for Enums.


2 Answers

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.

like image 59
JeeBee Avatar answered Oct 23 '22 16:10

JeeBee


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 reflect here too

like image 29
Mohammed Aslam Avatar answered Oct 23 '22 17:10

Mohammed Aslam