一.要求在網(wǎng)頁(yè)上顯示輸入框,根據(jù)用戶(hù)輸入的城市獲取該城市的天氣預(yù)報(bào)拔鹰,然后顯示在該網(wǎng)頁(yè)上贵涵。
二.遇到的問(wèn)題
當(dāng)要讀取的天氣情況的文檔位于本地計(jì)算機(jī)時(shí),可以回顯天氣情況例书,但是當(dāng)動(dòng)態(tài)的從網(wǎng)上獲取并回顯時(shí)刻炒,由于無(wú)法跨域訪問(wèn)數(shù)據(jù)自沧,不能回顯在網(wǎng)頁(yè)上。
三.解決辦法(兩種)
1.使用雅虎推出的一種類(lèi)似 SQL 的查詢(xún)語(yǔ)言YQL來(lái)查詢(xún)天氣情況爱谁,它的原理就是目前在Web上面已經(jīng)有很多結(jié)構(gòu)化數(shù)據(jù)可以供開(kāi)發(fā)人員來(lái)使用孝偎。但是使用這些數(shù)據(jù),要求對(duì)數(shù)據(jù)的請(qǐng)求和響應(yīng)格式有一定的了解寺旺。不同服務(wù)提供者所采用的數(shù)據(jù)格式是不同的势决。YQL 是雅虎提供的一種類(lèi)似 SQL 的查詢(xún)語(yǔ)言,通過(guò)它可以把數(shù)據(jù)服務(wù)作為數(shù)據(jù)庫(kù)表來(lái)查詢(xún)陈莽,并獲得結(jié)果虽抄。YQL 服務(wù)的輸入是使用者提供的 YQL 語(yǔ)句。YQL 服務(wù)解析 YQL 語(yǔ)句私植,然后調(diào)用后臺(tái)真實(shí)的 Web 服務(wù)并獲取結(jié)果菠隆。后臺(tái) Web 服務(wù)的結(jié)果以 XML 或是 JSON 的格式返回給 YQL 服務(wù)的使用者(具體見(jiàn)下圖)狂秘,然后我們將所得的結(jié)果轉(zhuǎn)換為xml對(duì)象躯肌,通過(guò)解析xml對(duì)象將天氣情況回顯在網(wǎng)頁(yè)上。
2.通過(guò)java中mvc框架來(lái)解決钱烟,可以在后臺(tái)建立控制類(lèi)拴袭,通過(guò)控制類(lèi)去抓取目標(biāo)網(wǎng)頁(yè)上的內(nèi)容曙博,然后將它返回前端,前段將后臺(tái)返回的內(nèi)容轉(zhuǎn)換為xml對(duì)象般哼,通過(guò)解析xml對(duì)象回顯目標(biāo)城市的天氣情況惠窄,原理如下:
四.具體實(shí)現(xiàn)
1.YQL查詢(xún)語(yǔ)言實(shí)現(xiàn)
<html>
<meta http-equiv="Access-Control-Allow-Origin" content="*" />
<script src="js/jquery-1.4.2.min.js"></script>
<body>
<label>城市</label>
<input id="city" type="text">
<input type="submit" value="查詢(xún)" onclick="fun()">
<h1>W3School.com.cn Internal Note</h1>
<p><b>city:</b> <span id="to"></span><br />
<b>time:</b> <span id="from"></span><br />
<b>wendu:</b> <span id="message"></span><br />
<b>suggest:</b> <span id="suggest"></span><br />
</body>
<script type="text/javascript">
function fun(){
var city=document.getElementById("city").value;
var site = 'http://www.sojson.com/open/api/weather/xml.shtml?city='+city;
var yql = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent('select * from xml where url="' + site + '"') + '&format=xml&callback=?';
$.getJSON(yql, function (data) {
console.log(data);
var xmlDoc = (new DOMParser()).parseFromString(data.results[0],"text/xml");
document.getElementById("to").innerHTML=
xmlDoc.getElementsByTagName("city")[0].childNodes[0].nodeValue;
document.getElementById("from").innerHTML=
xmlDoc.getElementsByTagName("updatetime")[0].childNodes[0].nodeValue;
document.getElementById("message").innerHTML=
xmlDoc.getElementsByTagName("wendu")[0].childNodes[0].nodeValue;
document.getElementById("suggest").innerHTML=
xmlDoc.getElementsByTagName("environment")[0].getElementsByTagName("suggest")[0].childNodes[0].nodeValue;
});
}
</script>
</html>
2.java中mvc框架實(shí)現(xiàn)
①前端視圖
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<label>城市</label>
<input id="city" type="text">
<input type="submit" value="查詢(xún)" onclick="fun()">
<h1>W3School.com.cn Internal Note</h1>
<p><b>city:</b> <span id="to"></span><br />
<b>time:</b> <span id="from"></span><br />
<b>wendu:</b> <span id="message"></span><br />
<b>suggest:</b> <span id="suggest"></span><br />
</body>
<script type="text/javascript">
function fun(){
var city=document.getElementById("city").value;
window.location.href="<%=request.getContextPath()%>/WeatherServlet?city="+city;
}
var xmlDoc = (new DOMParser()).parseFromString('<%=request.getAttribute("weather") %>',"text/xml");
alert('<%=request.getAttribute("weather")%>');
document.getElementById("to").innerHTML=
xmlDoc.getElementsByTagName("city")[0].childNodes[0].nodeValue;
document.getElementById("from").innerHTML=
xmlDoc.getElementsByTagName("updatetime")[0].childNodes[0].nodeValue;
document.getElementById("message").innerHTML=
xmlDoc.getElementsByTagName("wendu")[0].childNodes[0].nodeValue;
document.getElementById("suggest").innerHTML=
xmlDoc.getElementsByTagName("environment")[0].getElementsByTagName("suggest")[0].childNodes[0].nodeValue;
</script>
</html>
②后臺(tái)控制類(lèi)
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Scanner;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class WeatherServlet
*/
@WebServlet("/WeatherServlet")
public class WeatherServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
String city = request.getParameter("city");
//參數(shù)url化
city = java.net.URLEncoder.encode(city, "utf-8");
String apiUrl = String.format("http://www.sojson.com/open/api/weather/xml.shtml?city=%s",city);
//開(kāi)始請(qǐng)求
URL url= new URL(apiUrl);
URLConnection open = url.openConnection();
InputStream input = open.getInputStream();
//這里轉(zhuǎn)換為String,帶上包名蒋腮,怕你們引錯(cuò)包
Scanner scan=new Scanner(input,"utf-8");
String result=scan.useDelimiter("\\A").next();
//輸出
request.setAttribute("weather", result);
System.out.println(result);
request.getRequestDispatcher("/1.jsp").forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
五.運(yùn)行截圖