您的位置:首页 > Web前端 > JavaScript

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

2013-04-19 14:05 507 查看
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格式数据到后台,接受并解析。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: