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

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

/**
 * 
 */
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>

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