关于servlet中不能获取前台传入的json数据的问题

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/JohnnyWangDD/article/details/78391595

今天上午遇到一个奇怪的问题,自己写了一个测试小程序,没有用框架,前台传入一个json数据给servlet,但servlet中接受不到,代码如下:

servlet的代码:

public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
			String nn = request.getParameter("name");
		 	PrintWriter out = response.getWriter();  
	        System.out.println("doGet invoked!");  
	        out.println(nn);  
	        out.flush(); 
	}
前端代码:

<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE html>
<html>
<head>
 <script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery-1.8.3.js"></script>
<script>
	    
	function requestJson(){
	var j ={"name":"wang","sex":"nan"};
	       $.ajax({
	             type:"post",
	             url:"servlet/Test",
	             contentType:'application/json;charset=UTF-8',
	             //数据格式 json字符串传递
	             data:j,
	             success:function(data){
	              alert(data);
	             }
	       });
	    }
</script>
</head>

<body>
<input type="button" value="jj" οnclick="requestJson()">

</body>
</html>
但在后台,一直那不到要的值,这个问题困扰了我一上午,之前用spring框架,后台直接拿到json数据封装到对象中,但没用框架的话不可以这样做。

之后在网上看到其他前辈的建议,前端的代码:

contentType:'application/json;charset=UTF-8',

改为

contentType: "application/x-www-form-urlencoded",
问题解决。

原理:

application/x-www-form-urlencoded方式是Jquery的Ajax请求默认方式,这种方式的好处就是浏览器都支持,在请求发送过程中会对数据进行序列化处理,以键值对形式?key1=value1&key2=value2的方式发送到服务器,如果用Jquery,它内部已经进行了处理,如果自己写原生的Ajax请求,就需要自己对数据进行序列化。

OK,问题解决。

展开阅读全文

前台ExtJs4.1后台servlet接收json数据问题

09-27

