`
javaeye_hua
  • 浏览: 82232 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

web service + jsp 实现天气预报功能

阅读更多

今天下午,着手制作了一个天气预报调用模块,采用SOAP + WEBSERVICE + JAVA + JSP实现,具体如下:

/**
 * 
 */
package com.hnwater.business.weather;

import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Hashtable;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 * @author hxb
 *
 */
public class WeatherUtil {

	private String encoding = "GBK";
	private String webServiceUrl = "http://www.webxml.com.cn/WebServices/WeatherWebService.asmx";
	
	
	/**
	 * @return get instance of WeatherUtil
	 */
	public static WeatherUtil getInstance(){
		return new WeatherUtil();
	}
	
	/**   
     * 获取SOAP的请求头,并替换其中的标志符号为用户输入的城市   
     * @param city用户输入的城市名称   
     * @return 客户将要发送给服务器的SOAP请求   
     */   
    private String getSoapRequest(String city) {    
        StringBuilder sb = new StringBuilder();    
        sb.append("<?xml version=\"1.0\" encoding=\"" + encoding + "\"?>");
        sb.append("<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" ");
        sb.append("xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" ");
        sb.append("xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">");
        sb.append("<soap:Body>");
        sb.append("<getWeatherbyCityName xmlns=\"http://WebXml.com.cn/\">");
        sb.append("<theCityName>");
        sb.append(city);
        sb.append("</theCityName>");
        sb.append("</getWeatherbyCityName>");
        sb.append("</soap:Body>");
        sb.append("</soap:Envelope>");    
        return sb.toString();    
    }   
    /**   
     * 用户把SOAP请求发送给服务器端,并返回服务器点返回的输入流   
     * @param city用户输入的城市名称   
     * @return 服务器端返回的输入流,供客户端读取   
     * @throws Exception   
     */   
    private InputStream getSoapInputStream(String city) throws Exception {    
        try {    
            String soap = getSoapRequest(city);    
            if (soap == null) {    
                return null;    
            }    
            URL url = new URL(webServiceUrl);    
            URLConnection conn = url.openConnection();    
            conn.setUseCaches(false);    
            conn.setDoInput(true);    
            conn.setDoOutput(true);    
   
            conn.setRequestProperty("Content-Length", Integer.toString(soap    
                    .length()));    
            conn.setRequestProperty("Content-Type", "text/xml; charset=" + encoding);    
            conn.setRequestProperty("SOAPAction",    
                    "http://WebXml.com.cn/getWeatherbyCityName");    
   
            OutputStream os = conn.getOutputStream();    
            OutputStreamWriter osw = new OutputStreamWriter(os, encoding);    
            osw.write(soap);    
            osw.flush();    
            osw.close();    
   
            InputStream is = conn.getInputStream();    
            return is;    
        } catch (Exception e) {    
            e.printStackTrace();    
            return null;    
        }    
    }   
    /**   
     * 对服务器端返回的XML进行解析   
     * @param city 用户输入的城市名称   
     * @return 字符串 用,分割   
     */   
    public Hashtable<String,Object> getWeather(String city) {
    	Hashtable<String,Object> weathers = new Hashtable<String,Object>(0);
        try {    
            Document doc = null;    
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();    
            dbf.setNamespaceAware(true);    
            DocumentBuilder db = dbf.newDocumentBuilder();    
            InputStream is = getSoapInputStream(city);    
            doc = db.parse(is);    
            NodeList nl = doc.getElementsByTagName("string");    
            for (int count = 0; count < nl.getLength(); count++) {    
                Node n = nl.item(count);
                String nv = n.getFirstChild().getNodeValue();//当前节点信息
                nv = (nv == null ? "" : nv);
                if(nv.equals("查询结果为空!")) {
                    return null;    
                }    
                if(count != 11){
                	weathers.put(WeatherObj.input.get(count), nv);
                	continue;
                }
                if(count == 11){
                	this.analyzedZhiShu(weathers, 11,nv);
                }
            }    
            is.close();    
            
            return weathers;
            
        } catch (Exception e) {    
            e.printStackTrace();    
            return null;    
        }    
    }
    /**
     * @param weathers
     * @param indexId
     * 解析各个指数信息
     */
    private boolean analyzedZhiShu(Hashtable<String,Object> weathers,int indexId,String zhiShuMess){
    	if(weathers == null || zhiShuMess == null || zhiShuMess.equals("")){
    		return false;
    	}
    	ArrayList<WeatherObj> objs = new ArrayList<WeatherObj>(0);
    	
		String s1Content = "";
		String s2Content = "";
		String s3Content = "";
		String s4Content = "";
		String s5Content = "";
		String s6Content = "";
		String s7Content = "";
		String s8Content = "";
		//这里开始进行具体详细测试
		String str = zhiShuMess;
		//穿衣指数
		s1Content = str.substring(str.indexOf(WeatherObj.CHUANYIZHISHU) + WeatherObj.CHUANYIZHISHU.length(), str.indexOf(WeatherObj.GANMAOZHISHU));
		WeatherObj obj1 = new WeatherObj();
		obj1.setName(WeatherObj.CHUANYIZHISHU);
		obj1.setMessage(s1Content);
		objs.add(obj1);
		//感冒指数
		s2Content = str.substring(str.indexOf(WeatherObj.GANMAOZHISHU) + WeatherObj.GANMAOZHISHU.length(), str.indexOf(WeatherObj.CHENLIANZHISHU));
		WeatherObj obj2 = new WeatherObj();
		obj2.setName(WeatherObj.GANMAOZHISHU);
		obj2.setMessage(s2Content);
		objs.add(obj2);
		//晨练指数
		s3Content = str.substring(str.indexOf(WeatherObj.CHENLIANZHISHU) + WeatherObj.CHENLIANZHISHU.length(), str.indexOf(WeatherObj.JIAOTONGZHISHU));
		WeatherObj obj3 = new WeatherObj();
		obj3.setName(WeatherObj.CHENLIANZHISHU);
		obj3.setMessage(s3Content);
		objs.add(obj3);
		//交通指数
		s4Content = str.substring(str.indexOf(WeatherObj.JIAOTONGZHISHU) + WeatherObj.JIAOTONGZHISHU.length(), str.indexOf(WeatherObj.LIANGSHAIZHISHU));
		WeatherObj obj4 = new WeatherObj();
		obj4.setName(WeatherObj.JIAOTONGZHISHU);
		obj4.setMessage(s4Content);
		objs.add(obj4);
		//晾晒指数
		s5Content = str.substring(str.indexOf(WeatherObj.LIANGSHAIZHISHU) + WeatherObj.LIANGSHAIZHISHU.length(), str.indexOf(WeatherObj.LVYOUZHISHU));
		WeatherObj obj5 = new WeatherObj();
		obj5.setName(WeatherObj.LIANGSHAIZHISHU);
		obj5.setMessage(s5Content);
		objs.add(obj5);
		//旅游指数
		s6Content = str.substring(str.indexOf(WeatherObj.LVYOUZHISHU) + WeatherObj.LVYOUZHISHU.length(), str.indexOf(WeatherObj.LUKUANGZHISHU));
		WeatherObj obj6 = new WeatherObj();
		obj6.setName(WeatherObj.LVYOUZHISHU);
		obj6.setMessage(s6Content);
		objs.add(obj6);
		//路况指数
		s7Content = str.substring(str.indexOf(WeatherObj.LUKUANGZHISHU) + WeatherObj.LUKUANGZHISHU.length(),str.indexOf(WeatherObj.SHUSHIDUZHISHU));
		WeatherObj obj7 = new WeatherObj();
		obj7.setName(WeatherObj.LUKUANGZHISHU);
		obj7.setMessage(s7Content);
		objs.add(obj7);
		//舒适度指数
		s8Content = str.substring(str.indexOf(WeatherObj.SHUSHIDUZHISHU) + WeatherObj.SHUSHIDUZHISHU.length());
		WeatherObj obj8 = new WeatherObj();
		obj8.setName(WeatherObj.SHUSHIDUZHISHU);
		obj8.setMessage(s8Content);
		objs.add(obj8);
    	
    	weathers.put(WeatherObj.ZHISHU, objs);
    	
    	return true;
    } 
    
    public static void main(String[] args0){
    	WeatherUtil wu = WeatherUtil.getInstance();
    	wu.getWeather("靖宇");
    }
}
/**
 * 
 */
package com.hnwater.business.weather;

import java.util.Hashtable;

/**
 * @author hxb
 *
 */
public class WeatherObj {

	public static final String REGIONFIRST = "_regionFirst";//上级行政区
	public static final String REGIONSECOND = "_regionSecond";//本级行政区
	public static final String REGIONID = "_regionId";//行政区id
	public static final String REGIONPIC = "_regionPic";//行政区图片
	public static final String REPORTTIME = "_reportTime";//最新上报时间
	public static final String TODAYTEMPERATURE = "_todayTemperature";//今天温度
	public static final String TODAYDATE = "_todayDate";//今天日期
	public static final String TODAYWIND = "_todayWind";//今天风况
	public static final String TODAYPIC_1 = "_todayPic_1";//今天天气图片1
	public static final String TODAYPIC_2 = "_todayPic_2";//今天天气图片2
	public static final String TODAYDETAIL = "_todayDetail";//今天天气实况
	public static final String ZHISHU = "_zhiShu";//各个指数
	public static final String CHUANYIZHISHU = "穿衣指数:";
	public static final String GANMAOZHISHU = "感冒指数:";
	public static final String CHENLIANZHISHU = "晨练指数:";
	public static final String JIAOTONGZHISHU = "交通指数:";
	public static final String LIANGSHAIZHISHU = "晾晒指数:";
	public static final String LVYOUZHISHU = "旅游指数:";
	public static final String LUKUANGZHISHU = "路况指数:";
	public static final String SHUSHIDUZHISHU = "舒适度指数:";
	public static final String TOMORROWTEMPERATURE = "_tomorrowTemperature";//明天温度
	public static final String TOMORROWDATE = "_tomorrowDate";//明天日期
	public static final String TOMORROWWIND = "_tomorrowWind";//明天风况
	public static final String TOMORROWPIC_1 = "_tomorrowPic_1";//明天天气图片1
	public static final String TOMORROWPIC_2 = "_tomorrowPic_2";//明天天气图片2
	public static final String AFTERTOMORROWTEMPERATURE = "_affterTomorrowTemperature";//后天温度
	public static final String AFTERTOMORROWDATE = "_affterTomorrowDate";//后天日期
	public static final String AFTERTOMORROWWIND = "_affterTomorrowWind";//后天风况
	public static final String AFTERTOMORROWPIC_1 = "_affterTomorrowPic_1";//后天天气图片1
	public static final String AFTERTOMORROWPIC_2 = "_affterTomorrowPic_2";//后天天气图片2
	public static final String DESCRIPT = "_descript";//本地介绍
	
	public static final Hashtable<Integer,String> input = new Hashtable<Integer,String>(0);//常量与数量对应
	
	static{
		input.put(0, REGIONFIRST);
		input.put(1, REGIONSECOND);
		input.put(2, REGIONID);
		input.put(3, REGIONPIC);
		input.put(4, REPORTTIME);
		
		input.put(5, TODAYTEMPERATURE);
		input.put(6, TODAYDATE);
		input.put(7, TODAYWIND);
		input.put(8, TODAYPIC_1);
		input.put(9, TODAYPIC_2);
		input.put(10, TODAYDETAIL);
		
		input.put(11, ZHISHU);
		
		input.put(12, TOMORROWTEMPERATURE);
		input.put(13, TOMORROWDATE);
		input.put(14, TOMORROWWIND);
		input.put(15, TOMORROWPIC_1);
		input.put(16, TOMORROWPIC_2);
		
		input.put(17, AFTERTOMORROWTEMPERATURE);
		input.put(18, AFTERTOMORROWDATE);
		input.put(19, AFTERTOMORROWWIND);
		input.put(20, AFTERTOMORROWPIC_1);
		input.put(21, AFTERTOMORROWPIC_2);
		
		input.put(22, DESCRIPT);
	}
	
	private String name;
	
	private String message;

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
	
	
	
}

 

<%@ page language="java" pageEncoding="GBK"%>
<%@ page import="java.util.ArrayList,java.util.Hashtable"%>
<jsp:directive.page import="com.hnwater.business.weather.WeatherObj;"/>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
	<head>
		<title>城市天气信息</title>
<%--		
	<link rel="stylesheet" type="text/css" href="../css/webstyle.css">
--%>
	</head>
<style>
body{
	font-size:12px;
}
table{
	border-collapse:sparate;
	border-spacing:0px;
}
td{
	padding:0px;
    border:0px solid #000;
    text-align:center;
    font-size:12px;
	color:#2A5CAA;
	border-color:#2A5CAA;
}
.noMess{
	text-align: center;
	text-valign: center;
}

</style>	
	<body>
<%
	String city = "白山";
	Hashtable<String,Object> weathers = com.hnwater.business.weather.WeatherUtil
		.getInstance().getWeather(city);
	if(weathers == null){					
%>
	<span class="noMess">
		暂不支持该<%=city%>地区天气预报!!!
	</span>	
<%}else{ %>
	<table border="0" cellpadding="0" cellspacing="0" width="380">
		<tr>
			<td><%=weathers.get(WeatherObj.REGIONFIRST) + " " + weathers.get(WeatherObj.REGIONSECOND)%> 72小时天气预报</td>
			<td>最新上报时间:<%=weathers.get(WeatherObj.REPORTTIME)%></td>
		</tr>
		<tr>
			<td colspan="2">
				<table border="0" cellpadding="0" cellspacing="0">
				<tr>
					<td><%=weathers.get(WeatherObj.TODAYDATE) + " " + weathers.get(WeatherObj.TODAYTEMPERATURE)%></td>
				</tr>
				<tr>
					<td><%=weathers.get(WeatherObj.TODAYWIND)%></td>
				</tr>
				<tr>
					<td>
						<img src="../images/weather/<%=weathers.get(WeatherObj.TODAYPIC_1)%>">
						&nbsp;
						<img src="../images/weather/<%=weathers.get(WeatherObj.TODAYPIC_2)%>">
					</td>
				</tr>
				<tr>
					<td><%=weathers.get(WeatherObj.TODAYDETAIL)%></td>
				</tr>
				</table>
			</td>
		</tr>
		<tr>
			<td colspan="2">
				<table border="0" cellpadding="0" cellspacing="0">
				<tr>
					<td><%=weathers.get(WeatherObj.TOMORROWDATE) + " " + weathers.get(WeatherObj.TOMORROWTEMPERATURE)%></td>
				</tr>
				<tr>
					<td><%=weathers.get(WeatherObj.TOMORROWWIND)%></td>
				</tr>
				<tr>
					<td>
						<img src="../images/weather/<%=weathers.get(WeatherObj.TOMORROWPIC_1)%>">
						&nbsp;
						<img src="../images/weather/<%=weathers.get(WeatherObj.TOMORROWPIC_2)%>">
					</td>
				</tr>
				</table>
			</td>
		</tr>
		<tr>
			<td colspan="2">
				<table border="0" cellpadding="0" cellspacing="0">
				<tr>
					<td><%=weathers.get(WeatherObj.TOMORROWDATE) + " " + weathers.get(WeatherObj.TOMORROWTEMPERATURE)%></td>
				</tr>
				<tr>
					<td><%=weathers.get(WeatherObj.TOMORROWWIND)%></td>
				</tr>
				<tr>
					<td>
						<img src="../images/weather/<%=weathers.get(WeatherObj.TOMORROWPIC_1)%>">
						&nbsp;
						<img src="../images/weather/<%=weathers.get(WeatherObj.TOMORROWPIC_2)%>">
					</td>
				</tr>
				</table>
			</td>
		</tr>
		<%
			ArrayList<WeatherObj> objs = (ArrayList<WeatherObj>)weathers.get(WeatherObj.ZHISHU);
			for(int i = 0;objs != null && i < objs.size();i++){
				WeatherObj obj = objs.get(i);
		 %>
		<tr>
			<td><%=obj.getName()%></td>
			<td><%=obj.getMessage()%></td>
		</tr>
		<%} %>
	</table>
	
	
	
	
<%} %>		
	</body>
</html>

  附件为气象信息所需图标。

6
0
分享到:
评论
1 楼 obnijeh 2009-08-07  
多谢。收藏了。有空再看看。

相关推荐

    JSP Java 调用Web Service

    JSP 调用天气预报Web服务,数据来源于中国气象局http://www.cma.gov.cn/ ,数据每2.5小时左右自动更新一次,准确可靠。包括 340 多个中国主要城市和 60 多个国外主要城市三日内的天气预报数据。

    google天气预报的实现

    在本案例中,实现Google天气预报功能主要采用了Web Service的方式进行编程。这种方式的优点在于其灵活性高,能够适应多种客户端和服务端的需求。 #### 三、技术细节 1. **HTTP请求与响应** - 实现Google天气预报...

    service 天气预报

    通过上述分析,我们了解到天气预报服务是通过特定的Web服务接口实现的,WSDL文件提供了服务的详细描述,而命名空间则在保证服务接口和数据交换的清晰性和一致性方面发挥着关键作用。在开发基于Web的服务时,理解并...

    基于webservices 航班信息查询 开题报告

    2. **天气信息**: 在实现基本功能的基础上,进一步集成天气预报服务,为用户提供出发地和目的地的天气状况。 #### 拟采用的研究方案与方法 1. **技术栈选择**: 使用Java语言进行开发,结合Web Services技术实现跨...

    ACCP 5.0 Y2 WEB服务

    它通常用于实现实时天气预报、电子支付(如安付通、支付宝)等功能。在购物网站中,多个系统可能需要共同的结账功能,Web服务就可以作为服务提供者,让不同的购物网站通过API调用来实现这一功能。Web服务的出现打破...

    JSP快速入门.rar_JSP入门_jsp_jsp 入门

    2. **动态内容生成** - 如新闻、天气预报等实时更新的信息。 3. **用户认证和授权** - 登录系统,权限管理等。 4. **数据展示** - 从数据库中检索并显示数据。 **学习JSP的资源:** 1. **在线教程** - 许多网站提供...

    webService总结1

    4. **内容聚合**:将多个来源的数据(如股票行情、天气预报)集成到一个应用中。 【相关框架】 在Java世界中,常见的WebService框架有Axis、Axis2、XFire、CXF以及JAX-WS。其中,Axis2和CXF是目前较为活跃的开源...

    WeatherWebService.wsdl

    当我们谈论`WeatherWebService.wsdl`时,我们实际上是在讨论一个定义了天气预报Web服务接口的文件。WSDL,全称Web Service Description Language,是一种XML格式,用于描述Web服务及其操作、消息格式和绑定。它是...

    SSM框架——详细整合教程(Spring+SpringMVC+MyBatis)

    通过以上步骤,我们可以成功地将 Spring、SpringMVC 和 MyBatis 这三个框架整合在一起,搭建起一个功能完善、扩展性强的 Web 开发平台。 #### 四、总结 SSM 框架的整合并不难,关键是理解各框架的基本原理和技术...

    liferay二次开发指南,doc

    Portlet可以是任何类型的Web应用,如新闻聚合、天气预报、论坛等。 1.3.2 Portlet与Servlet的关系 Portlet和Servlet类似,都是基于Java的Web组件,但它们有显著的区别。Portlet运行在portlet容器中,有独立的生命...

    利用Liferay开发portal应用(插件)

    Portlet是Liferay中的可重用组件,可以在门户页面上独立显示,如新闻、天气预报或者自定义业务逻辑的应用。在标题中提到的“开发portal应用(插件)”,实际上就是指创建和部署这些portlets。 描述中提到的将文件放到...

    J2EE气象科技服务平台

    地图可以显示气象站的位置、天气预报、雷达图像等多种信息。此外,AJAX(Asynchronous JavaScript and XML)技术可能也被用来增强用户体验,实现地图的无刷新更新和交互性。 3. **集成邮件系统** 平台集成邮件系统...

    关于Portal

    - **内容集成**: 整合来自不同来源的信息,如新闻、天气预报、电子邮件等。 - **显示**: 将上述内容以用户友好的形式展示出来。 #### 3. Portal技术组成 Portal技术主要包括三个关键组成部分: - **Portal服务器 ...

    spring,struts,Ejb 项目综合 ,sse

    这在实时更新的应用场景中非常有用,如股票报价、天气预报或社交媒体通知。SSE通过建立一个持久化的HTTP连接,服务器可以在任何时候向客户端发送事件数据。客户端使用EventSource接口来接收这些事件。SSE相比于...

    HyperContent-开源

    Portlet可以展示动态数据,如新闻、天气预报或者用户定制的信息,增强了用户体验和互动性。 4. **开源软件的优势** 作为开源软件,HyperContent拥有源代码开放、社区驱动和支持的特点。开发者可以根据实际需求进行...

    visit-advisor:J2EE应用程序为用户提供参加所选活动的最佳时间

    这可能涉及到考虑多种因素,如交通状况、天气预报、活动热度、个人偏好等,从而提供个性化的建议。这需要应用程序具备数据处理、算法设计、用户界面交互以及后端服务器的高效处理能力。 【标签解析】 "Java"标签...

Global site tag (gtag.js) - Google Analytics