Java 如何使用 JSP 变量检查条件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16185956/
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
How to check condition with JSP variable?
提问by Kapil
Hello i am New jsp i want to check condition in jsp. whether value is null or not.? i have write following code in jsp page
你好,我是新的 jsp,我想在 jsp 中检查条件。值是否为空。?我在jsp页面中写了以下代码
<% String s = request.getParameter("search"); %>
<%=s %>
<% if (<%=s ==null) { %>
<div>textbox is empty</div>
<% } else { %>
<div>textbox value..
<% } %>
i get textbox value in variable if textbox value is null then it should display first message othervise second. tell me how to do?
如果文本框值为空,我会在变量中获取文本框值,那么它应该显示第一条消息,否则第二条消息。告诉我怎么办?
采纳答案by harsh
<% String s = request.getParameter("search"); %>
<%=s %>
<% if (s==null || s.isEmpty()) { %>
<div>textbox is empty</div>
<% } else { %>
<div>textbox value..
<% } %>
回答by NilsH
Does it even compile? <% if (<%=s ==null) { %>
should at least be
它甚至编译吗?<% if (<%=s ==null) { %>
至少应该是
<% if (s == null) { %>
If you want to check for empty string as well, do
如果您还想检查空字符串,请执行
<% if(s == null || s.trim().length == 0) { %>
回答by ntstha
<% String s = request.getParameter("search");
if (s ==null) { %>
<div>textbox is empty</div>
<% } else { %>
<div><span><%=s%></span></div>
<% } %>
edited to include empty string
编辑为包含空字符串
<%
String s="";
if(request.getParameter("search")!=null)
{
s=request.getParamater("search");
}
if(s.trim().length()==0)
{%>
<div>Empty Field</div>
<%}
else{%>
<div><span><%=s%></div>
<%}%>
回答by Alpesh Gediya
<% String s = request.getParameter("search"); %>
<%=s %>
<% if (s ==null) { %>
<div>textbox is empty</div>
<% } else { %>
<div>textbox value..
<% } %>
回答by NINCOMPOOP
The best way to do it is with JSTL. Please avoid scriptlets in JSP.
最好的方法是使用JSTL。请避免在 JSP 中使用 scriptlet。
<c:choose>
<c:when test="${empty search}">
<div>textbox is empty</div>
</c:when>
<c:otherwise>
<div>textbox value is ${search}</div>
</c:otherwise>
</c:choose>
回答by Bhagawat
In jsp
, it is easy to check whether a variable is empty or not
.
在 中jsp
,很容易检查是否 a variable is empty or not
。
String search;
if(search.isEmpty()){
out.println("The variable is empty ?");
}
else{
out.println("The variable is Not empty ?");
}