@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. jws.mono脚本安装详解

    就在最近两天,最新版本的jws.mono上线了,这个版本除了提供与之前版本拥有的功能外,还额外提供了一个“自动化”的安装脚本,通过执行该脚本,jws.mono将自动快速的安装到指定的目录,同时,通过改 ...

  2. ASP.NET Web API路由系统:路由系统的几个核心类型

    虽然ASP.NET Web API框架采用与ASP.NET MVC框架类似的管道式设计,但是ASP.NET Web API管道的核心部分(定义在程序集System.Web.Http.dll中)已经移除 ...

  3. k近邻(KNN)复习总结

    摘要: 1.算法概述 2.算法推导 3.算法特性及优缺点 4.注意事项 5.实现和具体例子 6.适用场合内容: 1.算法概述 K近邻算法是一种基本分类和回归方法:分类时,根据其K个最近邻的训练实例的类 ...

  4. 机器学习理论知识部分--偏差方差平衡(bias-variance tradeoff)

    摘要: 1.常见问题 1.1 什么是偏差与方差? 1.2 为什么会产生过拟合,有哪些方法可以预防或克服过拟合? 2.模型选择例子 3.特征选择例子 4.特征工程与数据预处理例子 内容: 1.常见问题 ...

  5. JVM字节码指令

    invokevirtual 调用实例方法 invokespecial 调用父类构造,实例初始化方法,私有方法 dup 复制栈顶数值,并且复制值进栈,pop/pop2为栈顶值出栈 aload_0 加载第 ...

  6. 谈谈php里的IOC控制反转,DI依赖注入

    理论 发现问题 在深入细节之前,需要确保我们理解"IOC控制反转"和"DI依赖注入"是什么,能够解决什么问题,这些在维基百科中有非常清晰的说明. 控制反转(In ...

  7. A Simple OpenCASCADE Qt Demo-occQt

    A Simple OpenCASCADE Qt Demo-occQt eryar@163.com Abstract. OpenCASCADE have provided the Qt samples ...

  8. JS 原型,检索,更新,引用等

    <script type="text/javascript"> var myObject=maker({ first:f, last:1, state:s, city: ...

  9. ASP.NET MVC5 网站开发实践(二) Member区域–我的咨询列表及添加咨询

    上次把咨询的架构搭好了,现在分两次来完成咨询:1.用户部分,2管理部分.这次实现用户部分,包含两个功能,查看我的咨询和进行咨询. 目录: ASP.NET MVC5 网站开发实践 - 概述 ASP.NE ...

  10. 万能Adapter以及ViewHolder性能优化

    //CommonAdapter import android.content.Context; import android.widget.BaseAdapter; import java.util. ...