JSONP跨域

1.服务端
public class ServletTest extends HttpServlet {
	public void init() throws ServletException {

	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 获得客户端请求的方法
		String method = request.getParameter("method");
		if (method.equals("getInfo")) {
			getXXXInfo(request, response);
		}
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

	}

	public void getXXXInfo(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        String id = request.getParameter("id");
        JSONObject json = new JSONObject();
        // 得到结果集result拼成json
        for(int i = 0; i < result.size(); i++){
            HashMap hm = new HashMap();
            // 把要用到的信息放到hm中
              hm.put("title",result.get("title"));
            ...
            json.put(new Integer(i), hm);
        }

        String output = json.toString();
        response.setContentType("text/html;charset=GBK");
        response.getWriter().print(output);
    }
}


2.客户端
package com.bennett;

public class RemoteJson {
	public static String url = Configuration.getProperty("sys.url");

	public static ArrayList getXXXInfo(String id) throws IOException,
			JSONException {
		InputStream is = new URL(url + "/www/api/api.api?method=getInfo&id="
				+ id).openStream();
		try {
			ArrayList al = new ArrayList();
			BufferedReader rd = new BufferedReader(new InputStreamReader(is,
					Charset.forName("GBK")));
			String jsonText = readAll(rd);
			JSONObject json = JSONObject.fromObject(jsonText);
			for (int i = 0; i < json.size(); i++) {
				JSONObject jsonrow = JSONObject.fromObject(json.get(String
						.valueOf(i)));
				HashMap hm = new HashMap();
				hm.put("title", jsonrow.get("title"));
				...
				al.add(i, hm);
			}
			return al;
		} finally {
			is.close();
		}
	}

	private static String readAll(Reader rd) throws IOException {
		StringBuilder sb = new StringBuilder();
		int cp;
		while ((cp = rd.read()) != -1) {
			sb.append((char) cp);
		}
		return sb.toString();
	}

	public static JSONObject readJsonFromUrl(String url) throws IOException,
			JSONException {
		InputStream is = new URL(url).openStream();
		try {
			BufferedReader rd = new BufferedReader(new InputStreamReader(is,
					Charset.forName("UTF-8")));
			String jsonText = readAll(rd);
			JSONObject json = JSONObject.fromObject(jsonText);
			return json;
		} finally {
			is.close();
		}
	}
}


3.web.xml
<servlet-mapping>
    <servlet-name>ServletTest</servlet-name>
    <url-pattern>/api/api.api</url-pattern>
</servlet-mapping> 

你可能感兴趣的:(jsonp)