@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. 让Ajax更简单

    之前写了一篇 ASP.NET中一种超简单的Ajax解决方案 最近把他拿出来更新了下,把demo也搞的更详细了一点 加入了blqw.Json,所以支持更多类型参数和返回值 优化了对exception的处 ...

  2. I/O重定向的原理和实现

    在Unix系统中,每个进程都有STDIN.STDOUT和STDERR这3种标准I/O,它们是程序最通用的输入输出方式.几乎所有语言都有相应的标准I/O函数,比如,C语言可以通过scanf从终端输入字符 ...

  3. AD域内DNS服务器如何解析公网域名

    原创地址:http://www.cnblogs.com/jfzhu/p/4022999.html 转载请注明出处 AD域内需要有DNS服务器,用于解析域内的计算机名,但是域内的计算如何解析公网的域名呢 ...

  4. Ubuntu 安装OpenERP

    网上的都TM不靠谱.... 1.用root登录,修改/etc/apt/sources.list 文件 sudo /etc/apt/sources.list u root 注意一定要加U root否则没 ...

  5. 一个不错的vue表单验证插件

    github文档 用着不错,官方的文档例子很简单 <body> <div id="app"> <validator name="valida ...

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

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

  7. Cookie与Session

    再说Cookie与Session之前,先要了解一下http协议. 何为http协议: http协议即超文本传输协议,一种基于浏览器请求与服务器响应的协议,该协议主要的特点就是它是一种无状态的协议(只针 ...

  8. java继承、抽象和接口

    package zdbExtends;public class Grandparent {        public Grandparent(){                System.out ...

  9. 基于stm32f4的ucGUI通过外部flash存储汉字库显示任意英文字符和汉字组合(控件可用)

    在做一个用到ucGUI的项目的时候要用到不定的汉字和英文字符,但是ucGUI本身又不支持读取芯片外部flash的字库来显示,于是查了下资料,如下: http://www.cnblogs.com/hik ...

  10. 利用免费cdn加速webpack单页应用

    回顾现状 在之前的学习过程中,react单页应用经过webpack打包之后会输出大概如下的目录结构,它就是站点的所有前端组成了:   1 2 3 4 5 6 MacBook-Pro:output ba ...