情景描述:rn前端采用extjs4推荐的MVC架构,其中Users Store文件Users.js内容如下:rn[code=JScript]rnExt.define('MyApp.store.Users',rn extend:'Ext.data.Store',rn model:'MyApp.model.User',rn autoLoad:true,//保证store一创建就从server端通过代理加载数据rn proxy://代理负责数据的加载和存储,和一个store或者一个model关联rn type:'ajax',rn api:rn read:'data/users.json',rn update:'TestServlet'//store中的某条记录发生更改,会将更改反馈给该urlrn ,rn reader://reader负责将response解码成store能理解的形式rn type:'json',rn root:'users',rn successProperty:'success'rn rn rn );rn[/code]rnrn当store的数据发生更改后,通过调用其sync()方法,便可将更改后的记录以json格式封装,并请求TestServlet。rnrn通过谷歌浏览器的工具查看,确实将更改后的记录发送过来了。request请求消息如下:rn请求头rnAccept:*/*rnAccept-Charset:GBK,utf-8;q=0.7,*;q=0.3rnAccept-Encoding:gzip,deflate,sdchrnAccept-Language:zh-CN,zh;q=0.8rnConnection:keep-alivernContent-Length:46rnContent-Type:application/jsonrnCookie:JSESSIONID=C179D89BFBA8D7C5DCB9FCFBBB9A7932; ext-stateGrid=o%3Acolumns%3Da%253Ao%25253Aid%25253Ds%2525253Ah1%255Eo%25253Aid%25253Ds%2525253Ah2%255Eo%25253Aid%25253Ds%2525253Ah3%255Eo%25253Aid%25253Ds%2525253Ah4%255Eo%25253Aid%25253Ds%2525253Ah5%255Eo%25253Aid%25253Ds%2525253Ah6rnHost:localhost:8080rnOrigin:http://localhost:8080rnReferer:http://localhost:8080/SMS/index.jsprnUser-Agent:Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.89 Safari/537.1rnX-Requested-With:XMLHttpRequestrnrn携带的查询参数(ExtJs自己生成的)rn_dc:1348753949136rn如下便是更改后的记录(json格式)rnRequest Payloadrn"id":1,"name":"Kate","email":"ed@sencha.com"rnrn我的问题是:rn后台如何通过HttpServletRequest获取呢?即,如何获取请求中的Request Payload内容?相关的json包及依赖包都已经导入。rn在此致谢。 论坛

后台向前台传入json数据后解析问题

05-25

[code=java]Map >goodsMap=goodsService.getAllImgBygoodsId(Integer.parseInt(goods_id)); rn PrintWriter out =response.getWriter();rn out.print(JSON.toJSONString(goodsMap));[/code]rn[code=javascript]success :function(data)rn alert(data);rn $(".cd-quick-view").empty();rn var returnData = eval(data);rn $.each(returnData,function(index,value) rn var $link1 =$(" "); rn var $link2 =$(" ");rn $link1.append($link2); rn $.each(value.value,function(index,value)rn var $link3 =$(" ");rn var $imglist=$("");rn $imglist.attr('src',value.key.img_name);rn $link3.append($imglist);rn $link2.append($link3);rn )rn var $link4 =$(" Prev Next");rn $link.append($link4);rn rn var $link5 =$(" ");rn var $link6 =$(" "+value.key.goods_name+"");rn var $link7=$(" "+value.key.goods_info+"");rn $link5.append($link6);rn $link5.append($link7);rn var $link8 =$("");rn $link8.attr('href','#0');rn $link8.addClass("cd-close");rn $link8.html('Close');rn rn $(".cd-quick-view").append($link1);rn $(".cd-quick-view").append($link2);rn $(".cd-quick-view").append($link3);rn $(".cd-quick-view").append($link4);rn $(".cd-quick-view").append($link5);rn $(".cd-quick-view").append($link6);rn $(".cd-quick-view").append($link7);rn $(".cd-quick-view").append($link8);rn )rn ,[/code]rn这是我一次rn"collect_count":30,"comment_count":200,"goods_name":"2","goods_price":"20","id":2,"sale_count":40,"stype_id":1:["goods_id":2,"id":2,"img_name":"banma.jpg","goods_id":2,"id":8,"img_name":"banma.jpg"] 论坛

ASP.NET中前台 js远程获取json数据返回值问题

10-12

在控制台输入:rnrnrnvar json = $.getJSON("http://192.168.0.124:1117/zhidanServices/ShangjianAjax.svc/getShangjianGoods?billno=16034757052&voyageno=00007181&jsoncallback=?");rnrn返回的是rn:Objectrnabort: function ( statusText ) rnalways: function () rncomplete: function () rndone: function () rnerror: function () rnfail: function () rngetAllResponseHeaders: function () rngetResponseHeader: function ( key ) rnoverrideMimeType: function ( type ) rnpipe: function ( /* fnDone, fnFail, fnProgress */ ) rnprogress: function () rnpromise: function ( obj ) rnreadyState: 4rnsetRequestHeader: function ( name, value ) rnstate: function () rnstatus: 200rnstatusCode: function ( map ) rnstatusText: "success"rnsuccess: function () rnthen: function ( /* fnDone, fnFail, fnProgress */ ) rn__proto__: Objectrnrnrnrn在控制台输入rnjsonxml = "billno": "16034757052", "shipname": "00007181", "GoodList": [ "serialno": 0, "hsNo": "6404200000", "produceCountryNo": "380", "quantityUnit": "", "valueType": "156", "weightUnit": "035", "packType1": "4M", "goodsNameCn": "男式皮鞋", "quantity": "", "goodsValue": "461520.00", "netWeight": "121.96000", "grossWeight": "", "specification": "", "wasteFlag": "N" , "serialno": 0, "hsNo": "6403590090", "produceCountryNo": "380", "quantityUnit": "", "valueType": "156", "weightUnit": "035", "packType1": "4M", "goodsNameCn": "女式高跟鞋", "quantity": "", "goodsValue": "193115.00", "netWeight": "51.42400", "grossWeight": "", "specification": "", "wasteFlag": "N"] ;rnrn返回:ObjectrnGoodList: Array[2]rn0: ObjectrngoodsNameCn: "男式皮鞋"rngoodsValue: "461520.00"rngrossWeight: ""rnhsNo: "6404200000"rnnetWeight: "121.96000"rnpackType1: "4M"rnproduceCountryNo: "380"rnquantity: ""rnquantityUnit: ""rnserialno: 0rnspecification: ""rnvalueType: "156"rnwasteFlag: "N"rnweightUnit: "035"rn__proto__: Objectrn1: Objectrnlength: 2rn__proto__: Array[0]rnbillno: "16034757052"rnshipname: "00007181"rn__proto__: Objectrnrnrn下面的jsonxml是从那个网址获得json数据。rnrn我现在在js中要用那个网址获取json绑定在jqGrid上。直接写json可以显示,用那个网址获取就没有数据,向大神求救。。。我也不知道我有多少分,您就当自己是活雷锋吧。。。 论坛

没有更多推荐了,返回首页