JSTL과 함께 EL을 사용하여 Enum 값에 액세스
다음과 같이 정의 된 Status라는 Enum이 있습니다.
public enum Status {
VALID("valid"), OLD("old");
private final String val;
Status(String val) {
this.val = val;
}
public String getStatus() {
return val;
}
}
VALIDJSTL 태그 의 값에 액세스하고 싶습니다 . 특히 태그 의 test속성입니다 <c:when>. 예
<c:when test="${dp.status eq Status.VALID">
이것이 가능한지 잘 모르겠습니다.
문자열에 대한 간단한 비교가 작동합니다.
<c:when test="${someModel.status == 'OLD'}">
Spring MVC를 사용하는 경우 Spring Expression Language (SpEL)가 도움이 될 수 있습니다.
<spring:eval expression="dp.status == T(com.example.Status).VALID" var="isValid" />
<c:if test="${isValid}">
isValid
</c:if>
여기에 3 가지 선택 항목이 있으며 그중 어느 것도 완벽하지 않습니다.
test속성 에서 스크립틀릿을 사용할 수 있습니다 .<c:when test="<%= dp.getStatus() == Status.VALID %>">이것은 열거 형을 사용하지만 JSP 2.0에서 "올바른 방법"이 아닌 스크립틀릿도 사용합니다. 그러나 가장 중요한 것은를
when사용 하여 동일한 조건에 다른 조건을 추가하려는 경우 작동하지 않는다는 것${}입니다. 그리고 이것은 테스트하려는 모든 변수가 스크립틀릿에 선언되거나 요청 또는 세션에 유지되어야 함을 의미합니다 (pageContext변수는.tag파일 에서 사용할 수 없음 ).문자열과 비교할 수 있습니다.
<c:when test="${dp.status == 'VALID'}">깔끔해 보이지만 열거 형 값을 복제하고 컴파일러에서 유효성을 검사 할 수없는 문자열을 도입했습니다. 따라서 열거 형에서 해당 값을 제거하거나 이름을 바꾸면이 코드 부분에 더 이상 액세스 할 수 없음을 알 수 없습니다. 기본적으로 매번 코드를 검색 / 바꾸어야합니다.
사용하는 각 열거 형 값을 페이지 컨텍스트에 추가 할 수 있습니다.
<c:set var="VALID" value="<%=Status.VALID%>"/>그런 다음 이렇게 할 수 있습니다.
<c:when test="${dp.status == VALID}">
스크립틀릿도 사용하지만 마지막 옵션 (3)을 선호합니다. 값을 설정할 때만 사용하기 때문입니다. 나중에 다른 EL 조건과 함께 더 복잡한 EL 표현식에서 사용할 수 있습니다. 옵션 (1) test에서는 단일 when태그 의 속성에 스크립틀릿과 EL 표현식을 사용할 수 없습니다 .
따라서 내 문제를 완전히 해결하려면 다음을 수행해야했습니다.
<% pageContext.setAttribute("old", Status.OLD); %>
그런 다음 할 수있었습니다.
<c:when test="${someModel.status == old}"/>...</c:when>
예상대로 작동했습니다.
두 가지 가능성이 더 있습니다.
JSP EL 3.0 상수
버전 3.0 이상의 EL을 사용하는 한 다음과 같이 페이지로 상수를 가져올 수 있습니다.
<%@ page import="org.example.Status" %>
<c:when test="${dp.status eq Status.VALID}">
그러나 일부 IDE는 아직이를 이해하지 못 하므로 (예 : IntelliJ ) 런타임까지 오타를 입력해도 경고가 표시되지 않습니다.
적절한 IDE 지원을 받으면 이것이 제가 선호하는 방법입니다.
Helper Methods
You could just add getters to your enum.
public enum Status {
VALID("valid"), OLD("old");
private final String val;
Status(String val) {
this.val = val;
}
public String getStatus() {
return val;
}
public boolean isValid() {
return this == VALID;
}
public boolean isOld() {
return this == OLD;
}
}
Then in your JSP:
<c:when test="${dp.status.valid}">
This is supported in all IDEs and will also work if you can't use EL 3.0 yet. This is what I do at the moment because it keeps all the logic wrapped up into my enum.
Also be careful if it is possible for the variable storing the enum to be null. You would need to check for that first if your code doesn't guarantee that it is not null:
<c:when test="${not empty db.status and dp.status.valid}">
I think this method is superior to those where you set an intermediary value in the JSP because you have to do that on each page where you need to use the enum. However, with this solution you only need to declare the getter once.
For this purposes I do the following:
<c:set var="abc">
<%=Status.OLD.getStatus()%>
</c:set>
<c:if test="${someVariable == abc}">
....
</c:if>
It's looks ugly, but works!
I do not have an answer to the question of Kornel, but I've a remark about the other script examples. Most of the expression trust implicitly on the toString(), but the Enum.valueOf() expects a value that comes from/matches the Enum.name() property. So one should use e.g.:
<% pageContext.setAttribute("Status_OLD", Status.OLD.name()); %>
...
<c:when test="${someModel.status == Status_OLD}"/>...</c:when>
Add a method to the enum like:
public String getString() {
return this.name();
}
For example
public enum MyEnum {
VALUE_1,
VALUE_2;
public String getString() {
return this.name();
}
}
Then you can use:
<c:if test="${myObject.myEnumProperty.string eq 'VALUE_2'}">...</c:if>
When using a MVC framework I put the following in my controller.
request.setAttribute(RequestParameterNamesEnum.INBOX_ACTION.name(), RequestParameterNamesEnum.INBOX_ACTION.name());
This allows me to use the following in my JSP Page.
<script> var url = 'http://www.nowhere.com/?${INBOX_ACTION}=' + someValue;</script>
It can also be used in your comparison
<c:when test="${someModel.action == INBOX_ACTION}">
Which I prefer over putting in a string literal.
<%@ page import="com.example.Status" %>
1. ${dp.status eq Title.VALID.getStatus()}
2. ${dp.status eq Title.VALID}
3. ${dp.status eq Title.VALID.toString()}
- Put the import at the top, in JSP page header
- If you want to work with getStatus method, use #1
- If you want to work with the enum element itself, use either #2 or #3
- You can use == instead of eq
I generally consider it bad practice to mix java code into jsps/tag files. Using 'eq' should do the trick :
<c:if test="${dp.Status eq 'OLD'}">
...
</c:if>
I do it this way when there are many points to use...
public enum Status {
VALID("valid"), OLD("old");
private final String val;
Status(String val) {
this.val = val;
}
public String getStatus() {
return val;
}
public static void setRequestAttributes(HttpServletRequest request) {
Map<String,String> vals = new HashMap<String,String>();
for (Status val : Status.values()) {
vals.put(val.name(), val.value);
}
request.setAttribute("Status", vals);
}
}
JSP
<%@ page import="...Status" %>
<% Status.setRequestAttributes(request) %>
<c:when test="${dp.status eq Status.VALID}">
...
In Java Class:
public class EnumTest{
//Other property link
private String name;
....
public enum Status {
ACTIVE,NEWLINK, BROADCASTED, PENDING, CLICKED, VERIFIED, AWARDED, INACTIVE, EXPIRED, DELETED_BY_ADMIN;
}
private Status statusobj ;
//Getter and Setters
}
So now POJO and enum obj is created. Now EnumTest you will set in session object using in the servlet or controller class session.setAttribute("enumTest", EnumTest );
In JSP Page
<c:if test="${enumTest.statusobj == 'ACTIVE'}">
//TRUE??? THEN PROCESS SOME LOGIC
참고URL : https://stackoverflow.com/questions/123598/access-enum-value-using-el-with-jstl
'Programing' 카테고리의 다른 글
| 현재 웹 페이지 스크롤 위치를 가져오고 설정하는 방법은 무엇입니까? (0) | 2020.08.16 |
|---|---|
| 정해진 기간이 지나면 만료되는 Android 평가판 애플리케이션 만들기 (0) | 2020.08.16 |
| 화면 회전 후 TextView 상태 복원? (0) | 2020.08.16 |
| void에서 &&는 무엇을 의미합니까 * p = && abc; (0) | 2020.08.16 |
| Git 브랜치를 닫는 방법? (0) | 2020.08.16 |