上一篇【http://www.jb51.cc/article/p-zimsebhc-bpe.html】的讲解传到后台的参数形式为username=yanshi02&password=123456 字符串。
那么如果传到后台的格式是JSON呢?
queryString = $('#editform').serializeArray();//object
queryString = JSON.stringify(queryString);//string
$.get(url,queryString,function(data){});
【JSP页面】
发送到服务器的数据作为查询字符串附加到 URL 之后。
如果 data 参数的值是对象(映射),那么在附加到 URL 之前将转换为字符串,并进行 URL 编码。
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'post.jsp' starting page</title>
<Meta http-equiv="pragma" content="no-cache">
<Meta http-equiv="cache-control" content="no-cache">
<Meta http-equiv="expires" content="0">
<Meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<Meta http-equiv="description" content="This is my page">
<!-- <link rel="stylesheet" type="text/css" href="styles.css"> -->
<script type="text/javascript" src="./scripts/jquery-1.7.2.js"></script>
<script type="text/javascript"> var url =""; var queryString = ""; $(function(){ $("input[type='button']").click(function(){ url = $("#editform").attr("action"); //queryString = $('#editform').serialize(); queryString = $('#editform').serializeArray(); queryString = JSON.stringify(queryString);//string $.get(url,function(data){ alert(data); },"json"); }); }); </script>
</head>
<body>
This is my JSP page. <br>
<form id="editform" action="getServlet2" method="get">
<input type="text" name="username" value=""/>
<input type="password" name="password" value=""/>
</form>
<input name="post" type="button" value="提交"/>
</body>
</html>
思路:
使用request.getQueryString();
获取传输的数据。
因为是JSON形式,所以不适宜用request.getParameterMap
;
因为是 get 请求,数据都在Query String Parameters 里面,不能使用request.getReader
;
package com.atgui.ajax.app.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.util.HashMap;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.codehaus.jackson.map.ObjectMapper;
public class GetServlet2 extends HttpServlet {
/** * Destruction of the servlet. <br> */
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException {
doPost(request,response);
}
public void doPost(HttpServletRequest request,IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
//拿到$("#editform").serialize();
String jsonString =request.getQueryString() ;
System.out.println(jsonString);
//进行解码,否则会有大量转译字符,如%22%23
String jsonString2 = URLDecoder.decode(jsonString.toString(),"UTF-8");
System.out.println(jsonString2);
ObjectMapper objectMapper = new ObjectMapper();
String resultJson = objectMapper.writeValueAsString(jsonString2);
System.out.println("resultJson ..."+resultJson);
out.print(resultJson);
out.flush();
out.close();
}
public void init() throws ServletException {
// Put your code here
System.out.println("getServlet init()....");
}
}
result as follows :
//servlet初始化
getServlet init()....
//获取的string,有大量转译字符
[{%22name%22:%22username%22,%22value%22:%22yanshi02%22},{%22name%22:%22password%22,%22value%22:%22123456%22}]
//解码后的字符串
[{"name":"username","value":"yanshi02"},{"name":"password","value":"123456"}]
//返回的json
resultJson ..."[{\"name\":\"username\",\"value\":\"yanshi02\"},{\"name\":\"password\",\"value\":\"123456\"}]"
如果直接返回jsonString2 (typeof data=object) JSP页面可以直接遍历该json 数组,不用解析;
如果返回resultJson(typeof data=string) JSP页面不可以直接遍历该json 数组,需要解析为json object 才能遍历;
题外话:
如果请求格式为$.get(url,{mydata:queryString},function(data){});
呢?
首先看大图:
发送到服务器的数据作为查询字符串附加到 URL 之后。
- 如果 data 参数的值是对象(映射),那么在附加到 URL 之前将转换为字符串,并进行 URL 编码。
数据在 Query String Parameters 里面!
一般有两种思路:
① 使用request.getParameterMap
;【只要为{key:value},就可以处理】
多用在`username=yanshi02&password=123456`形式中。 事实上,如果使用参数格式为{mydata:jsonstring},使用该方法比较麻烦。 需要再次从map中获取jsonstring,然后适当进行解析。
package com.atgui.ajax.app.servlet;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.codehaus.jackson.map.ObjectMapper;
public class GetServlet4 extends HttpServlet {
/** * request.getParameterMap(); */
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
System.out.println("postServlet2 destroy() ......");
}
public void doGet(HttpServletRequest request,IOException {
response.setContentType("application/json");
PrintWriter out = response.getWriter();
Map<String,String[]> map = request.getParameterMap();
for(String key : map.keySet()){
for (int i = 0; i < map.get(key).length; i++) {
System.out.println("key :"+key+","+i+","+map.get(key)[i]);
}
}
String jsonString = map.get("mydata")[0];
System.out.println("jsonString :"+jsonString);
ObjectMapper objectMapper = new ObjectMapper();
String resultJson = objectMapper.writeValueAsString(jsonString);
System.out.println("resultJson: "+resultJson);
// 此时为json object,jsp页面可直接使用data.key获取json属性
out.print(jsonString);
out.flush();
out.close();
}
public void init() throws ServletException {
// Put your code here
System.out.println("GetServlet4 init().......");
}
}
- result as follows :
key :mydata,0,[{"name":"username","value":"admin"},"value":"123456"}]
jsonString :[{"name":"username","value":"123456"}]
resultJson: "[{\"name\":\"username\",\"value\":\"admin\"},{\"name\":\"password\",\"value\":\"123456\"}]"
如果直接返回jsonString (typeof data =object )可以直接使用data.key 获取json对象属性或者进行json 数组遍历!
如果返回resultJson(typeof data =string )。。。最终将以字符数组的形式进行遍历!!!
② 使用 request.getQueryString
;
其实仍旧需要再次解析!解析之后的jsonString 可以直接返回(typeof data = object)! 如果再次使用objectMapper进行转换,那么最终将以字符数组的形式进行遍历!!!
附结果如下:
//获取的string----浏览器会进行URL编码
mydata=%5B%7B%22name%22%3A%22username%22%2C%22value%22%3A%22yanshi02%22%7D%2C%7B%22name%22%3A%22password%22%2C%22value%22%3A%22123456%22%7D%5D
//解码后的string
mydata=[{"name":"username","value":"123456"}]
//返回的json
resultJson ..."mydata=[{\"name\":\"username\",\"value\":\"123456\"}]"
只要可以拿到字符串,就可以转换为json,至于返回的是json object 还是json string ,视情况而定。!
第三种思路 !!!
原文链接:https://www.f2er.com/ajax/161434.html