📅  最后修改于: 2021-01-02 12:53:27             🧑  作者: Mango
JSON(JavaScript对象表示法)是一种与语言无关的数据格式。它与XML类似,因为XML使用标签JSON使用JavaScript的对象-语言表示法。
实作
创建一个Stock Exchange的JSON数据源示例:
我们已经实现了股票价格类别并刷新监视列表方法为:
/**
* Generate random stock prices.
*/
private void refreshWatchList() {
final double MAX_PRICE = 100.0; // $100.00
final double MAX_PRICE_CHANGE = 0.02; // +/- 2%
StockPrice[] prices = new StockPrice[stocks.size()];
for (int i = 0; i < stocks.size(); i++) {
double price = Random.nextDouble() * MAX_PRICE;
double change = price * MAX_PRICE_CHANGE
* (Random.nextDouble() * 2.0 - 1.0);
prices[i] = new StockPrice(stocks.get(i), price, change);
}
updateTable(prices);
}
在此,我们为JSON格式的股票报价创建一个servlet文件。以下是创建servlet的步骤:
1)创建一个Servlet
2)在Package下,将名称从.client更改为.server
3)用以下代码替换存根:
package com.google.gwt.sample.stockexchange.server;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class JsonStockData extends HttpServlet {
private static final double MAX_PRICE = 100.0; // $100.00
private static final double MAX_PRICE_CHANGE = 0.02; // +/- 2%
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
Random rnd = new Random();
PrintWriter out = resp.getWriter();
out.println('[');
String[] stockSymbols = req.getParameter("q").split(" ");
boolean firstSymbol = true;
for (String stockSymbol : stockSymbols) {
double price = rnd.nextDouble() * MAX_PRICE;
double change = price * MAX_PRICE_CHANGE * (rnd.nextDouble() * 2f - 1f);
if (firstSymbol) {
firstSymbol = false;
} else {
out.println(" ,");
}
out.println(" {");
out.print(" \"symbol\": \"");
out.print(stockSymbol);
out.println("\",");
out.print(" \"price\": ");
out.print(price);
out.println(',');
out.print(" \"change\": ");
out.println(change);
out.println(" }");
}
out.println(']');
out.flush();
}
}
GWT由内部构建servlet容器Jetty组成,该容器托管以JSON格式生成库存数据的servlet。在GWT中包括服务器端代码的步骤是:
StockExchange.html
jsonStockData
com.google.gwt.sample.stockexchange.server.JsonStockData
jsonStockData
/stockexchange/stockPrices