基于xml的实时天气项目

来源:互联网 发布:怎么做淘宝客服 编辑:程序博客网 时间:2024/05/16 01:41

效果图




WeatherController

package com.wxh.ew.controller;import java.io.IOException;import java.io.PrintWriter;import java.util.List;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import com.wxh.ew.dto.City;import com.wxh.ew.http.Constant;import com.wxh.ew.service.WeatherService;public class WeatherController extends HttpServlet {public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {this.doPost(request, response);}public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {request.getSession().setAttribute("imgPath", Constant.BASE_IMG_URI);String flag=request.getParameter("flag"); if("details".equals(flag)){details(request,response);//显示详情数据}else{list(request,response);}}private void details(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {String pyName=request.getParameter("pyName");String cityName=request.getParameter("cityName");WeatherService ws=new WeatherService();City city=ws.getCityWeather(pyName, cityName);request.setAttribute("city", city);request.getRequestDispatcher("details.jsp").forward(request, response);}private void list(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {String pyName=request.getParameter("pyName");pyName= pyName!=null?pyName:"china";WeatherService ws=new WeatherService();List<City> cities=ws.getCitiesWeather(pyName);//继续传递当前查询的城市集合对应的pyNamerequest.setAttribute("pyName", pyName);request.setAttribute("cities", cities);request.getRequestDispatcher("index.jsp").forward(request, response);}}

 City 

package com.wxh.ew.dto;/** * 描述城市天气详情的javabean * @author Administrator * */public class City {private String quName;//地区名称private String pyName;//下一级查询的文件名(下一级地区拼音名)private String cityName;//城市名字private String state1;//天气状态1(对应的天气图片1)private String state2;//天气状态2(对应的天气图片2)private String stateDetailed;//天气详情private String windState;//风力情况private String windDir;//风向private String windPower;//风力级别private String humidity;//湿度private String lastTime;//最近一次更新时间private int tem1;//最高温度private int tem2;//最低温度private int temNow;//当前温度public City() {}public City(String quName, String pyName, String cityName, String state1,String state2, String stateDetailed, String windState,String windDir, String windPower, String humidity, String lastTime,int tem1, int tem2, int temNow) {this.quName = quName;this.pyName = pyName;this.cityName = cityName;this.state1 = state1;this.state2 = state2;this.stateDetailed = stateDetailed;this.windState = windState;this.windDir = windDir;this.windPower = windPower;this.humidity = humidity;this.lastTime = lastTime;this.tem1 = tem1;this.tem2 = tem2;this.temNow = temNow;}public String getQuName() {return quName;}public void setQuName(String quName) {this.quName = quName;}public String getPyName() {return pyName;}public void setPyName(String pyName) {this.pyName = pyName;}public String getCityName() {return cityName;}public void setCityName(String cityName) {this.cityName = cityName;}public String getState1() {return state1;}public void setState1(String state1) {this.state1 = state1;}public String getState2() {return state2;}public void setState2(String state2) {this.state2 = state2;}public String getStateDetailed() {return stateDetailed;}public void setStateDetailed(String stateDetailed) {this.stateDetailed = stateDetailed;}public String getWindState() {return windState;}public void setWindState(String windState) {this.windState = windState;}public String getWindDir() {return windDir;}public void setWindDir(String windDir) {this.windDir = windDir;}public String getWindPower() {return windPower;}public void setWindPower(String windPower) {this.windPower = windPower;}public String getHumidity() {return humidity;}public void setHumidity(String humidity) {this.humidity = humidity;}public String getLastTime() {return lastTime;}public void setLastTime(String lastTime) {this.lastTime = lastTime;}public int getTem1() {return tem1;}public void setTem1(int tem1) {this.tem1 = tem1;}public int getTem2() {return tem2;}public void setTem2(int tem2) {this.tem2 = tem2;}public int getTemNow() {return temNow;}public void setTemNow(int temNow) {this.temNow = temNow;}@Overridepublic String toString() {return "City [cityName=" + cityName + ", humidity=" + humidity+ ", lastTime=" + lastTime + ", pyName=" + pyName + ", quName="+ quName + ", state1=" + state1 + ", state2=" + state2+ ", stateDetailed=" + stateDetailed + ", tem1=" + tem1+ ", tem2=" + tem2 + ", temNow=" + temNow + ", windDir="+ windDir + ", windPower=" + windPower + ", windState="+ windState + "]";}}

Constant

package com.wxh.ew.http;public class Constant {/** *  * 城市天气详情查询基本地址  *  */public static final String BASE_URI="http://flash.weather.com.cn/wmaps/xml/";public static final String BASE_IMG_URI="http://m.weather.com.cn/img/";}
HttpRequest

package com.wxh.ew.http;import java.io.IOException;import java.io.InputStream;import java.net.HttpURLConnection;import java.net.URL;/* * 用于发起http请求的网络连接类 */public class HttpRequest {public static InputStream read(String uri) throws IOException{InputStream is=null;//根据要请求的url地址构建一个URL对象URL url=new URL(uri);//打开到指定地址的连接HttpURLConnection conn=(HttpURLConnection) url.openConnection();//设置请求方式为getconn.setRequestMethod("GET");//设置读取的超时时间conn.setReadTimeout(10000);//设置连接的超时时间conn.setConnectTimeout(5000);//获取响应码int stateCode=conn.getResponseCode();System.out.println("http response code:"+stateCode);if(stateCode==HttpURLConnection.HTTP_OK){//如果响应成功,则获取服务端响应回来的数据is=conn.getInputStream();}return is;}}

WeatherService

package com.wxh.ew.service;import java.io.IOException;import java.io.InputStream;import java.util.List;import javax.xml.parsers.ParserConfigurationException;import org.xml.sax.SAXException;import com.wxh.ew.dto.City;import com.wxh.ew.http.Constant;import com.wxh.ew.http.HttpRequest;import com.wxh.ew.xml.XmlParser;/** *  * 处理天气数据的业务逻辑层 *    * @author Administrator * */public class WeatherService {//查询指定城市下所有的天气情况public List<City> getCitiesWeather(String pyName){List<City> cities=null;InputStream is=null;try {String uri= Constant.BASE_URI+pyName+".xml";is=HttpRequest.read(uri);XmlParser parser=new XmlParser();cities=parser.getCities(is);} catch (IOException e) {e.printStackTrace();} catch (ParserConfigurationException e) {e.printStackTrace();} catch (SAXException e) {e.printStackTrace();}finally{try {if(is!=null){is.close();}} catch (IOException e) {e.printStackTrace();}}return cities;}//查询指定某个城市的天气情况public City getCityWeather(String pyName,String cityName){List<City> cities=null;InputStream is=null;City city=null;try {String uri= Constant.BASE_URI+pyName+".xml";is=HttpRequest.read(uri);XmlParser parser=new XmlParser();cities=parser.getCities(is);for (City c : cities) {if(c.getCityName().equals(cityName)){//判断当前遍历到的城市名字是否是需要被查询到的名字city=c;break;}}} catch (IOException e) {e.printStackTrace();} catch (ParserConfigurationException e) {e.printStackTrace();} catch (SAXException e) {e.printStackTrace();}finally{try {if(is!=null){is.close();}} catch (IOException e) {e.printStackTrace();}}return city;}}
XmlParser


package com.wxh.ew.xml;import java.io.IOException;import java.io.InputStream;import java.util.ArrayList;import java.util.List;import javax.xml.parsers.DocumentBuilder;import javax.xml.parsers.DocumentBuilderFactory;import javax.xml.parsers.ParserConfigurationException;import org.w3c.dom.Document;import org.w3c.dom.Element;import org.w3c.dom.NodeList;import org.xml.sax.SAXException;import com.wxh.ew.dto.City;public class XmlParser {private DocumentBuilder builder;public XmlParser() throws ParserConfigurationException{builder=DocumentBuilderFactory.newInstance().newDocumentBuilder();}/** * 将指定的输入流解析为对应的JAVA对象 * @param is 包含天气数据输入流 * @return 返回解析获取的所有城市天气对象 * @throws IOException  * @throws SAXException  */public List<City> getCities(InputStream is) throws SAXException, IOException{List<City> cities=new ArrayList<City>();Document document=builder.parse(is);//获取所有的city元素NodeList list=document.getElementsByTagName("city");for (int i = 0; i < list.getLength(); i++) {Element element=(Element)list.item(i);String quName=element.getAttribute("quName");String pyName=element.getAttribute("pyName");String cityName=element.getAttribute("cityname");String state1=element.getAttribute("state1");String state2=element.getAttribute("state2");String stateDetailed=element.getAttribute("stateDetailed");String windState=element.getAttribute("windState");String windDir=element.getAttribute("windDir");String windPower=element.getAttribute("windPower");String humidity=element.getAttribute("humidity");String lastTime=element.getAttribute("time");int tem1=Integer.parseInt(element.getAttribute("tem1"));int tem2=Integer.parseInt(element.getAttribute("tem2"));String tn=element.getAttribute("temNow");//获取当前温度,如果没有当前温度(省级别天气)则使用-10000代表无数据int temNow= (tn!=null&&!"".equals(tn)&& !"暂无实况".equals(tn))?Integer.parseInt(tn):-10000;//根据获取的数据创建city对象City city=new City(quName, pyName, cityName, state1, state2, stateDetailed, windState, windDir, windPower, humidity, lastTime, tem1, tem2, temNow);cities.add(city);}return cities;}}


web.xml

<?xml version="1.0" encoding="UTF-8"?><web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">  <servlet>    <servlet-name>WeatherController</servlet-name>    <servlet-class>com.wxh.ew.controller.WeatherController</servlet-class>  </servlet>  <servlet-mapping>    <servlet-name>WeatherController</servlet-name>    <url-pattern>/weather</url-pattern>  </servlet-mapping>  <welcome-file-list>    <welcome-file>weather</welcome-file>  </welcome-file-list></web-app>

index.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <base href="<%=basePath%>">        <title>实时天气查询</title><meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><meta http-equiv="expires" content="0">    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"><meta http-equiv="description" content="This is my page"><!--<link rel="stylesheet" type="text/css" href="styles.css">-->  </head>    <style>  .box_main{  width:50%;  min-width:400px;  border:1px solid #808080;    margin:0 auto;  border-radius:5px;  }    .title{  width:100%;  height:50px;  background-color:#38B0FF;  color:#ffffff;  text-align:center;  line-height:50px;  font-size:25px;  }      .tab_data table{  width:100%;  border:1px solid  #8194AA;    border-collapse: collapse;  }    .tab_data table th,.tab_data table td{    border:1px solid #8194AA;    }    a{  text-decoration: none;  color:#000000;  }    a:HOVER {  text-decoration: underline;  color:#ff0000;    }}    </style>    <body>   <div class="box_main">   <div class="title">   实时天气      </div>   <div class="tab_data">    <table>      <tr>   <td colspan="5"><a href="javascript:history.back();"><<返回</a></td>   </tr>      <tr>   <th>城市/地区</th>   <th>天气</th>   <th>温度</th>   <th>风力情况</th>   <th>下属地区天气</th>   </tr>      <c:forEach items="${cities }" var="city">         <tr>   <td><a href="weather?flag=details&pyName=${city.pyName}&cityName=${city.cityName }">${city.cityName }</a></td>   <td><img src="${imgPath}d${city.state1}.gif"/>${city.stateDetailed }</td>      <td>${city.tem2}℃-${city.tem1}℃</td>   <td>${city.windState} ${city.windDir } ${windPower}</td>      <td><a href="weather?pyName=${city.pyName}">详情</a></td>   </tr>   </c:forEach>      </table>      </div>      </div>     </body></html>


details.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <base href="<%=basePath%>">        <title>实时天气查询</title><meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><meta http-equiv="expires" content="0">    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"><meta http-equiv="description" content="This is my page"><!--<link rel="stylesheet" type="text/css" href="styles.css">-->  </head>    <style>  .box_main{  width:50%;  min-width:400px;  border:1px solid #808080;    margin:0 auto;  border-radius:5px;  }    .title{  width:100%;  height:50px;  background-color:#38B0FF;  color:#ffffff;  text-align:center;  line-height:50px;  font-size:25px;  }      .tab_data table{  width:100%;  border:1px solid  #8194AA;    border-collapse: collapse;  }    .tab_data table th,.tab_data table td{    border:1px solid #8194AA;    }    a{  text-decoration: none;  color:#000000;  }    a:HOVER {  text-decoration: underline;  color:#ff0000;    }}    </style>    <body>   <div class="box_main">   <div class="title">   实时天气      </div>   <div class="tab_data">      <table>     <tr>     <th>     <img src="${imgPath}d${city.state1}.gif"/><br>     <c:if test="${city.temNow!=-10000}">     ${city.temNow }℃     </c:if>     </th>     </tr>     <tr>     <th style="color:#ff0000;font-size:20pt">${city.stateDetailed}</th>     </tr>     <tr>     <th>${city.tem2}℃-${city.tem1}℃</th>     </tr>          <tr>    <th>${city.windState}</th>    </tr>    <tr>    <th>风向:<c:out value="${city.windDir}"></c:out></th>    </tr>    <tr>    <th>风力:<c:out value="${city.windPower}"></c:out></th>    </tr>    <tr>    <th>湿度:<c:out value="${city.humidity}"></c:out></th>    </tr>    <tr>    <th>更新时间:<c:out value="${city.lastTime}"></c:out></th>    </tr>        </table>   </div>      </div>     </body></html>


0 0