Natural

 

jsp内嵌google天气

做网站的时候有时需要个天气预报的功能。可以利用google的api来获取目标城市的天气预报。。
常用的做法是先获取天气的xml存到本地,再解析出当天的日期显示到页面上。

获取天气的bean
 1 package com.company.utils;
 2 
 3 import java.io.BufferedReader;
 4 import java.io.BufferedWriter;
 5 import java.io.File;
 6 import java.io.FileOutputStream;
 7 import java.io.IOException;
 8 import java.io.InputStream;
 9 import java.io.InputStreamReader;
10 import java.io.OutputStreamWriter;
11 import java.io.Writer;
12 import java.net.URL;
13 
14 import javax.xml.parsers.DocumentBuilder;
15 import javax.xml.parsers.DocumentBuilderFactory;
16 
17 import org.w3c.dom.Document;
18 import org.w3c.dom.NodeList;
19 
20 public class GetWeather {
21 
22     /**
23      * 传入选入的城市
24      */
25     public String getWeather(String cityName, String fileAddr) {
26         // 获取google上的天气情况,写入文件
27         try {
28             URL url = new URL("http://www.google.com/ig/api?hl=zh_cn&weather="
29                     + cityName);
30             InputStream inputstream = url.openStream();
31             String s, str;
32             BufferedReader in = new BufferedReader(new InputStreamReader(inputstream));
33             StringBuffer stringbuffer = new StringBuffer();
34             Writer out = new BufferedWriter(new OutputStreamWriter(
35                     new FileOutputStream(fileAddr), "utf-8"));
36             while ((s = in.readLine()) != null) {
37                 stringbuffer.append(s);
38             }
39             str = new String(stringbuffer);
40             out.write(str);
41             out.close();
42             in.close();
43         } catch (IOException e) {
44             e.printStackTrace();
45         }
46 
47         // 读取需要的数据
48         File file = new File(fileAddr);
49         DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
50         String str = null;
51         try {
52             DocumentBuilder builder = factory.newDocumentBuilder();
53             Document doc = builder.parse(file);
54             NodeList nodelist1 = (NodeList) doc.getElementsByTagName("forecast_conditions");
55             NodeList nodelist2 = nodelist1.item(0).getChildNodes();
56             str = nodelist2.item(4).getAttributes().item(0).getNodeValue()
57                     + ",温度:"
58                     + nodelist2.item(1).getAttributes().item(0).getNodeValue()
59                     + "℃-"
60                     + nodelist2.item(2).getAttributes().item(0).getNodeValue()
61                     + "";
62         } catch (Exception e) {
63             e.printStackTrace();
64         }
65         return str;
66     }
67     
68 }
69 

利用servlet来获取目标城市的天气。google的天气api是用城市名的拼音。
当然,xml的存储路径可以用request获取web应用的根目录,存到应用的根目录上去。毕竟linux系统是没有C盘的……
 1 package com.company.servlet;
 2 
 3 import java.io.IOException;
 4 import java.io.PrintWriter;
 5 import java.text.DateFormat;
 6 
 7 import javax.servlet.ServletException;
 8 import javax.servlet.ServletOutputStream;
 9 import javax.servlet.http.HttpServlet;
10 import javax.servlet.http.HttpServletRequest;
11 import javax.servlet.http.HttpServletResponse;
12 
13 import com.company.utils.GetWeather;
14 
15 public class servletWeather extends HttpServlet {
16 
17 
18     private static final String APP_TODAY_WEATHER = "app_today_weather";    //applcation中的天气属性名
19     private static final String cityName = "hangzhou";                        //天气预报对象——城市名(用拼音)
20     private static final String cityName_ZH = "杭州";                        //天气预报对象——城市名(中文)
21     private static final String fileAddr = "C:/" + cityName + ".xml";        //用来存储天气预报的xml文件的路径名
22     
23     protected void processRequest(HttpServletRequest request,
24                                   HttpServletResponse response) throws
25         ServletException, IOException {
26         response.setContentType("text/html;charset=utf-8");
27         
28         //获取今天的日期
29         java.util.Date nowDate = new java.util.Date();
30         DateFormat dateformat = DateFormat.getDateInstance();
31         String todayDate = dateformat.format(nowDate);
32         
33         
34         // 获取application中存储的天气
35         String today_weather = (String)request.getSession().getServletContext().getAttribute(APP_TODAY_WEATHER);
36         
37         // 如果application中存储的天气为空,则重新获取一下;并存到application中
38         if(today_weather == null || "".equals(today_weather))
39         {    
40             today_weather = getTodayWeather();
41             today_weather = todayDate + " " + cityName_ZH + " " + today_weather;
42             request.getSession().getServletContext().setAttribute(APP_TODAY_WEATHER, today_weather);
43         }
44         else
45         {    // 如果application中存储的天气不是今天的,则重新获取一下;并存到application中
46             int flag = today_weather.indexOf(todayDate);
47             if(flag < 0)
48             {
49                 today_weather = getTodayWeather();
50                 today_weather = todayDate + " " + cityName_ZH + " " + today_weather;
51                 request.getSession().getServletContext().setAttribute(APP_TODAY_WEATHER, today_weather);
52             }
53         }
54 
55         PrintWriter responsePrintWriter = response.getWriter();
56         
57         // 输出天气(字符串)到页面
58         responsePrintWriter.write(today_weather);
59         
60         //以下关闭输入流!
61         responsePrintWriter.flush();
62         responsePrintWriter.close();
63     }
64     
65     /**
66      * 获取今天的天气
67      * @return String
68      */
69     public String getTodayWeather()
70     {
71         GetWeather ggw = new GetWeather();
72         return ggw.getWeather(cityName, fileAddr);
73     }
74 
75     protected void doGet(HttpServletRequest request,
76                          HttpServletResponse response) throws ServletException,
77         IOException {
78         processRequest(request, response);
79     }
80 
81     protected void doPost(HttpServletRequest request,
82                           HttpServletResponse response) throws ServletException,
83         IOException {
84         processRequest(request, response);
85     }
86 
87 }
88 



web.xml中需要配置一下servlet
<servlet>
    
<servlet-name>servletWeather</servlet-name>
    
<servlet-class>com.company.servlet.servletWeather</servlet-class>
</servlet>
<servlet-mapping>
    
<servlet-name>servletWeather</servlet-name>
    
<url-pattern>/servletWeather</url-pattern>
</servlet-mapping>

ok,只要在jsp页面调用一下这个servlet就好了
<div>
<iframe frameborder="0"  src="servletWeather"></iframe>
</div>



posted on 2010-03-24 22:11 此号已被删 阅读(908) 评论(0)  编辑  收藏 所属分类: J2EE


只有注册用户登录后才能发表评论。


网站导航:
 

导航

统计

常用链接

留言簿(8)

随笔分类(83)

随笔档案(78)

文章档案(2)

相册

收藏夹(7)

最新随笔

搜索

积分与排名

最新评论

阅读排行榜

评论排行榜