@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. Hadoop学习笔记—1.基本介绍与环境配置

    一.Hadoop的发展历史 说到Hadoop的起源,不得不说到一个传奇的IT公司—全球IT技术的引领者Google.Google(自称)为云计算概念的提出者,在自身多年的搜索引擎业务中构建了突破性的G ...

  2. [nRF51822] 10、基础实验代码解析大全 · 实验15 - RTC

    一.实验内容: 配置NRF51822 的RTC0 的TICK 频率为8Hz,COMPARE0 匹配事件触发周期为3 秒,并使能了TICK 和COMPARE0 中断. TICK 中断中驱动指示灯D1 翻 ...

  3. 没有水果机的也来体验下Visual Studio for Mac

    在去年微软已经宣布.NET将实现真正的跨平台,并且发布了Mac和Linux版的Visual Studio Code编辑器,但强大的Visual Studio确只有Windows版. 还坚守.NET开发 ...

  4. 巧用Ajax的beforeSend 提高用户体验

    jQuery是经常使用的一个开源js框架,其中的$.ajax请求中有一个beforeSend方法,用于在向服务器发送请求前执行一些动作.具体可参考jQuery官方文档:http://api.jquer ...

  5. Sql Server系列:子查询

    1 子查询概念 子查询是嵌套在另一个查询中的普通T-SQL查询.在有一个SELECT语句通过使用小括号创建子查询,作为另一个查询的部分数据或条件的基础. 子查询通常用于满足以下某个需求: ◊ 将一个查 ...

  6. sizzle分析记录:getAttribute和getAttributeNode

    部分IE游览器下无法通过getAttribute取值? <form name="aaron"> <input type="text" name ...

  7. ECMAScript5之StrictMode

    ECMAScript5引入一个严格模式的概念(Strict Mode). 它的作用就是不让Javascript的容错那么高,让我们对编写代码的规范要求高一点. 比如,当我们使用严格模式编写JavaSc ...

  8. 2、Redis入门介绍

    1.什么是Redis Redis:REmote DIctionary Server(远程字典服务器) 是完全开源免费的,用C语言编写的,遵守BSD协议,是一个高性能的(key/value)分布式内存数 ...

  9. MySQL学习笔记十六:锁机制

    1.数据库锁就是为了保证数据库数据的一致性在一个共享资源被并发访问时使得数据访问顺序化的机制.MySQL数据库的锁机制比较独特,支持不同的存储引擎使用不同的锁机制. 2.MySQL使用了三种类型的锁机 ...

  10. js实现css3的过渡,需要注意的一点(浏览器优化)

    大部分浏览器对元素几何改变时候的重排做了优化.据说是这样子,一定时间内本应多次重排的改变,浏览器会hold住,仅一次重排.其中如果使用分离的一步处理过程,例如计时器,依然多次重排.例如,当我们应用tr ...