@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 . 以及 提示手机号未注册 。


类型转换及返回json对象的问题的更多相关文章

  1. Spring MVC学习笔记——返回JSON对象

    1.想要GET请求返回JSON对象,首先需要导入jackson-all-1.9.4.jar包 2.在控制器中添加不同的show()方法 //show()方法返回JSON对象 @RequestMappi ...

  2. 转: .NET MVC3 几种返回 JSON 对象的方式和注意事项

    .NET MVC3 几种返回 JSON 对象的方式和注意事项 转自:http://blog.csdn.net/xxj_jing/article/details/7382589 引言在用 .NET MV ...

  3. Django中的 返回json对象的方式

    在返回json对象的几种方式: 1 from django.shortcuts import render, HttpResponse # Create your views here. from d ...

  4. VB 老旧版本维护系列---尴尬的webapi访问返回json对象

    尴尬的webapi访问返回json对象 首先Imports Newtonsoft.Json Imports MSXML2(Interop.MSXML2.dll) Dim URLEncode As Sy ...

  5. Struts2返回JSON对象的方法总结

    如果是作为客户端的HTTP+JSON接口工程,没有JSP等view视图的情况下,使用Jersery框架开发绝对是第一选择.而在基于Spring3 MVC的架构下,对HTTP+JSON的返回类型也有很好 ...

  6. (转)Struts2返回JSON对象的方法总结

    转自:http://kingxss.iteye.com/blog/1622455 如果是作为客户端的HTTP+JSON接口工程,没有JSP等view视图的情况下,使用Jersery框架开发绝对是第一选 ...

  7. MVC API 返回json 对象,使用netjson 返回

    1.清除xml 格式 GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear(); 2. ...

  8. ajax返回json对象的两种写法

    1. 前言 dataType: 要求为String类型的参数,预期服务器返回的数据类型.如果不指定,JQuery将自动根据http包mime信息返回responseXML或responseText,并 ...

  9. 前后台$.post交互并返回JSON对象

    1.前台代码: $.post(url,{"blogId":blogId},function(reData){ if(reData.state=="success" ...

随机推荐

  1. 让浏览器不再显示 https 页面中的 http 请求警报

    HTTPS 是 HTTP over Secure Socket Layer,以安全为目标的 HTTP 通道,所以在 HTTPS 承载的页面上不允许出现 http 请求,一旦出现就是提示或报错: Mix ...

  2. 类库间无项目引用时,在编译时拷贝DLL

    例一: xcopy $(TargetPath) $(SolutionDir)\Framework\HCSP.App\bin\Debug /y 例二: xcopy $(TargetPath) $(Sol ...

  3. 可以这样去理解group by和聚合函数

    写在前面的话:用了好久group by,今天早上一觉醒来,突然感觉group by好陌生,总有个筋别不过来,为什么不能够select * from Table group by id,为什么一定不能是 ...

  4. 【javascript 技巧】Array.prototype.slice的妙用

    Array.prototype.slice的妙用 开门见山,关于Array 的slice的用法可以参考这里 http://www.w3school.com.cn/js/jsref_slice_arra ...

  5. 几个毫无节操纯属恶搞的JavaScript插件

    fartscroll.js,为放屁而生 你知道么,有了这个js库,你的页面就可以——————————放屁勒! 打开下面的演示地址,然后滚动页面. 在线演示:http://theonion.github ...

  6. Oracle 中 union 和union all 的简单使用说明

    1.刚刚工作不久,经常接触oracle,但是对oracle很多东西都不是很熟.今天我们来了解一下union和union all的简单使用说明.Union(union all): 指令的目的是将两个 S ...

  7. JavaScript中的百变大咖~this

    原文链接:http://www.jeffjade.com/2015/08/03/2015-08-03-javascript-this/ JavaScript作为一种脚本语言身份的存在,因此被很多人认为 ...

  8. Cocos2d-x 3.x游戏开发之旅

    Cocos2d-x 3.x游戏开发之旅 钟迪龙 著   ISBN 978-7-121-24276-2 2014年10月出版 定价:79.00元 516页 16开 内容提要 <Cocos2d-x ...

  9. SQL Server 创建数据库邮件

    一. 背景 数据库发邮件通知数据库的运行状态(状态可以通过JOB形式获取)和信息,达到预警的效果. 二. 基础知识 msdb系统数据库保存有关Job,Database Mail,Nodifyicati ...

  10. 【原创】开源Math.NET基础数学类库使用(17)C#计算矩阵条件数

                   本博客所有文章分类的总目录:[总目录]本博客博文总目录-实时更新  开源Math.NET基础数学类库使用总目录:[目录]开源Math.NET基础数学类库使用总目录 上个月 ...