类型转换及返回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 . 以及 提示手机号未注册 。
类型转换及返回json对象的问题的更多相关文章
- Spring MVC学习笔记——返回JSON对象
1.想要GET请求返回JSON对象,首先需要导入jackson-all-1.9.4.jar包 2.在控制器中添加不同的show()方法 //show()方法返回JSON对象 @RequestMappi ...
- 转: .NET MVC3 几种返回 JSON 对象的方式和注意事项
.NET MVC3 几种返回 JSON 对象的方式和注意事项 转自:http://blog.csdn.net/xxj_jing/article/details/7382589 引言在用 .NET MV ...
- Django中的 返回json对象的方式
在返回json对象的几种方式: 1 from django.shortcuts import render, HttpResponse # Create your views here. from d ...
- VB 老旧版本维护系列---尴尬的webapi访问返回json对象
尴尬的webapi访问返回json对象 首先Imports Newtonsoft.Json Imports MSXML2(Interop.MSXML2.dll) Dim URLEncode As Sy ...
- Struts2返回JSON对象的方法总结
如果是作为客户端的HTTP+JSON接口工程,没有JSP等view视图的情况下,使用Jersery框架开发绝对是第一选择.而在基于Spring3 MVC的架构下,对HTTP+JSON的返回类型也有很好 ...
- (转)Struts2返回JSON对象的方法总结
转自:http://kingxss.iteye.com/blog/1622455 如果是作为客户端的HTTP+JSON接口工程,没有JSP等view视图的情况下,使用Jersery框架开发绝对是第一选 ...
- MVC API 返回json 对象,使用netjson 返回
1.清除xml 格式 GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear(); 2. ...
- ajax返回json对象的两种写法
1. 前言 dataType: 要求为String类型的参数,预期服务器返回的数据类型.如果不指定,JQuery将自动根据http包mime信息返回responseXML或responseText,并 ...
- 前后台$.post交互并返回JSON对象
1.前台代码: $.post(url,{"blogId":blogId},function(reData){ if(reData.state=="success" ...
随机推荐
- 借助 Lucene.Net 构建站内搜索引擎(上)
前言:最近翻开了之前老杨(杨中科)的Lucene.Net站内搜索项目的教学视频,于是作为老杨脑残粉的我又跟着复习了一遍,学习途中做了一些笔记也就成了接下来您看到的这篇博文,仅仅是我的个人笔记,大神请呵 ...
- MySQL 远程连接(federated存储引擎)
标签:federated存储引擎 概述 本文主要介绍通过federated存储引擎建立远程连接表 测试环境:mysql 5.6.21 步骤 开启federated存储引擎 先查看federated存储 ...
- 修改TNSLSNR的端口
oracle 服务一启动 TNSLSNR.exe 会占用8080端口,这时,如果我们其他程序需要使用8080端口就会比较麻烦,所以需要改一下端口: 用dba账户登录 CMD>sqlplus sy ...
- 《Entity Framework 6 Recipes》中文翻译系列 (15) -----第三章 查询之与列表值比较和过滤关联实体
翻译的初衷以及为什么选择<Entity Framework 6 Recipes>来学习,请看本系列开篇 3-8与列表值比较 问题 你想查询一个实体,条件是给定的列表中包含指定属性的值. 解 ...
- Thrift架构~目录
回到占占推荐博客索引 概念相关 thrift是一个软件框架,用来进行可扩展且跨语言的服务的开发.它结合了功能强大的软件堆栈和代码生成引擎,以构建在 C++, Java, Python, PHP, Ru ...
- mac下tomcat的安装与配置
1.到 apache官方主页 下载 Mac 版本的完整 tar.gz文件包.解压拷贝到 /Library目录下,并命名为Tomcat,其他目录也可. 2.修改目录权限 到终端输入 sudo chm ...
- 阿里云centos7搭建wordpress环境
阿里云搭建wordpress系统 一.购买阿里云 二.安装php开发环境 1. https://www.apachefriends.org/zh_cn/index.html网站下载linux下的xam ...
- 浅析Yii2的view层设计
Yii2.0的view层提供了若干重要的功能:assets资源管理,widgets小组件,layouts布局... 下面将通过对Yii2.0代码直接进行分析,看一下上述功能都是如何实现的,当然细枝末节 ...
- VS中行号对齐的辅助线(虚线)去除
3张图 2 3
- js修改后没反应-看看是不是取的缓存