のタグをString
使用して、aがnullまたは空かどうかを検証するにはどうすればよいですか?c
JSTL
名前の変数がありvar1
、それを表示できますが、それを検証するためにコンパレーターを追加したいと思います。
<c:out value="${var1}" />
nullまたは空の場合を検証したい(私の値は文字列です)。
JSTLのcタグを使用して、文字列がnullまたは空であるかどうかを検証するにはどうすればよいですか?
これには、でempty
キーワードを使用できます。<c:if>
<c:if test="${empty var1}">
var1 is empty or null.
</c:if>
<c:if test="${not empty var1}">
var1 is NOT empty or null.
</c:if>
または<c:choose>
:
<c:choose>
<c:when test="${empty var1}">
var1 is empty or null.
</c:when>
<c:otherwise>
var1 is NOT empty or null.
</c:otherwise>
</c:choose>
または、タグの束を条件付きでレンダリングする必要がなく、タグ属性内でしかチェックできない場合は、EL条件演算子を使用できます${condition? valueIfTrue : valueIfFalse}
。
<c:out value="${empty var1 ? 'var1 is empty or null' : 'var1 is NOT empty or null'}" />
これらの${}
こと(JSTLとは別の主題である式言語)の詳細については、こちらを確認してください。
空白の文字列もチェックするには、次のことをお勧めします
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<c:if test="${empty fn:trim(var1)}">
</c:if>
nullも処理します
nullまたは空のみをチェックする場合は、デフォルトのオプションで次のように使用できます。
<c:out default="var1 is empty or null." value="${var1}"/>
このコードは正しいですが、nullまたは空の文字列の代わりに多くのスペース('')を入力すると、falseが返されます。
これを修正するには、通常の式を使用します(以下のコードは、変数がnullか空か、org.apache.commons.lang.StringUtils.isNotBlankと同じように空白かどうかを確認します):
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<c:if test="${not empty description}">
<c:set var="description" value="${fn:replace(description, ' ', '')}" />
<c:if test="${not empty description}">
The description is not blank.
</c:if>
</c:if>
これがワンライナーです。
${empty value?'value is empty or null':'value is NOT empty or null'}
使用できます
${var == null}
あるいは。
これは、JavaコントローラーからJSPファイルに渡すintとStringを検証する方法の例です。
MainController.java:
@RequestMapping(value="/ImportJavaToJSP")
public ModelAndView getImportJavaToJSP() {
ModelAndView model2= new ModelAndView("importJavaToJSPExamples");
int someNumberValue=6;
String someStringValue="abcdefg";
//model2.addObject("someNumber", someNumberValue);
model2.addObject("someString", someStringValue);
return model2;
}
importJavaToJSPExamples.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<p>${someNumber}</p>
<c:if test="${not empty someNumber}">
<p>someNumber is Not Empty</p>
</c:if>
<c:if test="${empty someNumber}">
<p>someNumber is Empty</p>
</c:if>
<p>${someString}</p>
<c:if test="${not empty someString}">
<p>someString is Not Empty</p>
</c:if>
<c:if test="${empty someString}">
<p>someString is Empty</p>
</c:if>
In this step I have Set the variable first:
<c:set var="structureId" value="<%=article.getStructureId()%>" scope="request"></c:set>
In this step I have checked the variable empty or not:
<c:if test="${not empty structureId }">
<a href="javascript:void(0);">Change Design</a>
</c:if>