json_ajax提交json格式数据到servlet并解析

jsp页面将将表单数据转换为json格式

需要依赖的两个js文件(本次实践基于jquery):

网址:http://code.google.com/p/jquery-json/

网址:http://jquery.com/download/

js

$.fn.serializeObject = function () {
			var o = {};
			var a = this.serializeArray();
			$.each(a, function () {
			if (o[this.name]) {
				if (!o[this.name].push) {
						o[this.name] = [o[this.name]];
					}
					o[this.name].push(this.value || "");
				} else {
				o[this.name] = this.value || "";
				}
			});
			return o;
		};

ajax

var comment = $.toJSON($("form").serializeObject());
			$.ajax({
				type:"POST",
				contentType:"application/json",
				url:"comment.do",
				data:comment,
				dataType:"json",
				success:function(data){
					//window.location.href = "showProduct.do";
					$(":radio").removeAttr("checked");
					$(":text").val("");
					$("textarea").val("");
				},
				error:function(){
					alert("系统异常");
				},
				async:true
			});

jsp:

<form action="" method="post">
		<input type="hidden" value="${requestScope.productId }" name="productId">
		<label>评分:</label>
		<input type="radio" value="5" name="score">(很喜欢)	
		<input type="radio" value="4" name="score">(喜欢)	
		<input type="radio" value="3" name="score">(一般)	
		<input type="radio" value="2" name="score">(不喜欢)	
		<input type="radio" value="1" name="score">(很不喜欢)
		<br/>
		<label>标题:</label>
		<input type="text" size="80" name="subject">
		<br/>
		<label>正文:</label>
		<textarea rows="20" cols="70" name="content"></textarea>
		<br/>		
		<input type="button" value="提交">
	</form>

servlet:

servlet将前台页面的json数据

1.转换为json字符串

2.将json字符串转换为json对象

3.取出json对象中的值

需要依赖


 public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        String action = request.getRequestURI();
        String url = action.substring(action.lastIndexOf("/"),action.lastIndexOf(".do"));
	if(url.equals("/comment")){
            response.setContentType("application/json;charset=UTF-8");
            //接受前台页面ajax传输过来的json格式数据解析成json字符串
            String content = readContent(request);
            //将json字符串转换为json对象
            JSONObject jsonObject = null;
            try {
                jsonObject = new JSONObject(content);
                Comment comment = new Comment();
                comment.setSubject(jsonObject.getString("subject"));
                comment.setContent(jsonObject.getString("content"));
                comment.setScore(jsonObject.getInt("score"));
                comment.setProductId(jsonObject.getInt("productId"));
                comment.setTime(getTime());
                comment.setUserId(1);
                //用户信息,在用户登陆之后,就保存在session中,userId可以直接从session中获取
                //这里模拟一个数据
                Integer count = commentService.comment(comment);
                if(count == null){
                    //response.sendRedirect("/Comment/error.jsp");
                }else{
                    //response.sendRedirect("/Comment/showProduct.do");
                    objectMapper.writeValue(response.getOutputStream(), comment);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
       }
}
 private String readContent(HttpServletRequest request){
        StringBuffer json = new StringBuffer();
        String line = null;
        try {
            BufferedReader reader = request.getReader();
            while((line = reader.readLine()) != null){
                json.append(line);
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        return json.toString();
    }


以上实现从jsp页面传输json格式数据到后台,接受并解析。



  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值