Ajax调用数据提示:NULL”或“未定义”?

我通过Ajax调用将数据从jsp发送到控制器,而它是个对象数据(不是一个简单的字符串),因此有时在发送之前可能不会初始化它,因此我可能获得NULL或“NULL”或“未定义”的提示。

因此,在控制器中,我需要通过以下方式进行比较:

if(request.getParameter("variableName")!=null && !request.getParameter("variableName").equals("null") && !request.getParameter("variableName").equals("undefined"))

它看起来太乱了,有没有更好的处理方法?

In your AJAX call, before submitting the request ensure you send non-null value or empty string if null or undefined.

You can simplify the code as below.

Object obj = request.getParameter("variableName");
if(obj != null && !obj.equals("null") && !obj.equals("undefined"))

But the better option is to handle it just before sending the data via ajax to controller.

The first step it to avoid duplicated action, sow you should assign the result to a variable.

String result = request.getParameter("variableName");

Then instead of locking the logic in some if, you could check that application should continue.

if(result == null || "null".equals(result) || "undefined".equals(result)) {

   return; //or throw if required

}

As you probably will validate that very often you could extract the code to class RequestUtils, that could have static method validateRequestParameter(request, "variableName"), that will return true if valid else false.