类型转换及返回json对象的问题

	@ResponseBody
	@RequestMapping(value="/user/getUserId.do")//method=RequestMethod.POST
	public JSONObject getUserId(HttpServletRequest request, HttpServletResponse response)throws Exception {
	    response.setContentType("text/html");
	    request.setCharacterEncoding("utf-8");
	    response.setCharacterEncoding("utf-8");
	    String phoneNum = request.getParameter("phoneNum");
	    JSONObject jsonObject = new JSONObject();
	    
	    Integer userId = 0;
	        try
	        {	          
	            userId = userSlaveService.getUserId(phoneNum);	     
	            if(StringUtils.isNotEmpty(Integer.toString(userId))){
		        	jsonObject.accumulate("userId", userId);
		        }
//		        else{
//		        	return null;
//		        }
	        }
	        catch (Exception e)
	        {
	            Loger.logtxt("user", "获取Userid异常:" + e.toString());
	        }
	        
	        return jsonObject;
	}

  

1.  Integer 型变量 a  转换成 String 时, 如果 a 是 null ,用 Integer.toString(a)  或者 a.toString() 都会报空指针异常,需要 放到 try catch 中捕获异常。

    如上代码,如果 根据手机号 没有查到 Userid ,则 Userid 是 null 。 Integer.toString(userId) 会抛出 NullPointer 空指针异常,if 中的语句不会执行,跳到 catch , 执行catch 中的代码。 返回的 

jsonObject 是 {}

        //获取注册用户userid
        function  getUserId(){         
            var  phoneNum=$("#phoneNum").val()    
            
                     $.getJSON(
                             '<%=basePath %>user/getUserId.do',
                             {phoneNum:phoneNum},
                             function(data){    
                            alert("data:" + data)
                            alert("data.userid:" + eval(data).userId)
                            if(!(eval(data).userId)){
                                alert('该手机号未注册,请先注册');    
                            }
                            else{             
                                document.getElementById("marcherId").value=data.userId;
                            }
                         }
                   );                 
        }

前台 js  打印: data:[Object Object]  和 data.userid: undefined . 以及 提示手机号未注册 。 

如果 类型转换 不放到 try catch 中 ,比如写成如下:

    @ResponseBody
    @RequestMapping(value="/user/getUserId.do")//method=RequestMethod.POST
    public JSONObject getUserId(HttpServletRequest request, HttpServletResponse response)throws Exception {
        response.setContentType("text/html");
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        String phoneNum = request.getParameter("phoneNum");
        JSONObject jsonObject = new JSONObject();
        
        Integer userId = 0;
            try
            {              
                userId = userSlaveService.getUserId(phoneNum);         
//                if(StringUtils.isNotEmpty(Integer.toString(userId))){
//                    jsonObject.accumulate("userId", userId);
//                }
            }
            catch (Exception e)
            {
                Loger.logtxt("user", "获取Userid异常:" + e.toString());
            }
            if(StringUtils.isNotEmpty(Integer.toString(userId))){
                jsonObject.accumulate("userId", userId);
            }
            else{
                return null;
            }
            return jsonObject;
    }

在执行到 if 中的 Integer.toString(userId) 时,程序抛出异常。

后台报错: java.lang.NullPointerException ,程序异常终止,并不会执行 return 和 else 语句。前台页面没有任何反应。

如果写成这样:

    @ResponseBody
    @RequestMapping(value="/user/getUserId.do")//method=RequestMethod.POST
    public JSONObject getUserId(HttpServletRequest request, HttpServletResponse response)throws Exception {
        response.setContentType("text/html");
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        String phoneNum = request.getParameter("phoneNum");
        JSONObject jsonObject = new JSONObject();
        
        Integer userId = 0;
            try
            {              
                userId = userSlaveService.getUserId(phoneNum);         
//                if(StringUtils.isNotEmpty(Integer.toString(userId))){
//                    jsonObject.accumulate("userId", userId);
//                }
            }
            catch (Exception e)
            {
                Loger.logtxt("user", "获取Userid异常:" + e.toString());
            }
          
            jsonObject.accumulate("userId", userId);

            return jsonObject;
    }
没有查到数据,userId 是 null ,返回的 jsonObject  是 {"userId":null} 。 后台正常返回,没有异常抛出。
在 Chrome 中看到的是 500 Internal Server Error ,jquery1.6.1.js 的 xhr.send( ( s.hasContent && s.data ) || null ); 出错。 前台没有任何反应,没有执行 前台 的
 function(data) 函数 。(why?)
对于前台的   /eduappweb/user/getUserId.do?phoneNum=56354635635 HTTP/1.1 消息, 后台返回 HTTP/1.1 500 Internal Server Error The server encountered an internal error that prevented it from fulfilling this request.

所以如果要给前台返回json对象,需要判断json对象中key 的value 是不是 null 。如果json 中 value 的值是 null ,则返回 {} 给前台,不要把 {“key”:null} 这样的形式返回给前台。




    $.getJSON(
                             '<%=basePath %>user/getUserId.do',
                             {phoneNum:phoneNum},
                             function(data){    
                            alert("data:" + data)
                            alert("data.userid:" + eval(data).userId)
                            if(!(eval(data).userId)){
                                alert('该手机号未注册,请先注册');    
                            }
                            else{             
                                document.getElementById("marcherId").value=data.userId;
                            }
                         }
                   );       

 如果后台返回  null ,会执行 fanction 函数, 打印 data:null 。但是  eval(data).userId 会报错 Uncaught TypeError: Cannot read property 'userId' of null

 如果后台写成这样:

           JSONObject jsonObject = new JSONObject();  
    System.out.println("jsonObject: " + jsonObject);
            if(userId==null){
                return jsonObject;
            }else{
                jsonObject.accumulate("userId", userId);
            }        
            return jsonObject;

返回的是  jsonObject 值是 {}  ,  function函数正常执行。前台 js  打印: data:[Object Object]  和 data.userid: undefined . 以及 提示手机号未注册 。 




原文地址:https://www.cnblogs.com/z360519549/p/5758379.html