簡體   English   中英

Spring MVC控制器將空數據返回到視圖

[英]Spring MVC controller returns null data to the view

我有一個控制器,它返回用戶列表。 當用戶存在時,該程序可以正常運行。 但是,當找不到用戶時,控制器將null返回到jsp頁面,在這種情況下,我得到了一個空白屏幕,沒有打印出jsp頁面中的任何“警報”。 請讓我知道為什么無法打印alert(“用戶不存在”),以及當控制器向jsp頁面返回null時如何處理這種情況。

   @RequestMapping(value = "/userSearch",
                   method = RequestMethod.POST,
                   produces = "application/json")
   @ResponseBody
   public UserList search @RequestParam String username) 
   {     
          UserList userListObj = search(username); // search database

          if (userListObj.getUserList().size() > 0) 
          {
              return userListObj;
          } 
          else 
          {
              return null;
          }
     }

JSP代碼:

    function ajaxUserSearch() 
    {   
         var uname = $("#userName").val();
         if ( uname )
         {              
              $.ajax({
                type: "POST",
                url: "userSearch.htm",
                data: "username=" + uname ,
                dataType: "json",
                success: function(data) 
                {   
                     alert("data=" + data);
                     if ( data!=null )
                     {      
                          alert("data not null");
                     } 
                     else 
                     {            
                         alert(" user does not exist, please check");
                     }                 
                },                   
                error: function(jqXHR, status, error)
                {
                    alert("error=" + error + "\nstatus=" + status);
                }              
             });
       }
       else // If no name is entered but Search button is pressed
       {
            alert("Please enter a user name.");
       }
} 

不要返回null。 它基本上是一個空的http響應。

在Java代碼中,嘗試返回以下內容: return "notfound"

然后在Javacript success嘗試做類似的事情:

if (data != null) {
   if (data === "notfound") {
     alert("user not found"); 
   } else {
      alert("user found" + data);
   }
} else {
   alert("unexpected error when finding user. please try again"); 
}

甚至根本不需要檢查控制器中userListObj的大小...只需將對象返回到頁面即可:

@ResponseBody
public UserList search @RequestParam String username) {     
      return search(username); // search database
}

然后在ajax成功函數中,解析json並檢查UserList的長度:

success: function(data) {   
    var userListObj = $.parseJSON(data);
    if(userListObj.UserList.length > 0) {      
        alert("data not null");
    } else {
        alert("user does not exist, please check");
    }

我通過在客戶端輸入字段上禁用Enter鍵解決了自己的問題。

  $("form").bind("keypress", function (event) 
            {
                if (event.keyCode == 13) 
                {
                    event.preventDefault();
                    return false;
                }
            });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM