properties属性文件配置常量技巧

来源:互联网 发布:东风风神a30abs数据 编辑:程序博客网 时间:2024/05/18 00:41

这里做个小的demo,通过城市名获取天气预报接口的demo展开properties属性文件的配置技巧。

1、http.properties配置文件,放置在工程目录src/conf下:

hangzhou=杭州
huzhou=湖州
jiaxing=嘉兴
ningbo=宁波
taizhou=台州
quzhou=衢州
wenzhou=温州
jinhua=金华
lishui=丽水

2、java代码HttpProperties类

package com.web.util;import java.io.IOException;import java.io.InputStream;import java.util.Properties;/** * http.properties工具类 * @author huangyang * @company 聚合网络 * @version 2.0 * @desc 12580平台 * @date 2010-11-11 */public class HttpProperties extends Util{        private static HttpProperties httpProperties = null;        private static final String PROP_PATH = "/conf/http.properties";        private Properties properties = null;        private HttpProperties(){        init();    }        public static HttpProperties getInstance(){        if(httpProperties == null){            httpProperties = new HttpProperties();        }        return httpProperties;    }        private InputStream getInputStream(){        return HttpProperties.class.getResourceAsStream(PROP_PATH);    }        private void init(){        if(properties == null){            properties = new Properties();        }        try {            properties.load(getInputStream());        } catch (IOException e) {            log.error("未找到指定["+PROP_PATH+"]位置的属性文件");        }    }    public String get(String key){        return properties.getProperty(key);    }} 
3、免费的天气预报接口代码:

package com.web.util;import java.io.InputStream;import java.io.OutputStream;import java.io.OutputStreamWriter;import java.net.URL;import java.net.URLConnection;import javax.xml.parsers.DocumentBuilder;import javax.xml.parsers.DocumentBuilderFactory;import org.apache.log4j.Logger;import org.w3c.dom.Document;import org.w3c.dom.Node;import org.w3c.dom.NodeList;public class WeatherReport {private static final Logger log = Logger.getLogger(WeatherReport.class);/** * 获取SOAP的请求头,并替换其中的标志符号为用户输入的城市 *  * 编写者:胡清亮 *  * @param city *            用户输入的城市名称 * @return 客户将要发送给服务器的SOAP请求 */private static String getSoapRequest(String city) {StringBuilder sb = new StringBuilder();sb.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>"+ "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" "+ "xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" "+ "xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"+ "<soap:Body>    <getWeatherbyCityName xmlns=\"http://WebXml.com.cn/\">"+ "<theCityName>" + city+ "</theCityName>    </getWeatherbyCityName>"+ "</soap:Body></soap:Envelope>");return sb.toString();}/** * 用户把SOAP请求发送给服务器端,并返回服务器点返回的输入流 *  * 编写者:胡清亮 *  * @param city *            用户输入的城市名称 * @return 服务器端返回的输入流,供客户端读取 * @throws Exception */private static InputStream getSoapInputStream(String city) throws Exception {try {String soap = getSoapRequest(city);if (soap == null) {return null;}URL url = new URL("http://www.webxml.com.cn/WebServices/WeatherWebService.asmx");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=utf-8");conn.setRequestProperty("SOAPAction","http://WebXml.com.cn/getWeatherbyCityName");OutputStream os = conn.getOutputStream();OutputStreamWriter osw = new OutputStreamWriter(os, "utf-8");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 static String getWeather(String city) {try {Document doc;DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();dbf.setNamespaceAware(true);DocumentBuilder db = dbf.newDocumentBuilder();InputStream is = getSoapInputStream(city);doc = db.parse(is);NodeList nl = doc.getElementsByTagName("string");StringBuffer sb = new StringBuffer();String nowDate = com.web.util.DateUtil.getCurDate(com.web.util.DateUtil.yearMonthDay); sb.append(nowDate+"#\n");for (int count = 0; count < nl.getLength(); count++) {Node n = nl.item(count);if(n.getFirstChild().getNodeValue().equals("查询结果为空!") || n.getFirstChild()==null) {sb = new StringBuffer("#") ;sb.append(nowDate+"#\n");break ;}sb.append(n.getFirstChild().getNodeValue() + "#\n");}is.close();return sb.toString();} catch (Exception e) {log.info(e);return null;}}/** * 测试用 * @param args * @throws Exception */public static void main(String[] args) throws Exception {String sb = getWeather("杭州");String[] ss = sb.split("#");String date = ss[21];String nowDate = DateUtil.getCurDate(DateUtil.yearMonthDay);if(nowDate!=date)System.out.println(date);}}


4、业务代码,控制层中,使用request获取前台城市代号,并且根据城市代号取出httpProperties中的城市中文名

/** * 天气城市key对应天气info的map */public static final Map<String,String> ONLINE_WEATHER_MAP = new HashMap<String,String>();/** * 获取城市天气预报 *  * @param request * @param response */@RequestMapping("/getCityWeather")public void getCityWeather(HttpServletRequest request,HttpServletResponse response) {//获得地区String city = request.getParameter("cityCode");                  //根据城市代号取出httpProperties中的城市中文名                String cityAreaAddress = HttpProperties.getInstance().get(city);JSONObject object = new JSONObject();PrintWriter out = getPrintWriter(response, DEFAULT_ENCODING);try {request.setCharacterEncoding("UTF-8");String info = null;//获取系统当前时间yyyy-MM-dd格式String nowDate = com.web.util.DateUtil.getCurDate(com.web.util.DateUtil.yearMonthDay);info = ONLINE_WEATHER_MAP.get(city);if(StringUtil.isNotEmpty(info) && info.indexOf("#")>0){String[] ss = info.split("#");String date = ss[0];String oldDate = StringUtil.isNotEmpty(date) && date.length()>=10?date.substring(0,10):"2000-01-01"; if(!nowDate.equals(oldDate)){ info = WeatherReport.getWeather(city);}}else{                             //获取城市天气信息                             info = WeatherReport.getWeather(city);}ONLINE_WEATHER_MAP.put(city, info);String[] infos = null; if(StringUtil.isNotEmpty(info) && info.indexOf("#")>0){infos = info.split("#");//object.put("area", infos[1]); //地区object.put("city", infos[2]); //城市object.put("wenDu", infos[6]); //温度object.put("tianQi", infos[7].split(" ")[1]);//天气object.put("tianQiStart", infos[9]);//开始天气图片object.put("tianQiEnd", infos[10]);//结束天气图片}else{object.put("tianQiStart", "");//开始天气图片object.put("city", city); //城市}object.put("cityAreaAddress",cityAreaAddress);out.print(object);out.close();} catch (UnsupportedEncodingException e) {log.info(e);} catch (JSONException e) {log.info(e);}finally{if(out != null){out.close();}}}
5、前台代码及美工特效省略。。。。。。。。。。。

       图片上为本人调用2011-10-10日杭州地区天气接口得出的效果。

原创粉丝点击