用http://localhost:8080/testQueryStringJson/queryStringJ?miGuo=bama&xigongDa=liusir访问,输出:
INFO: Client is using QueryString[miGuo=bama&xigongDa=liusir]
{"miGuo":"bama","xigongDa":"liusir"}
import java.util.logging.Logger;
import java.io.IOException;
import java.util.logging.Level;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.JSONException;
import org.json.JSONObject;
/**
* Servlet implementation class queryStringJ
*/
@WebServlet("/queryStringJ")
public class queryStringJ extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final Logger LOGGER = Logger.getLogger(queryStringJ.class.getName());
/**
* @see HttpServlet#HttpServlet()
*/
public queryStringJ() {
super();
// TODO Auto-generated constructor stub
}
private JSONObject getQueryStringJSONObject(final HttpServletRequest request) throws JSONException {
JSONObject ret = null;
final String tmp = request.getQueryString();
if (null == tmp) {
return new JSONObject();
}
LOGGER.log(Level.INFO, "Client is using QueryString[{0}]", tmp);
final StringBuilder sb = new StringBuilder();
sb.append("{");
final String[] split = tmp.split("&");
for (int i = 0; i < split.length; i++) {
final String query = split[i];
final String[] kv = query.split("=");
if (kv.length != 2) {
return new JSONObject();
}
final String key = kv[0];
final String value = kv[1];
sb.append("\"");
sb.append(key);
sb.append("\":");
sb.append("\"");
sb.append(value);
sb.append("\"");
if (i < split.length - 1) {
sb.append(",");
}
}
sb.append("}");
ret = new JSONObject(sb.toString());
return ret;
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
try {
System.out.println(getQueryStringJSONObject(request));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
源代码:
http://pan.baidu.com/share/link?shareid=3303218273&uk=3878681452