2013-04-24 87 views
0

你好,我是新的jsp我想檢查jsp中的條件。值是否爲空。 我在jsp頁面寫入​​以下代碼如何用JSP變量檢查條件?

<% String s = request.getParameter("search"); %> 
    <%=s %> 
    <% if (<%=s ==null) { %> 
    <div>textbox is empty</div> 

    <% } else { %> 
    <div>textbox value.. 
    <% } %> 

我得到在可變文本框的值,如果文本框的值是空值,則它應該顯示othervise第二第一消息。 告訴我該怎麼辦?

+1

順便說一下,最好的做法是避免在您的jsp中使用scriptlet。 http://stackoverflow.com/questions/3177733/how-to-avoid-java-code-in-jsp-files – Drogba 2013-04-24 07:36:12

+0

這是更多的語法問題 - 我想一旦Rajan得到他的答案,問題應該被刪除。 – aquaraga 2013-04-24 07:37:04

+0

你的問題說如果文本框的值爲空,那麼執行'if',否則'else'?你的文本框的價值是什麼? s的價值? – harsh 2013-04-24 07:40:59

回答

5
<% String s = request.getParameter("search"); %> 
    <%=s %> 
    <% if (s==null || s.isEmpty()) { %> 
    <div>textbox is empty</div> 

    <% } else { %> 
    <div>textbox value.. 
    <% } %> 
+0

如果我不插入文本框中的值,那麼它也去其他部分 – Kapil 2013-04-24 07:37:43

+1

@Rajan你可以檢查's'打印的是什麼值嗎?它可能不是'null',而是空'''''或者有空格。檢查修改回答.. – harsh 2013-04-24 07:42:24

+0

當然..讓我試 – Kapil 2013-04-24 07:44:00

3

它甚至編譯? <% if (<%=s ==null) { %>至少應該

<% if (s == null) { %> 

如果要檢查空字符串爲好,做

<% if(s == null || s.trim().length == 0) { %> 
+0

不,它給我錯誤 – Kapil 2013-04-24 07:31:15

+0

請給我正確的代碼,請 – Kapil 2013-04-24 07:31:52

+0

我已經有。 – NilsH 2013-04-24 07:32:23

2
<% String s = request.getParameter("search"); 
    if (s ==null) { %> 
    <div>textbox is empty</div> 

    <% } else { %> 
    <div><span><%=s%></span></div> 
    <% } %> 

編輯成包括空字符串

<% 
     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> 
      <%}%> 
+0

你好ntstha .... – Kapil 2013-04-24 07:40:00

1
<% String s = request.getParameter("search"); %> 
    <%=s %> 
    <% if (s ==null) { %> 
    <div>textbox is empty</div> 

    <% } else { %> 
    <div>textbox value.. 
    <% } %> 
+0

hello alpesh Gediya ...它也去其他部分 – Kapil 2013-04-24 07:40:24

8

最好的辦法是用JSTLPlease avoid scriptlets in JSP

<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>