`
jilong-liang
  • 浏览: 481319 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类

Spring quartz定时结合Jsoup和Dom4j使用解析百度地图API

阅读更多

 

<?xml version="1.0" encoding="utf-8" ?>
<GeocoderSearchResponse>
	<status>0</status>
	<result>
		<location>
			<lat>39.983424071404</lat>
			<lng>116.322987</lng>
		</location>
		<formatted_address>北京市海淀区中关村大街27号1101-08室</formatted_address>
		<business>人民大学,中关村,苏州街</business>
		<addressComponent>
			<streetNumber></streetNumber>
			<street>中关村大街</street>
			<district>海淀区</district>
			<city>北京市</city>
			<province>北京市</province>
		</addressComponent>
		<cityCode>131</cityCode>
		<pois>
			<poi>
				<addr>中关村西区南侧(中关村科技园区内)</addr>
				<distance>0.050000</distance>
				<name>中关村大厦</name>
				<poiType>办公大厦,商务大厦</poiType>
				<tel>(010)82856666</tel>
				<zip>100000</zip>
				<point>
					<x>116.32298658484</x>
					<y>39.983423843929</y>
				</point>
			</poi>
			<poi>
				<addr>中关村大街27号</addr>
				<distance>0.050000</distance>
				<name>眉州东坡酒楼中关村店</name>
				<poiType>中餐馆,餐饮</poiType>
				<tel>(010)82856948</tel>
				<zip></zip>
				<point>
					<x>116.32298658484</x>
					<y>39.983423843929</y>
				</point>
			</poi>
			<poi>
				<addr>中关村大街27号</addr>
				<distance>0.050000</distance>
				<name>中国人民财产保险中关村营业部</name>
				<poiType>中国人民财产保险,保险公司,金融</poiType>
				<tel>(010)82856779</tel>
				<zip>100000</zip>
				<point>
					<x>116.32298658484</x>
					<y>39.983423843929</y>
				</point>
			</poi>
			<poi>
				<addr>北京市海淀区</addr>
				<distance>94.432081</distance>
				<name>光合作用书房</name>
				<poiType>图书音像,购物</poiType>
				<tel></tel>
				<zip></zip>
				<point>
					<x>116.32239334388</x>
					<y>39.983890240676</y>
				</point>
			</poi>
			<poi>
				<addr>中关村大街27号</addr>
				<distance>42.195731</distance>
				<name>建行中关村支行</name>
				<poiType>中国建设银行,银行,金融</poiType>
				<tel></tel>
				<zip>100000</zip>
				<point>
					<x>116.32292037972</x>
					<y>39.983711118168</y>
				</point>
			</poi>
			<poi>
				<addr>北京市海淀区</addr>
				<distance>62.342644</distance>
				<name>海淀医院-激光整形美容部</name>
				<poiType>美容美发,生活服务</poiType>
				<tel></tel>
				<zip></zip>
				<point>
					<x>116.32317954086</x>
					<y>39.98301950182</y>
				</point>
			</poi>
			<poi>
				<addr>中关村大街19号新中关购物中心1楼</addr>
				<distance>112.983688</distance>
				<name>星巴克新中关店</name>
				<poiType>星巴克,咖啡厅,休闲餐饮,餐饮</poiType>
				<tel>(010)82486056</tel>
				<zip></zip>
				<point>
					<x>116.32218215226</x>
					<y>39.983899777278</y>
				</point>
			</poi>
		</pois>
	</result>
</GeocoderSearchResponse>

 从xml可以分析成几个实体类

 

  

 

 

纯粹的解析

 

package com.app.duapp;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.app.common.AppDbUtil;
import com.app.entity.duapp.Address;
import com.app.entity.duapp.Geocoder;
import com.app.entity.duapp.Location;
import com.app.entity.duapp.Point;
import com.app.entity.duapp.Pois;
/**
 * @author liangjilong
 */
@SuppressWarnings("all")
public class Deocoder {
	
	public static void main(String[] args)throws Exception {
		String url = "http://api.map.baidu.com/geocoder/v2/?ak=E4805d16520de693a3fe707cdc962045&callback=renderReverse&location=39.983424,116.322987&output=xml&pois=1";
		readXml(url);
	}
	/**
	 * 
	 * @param url xml地址
	 * @return
	 */
	public static void readXml(String url) {
		List<Geocoder> list=new ArrayList<Geocoder>();
		try {
			SAXReader reader = new SAXReader();
			Document document =reader.read(url);//如果是本地的xml就new File(filename);
			Element root = document.getRootElement();//获取根节点
			System.out.println((root.elementText("status")));//状态-->第一个大节点
		
			Iterator<Element> iter = root.elementIterator("result");//第二大节点
			for (Iterator iter1 =iter; iter1.hasNext();) {
				Element Node1=(Element)iter1.next();
				
				Element locationNode=Node1.element("location");//location节点
				System.out.println(locationNode.elementText("lat"));//纬度
				String lng=locationNode.elementText("lng");//经度
				String format_addr=Node1.elementText("formatted_address");
				String business=Node1.elementText("business");
				
				Address address=new Address();
				Element addressComponent=Node1.element("addressComponent");//addressComponent节点
				if(addressComponent.elementText("streetNumber")!=""&&addressComponent.elementText("streetNumber")!=null)
				{
					address.setStreetNumber(addressComponent.elementText("streetNumber"));
				}
				System.out.println(addressComponent.elementText("street"));
				System.out.println(addressComponent.elementText("district"));
				System.out.println(addressComponent.elementText("city"));
				System.out.println(addressComponent.elementText("province"));
				System.out.println(Node1.elementText("cityCode"));//cityCode节点

			    Element poisNode=Node1.element("pois");//pois节点
			    
			    for (Iterator iter2 = poisNode.elementIterator(); iter2.hasNext();) {
					Element poisNodes=(Element)iter2.next();
					System.out.println(poisNodes.elementText("addr"));
					System.out.println(poisNodes.elementText("distance"));
					System.out.println(poisNodes.elementText("name"));
					System.out.println(poisNodes.elementText("tel"));
					if(poisNodes.elementText("zip")!=""&&poisNodes.elementText("zip")!=null)
			        {
						System.out.println(poisNodes.elementText("zip"));
					}
					
					Element point=poisNodes.element("point");//point节点
					
					System.out.println(point.elementText("x"));
					System.out.println(point.elementText("y"));
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	 
}

 

 Jsoup的解析xml 

 

package com.app.duapp;
import java.util.Iterator;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
/**
 * @author liangjilong
 */
@SuppressWarnings("all")
public class JsoupXml {
	
	public static void main(String[] args)throws Exception {
		String url = "http://api.map.baidu.com/geocoder/v2/?ak=E4805d16520de693a3fe707cdc962045&callback=renderReverse&location=39.983424,116.322987&output=xml&pois=1";
		//readXml(url);
		JsoupReadXml(url);
	}
	/**
	 * 
	 * @param url xml地址
	 * @return
	 */
	public static void readXml(String url) throws Exception{ 
		
		Document doc=Jsoup.connect(url).get();
		
		Elements status=doc.select("status");//status节点
		for(Element st:status){
			System.out.println(st.text());//获取值
		}
		Elements lats=doc.select("lat");//lat节点
		for(Element lat:lats){
			System.out.println(lat.text());
		}
		Elements lngs=doc.select("lng");//lng节点
		for(Element lng:lngs){
			System.out.println(lng.text());
		}
		Elements formatted_address=doc.select("formatted_address");//formatted_address节点
		for(Element a:formatted_address){
			System.out.println(a.text());
		}
		
		Elements businesss=doc.select("business");//business节点
		for(Element b:businesss){
			System.out.println(b.text());
		}
		Elements streetNumbers=doc.select("streetNumber");//streetNumber节点
		for(Element sn:streetNumbers){
			System.out.println(sn.text());
		}
		Elements streets=doc.select("street");//street节点
		for(Element st:streets){
			System.out.println(st.text());
		}
		Elements districts=doc.select("district");//district节点
		for(Element d:districts){
			System.out.println(d.text());
		}
		Elements citys=doc.select("city");//city节点
		for(Element c:citys){
			System.out.println(c.text());
		}
		Elements provinces=doc.select("province");//province节点
		for(Element p:provinces){
			System.out.println(p.text());
		}
		Elements cityCodes=doc.select("cityCode");//cityCode节点
		for(Element cc:cityCodes){
			System.out.println(cc.text());
		}
		Elements addrs=doc.select("addr");//addr节点
		for(Element add:addrs){
			System.out.println(add.text());
		}
		Elements distances=doc.select("distance");//distance节点
		for(Element d:distances){
			System.out.println(d.text());
		}
		Elements names=doc.select("name");//name节点
		for(Element n:names){
			System.out.println(n.text());
		}
		Elements poiTypes=doc.select("poiType");//poiType节点
		for(Element pt:poiTypes){
			System.out.println(pt.text());
		}
		Elements tels=doc.select("tel");//tel节点
		for(Element t:tels){
			System.out.println(t.text());
		}
		Elements zips=doc.select("zip");//zip节点
		for(Element z:zips){
			System.out.println(z.text());
		}
		Elements xs=doc.select("x");//zip节点
		for(Element x:xs){
			System.out.println(x.text());
		}
		Elements ys=doc.select("y");//zip节点
		for(Element y:ys){
			System.out.println(y.text());
		}
		
	}
	
	/**
	 * 用Jsoup去解析xml
	 * @param url
	 */
	private static void JsoupReadXml(String url) throws Exception{
		org.jsoup.nodes.Document doc=Jsoup.connect(url).get();
		if(doc!=null)
		{
			Elements pois=doc.select("poi");//获取到poi节点
			for(org.jsoup.nodes.Element poi:pois){
				
				String addr=poi.getElementsByTag("addr").text().trim();
				String distance=poi.getElementsByTag("distance").text().trim();
				String name=poi.getElementsByTag("name").text().trim();
				String poiType=poi.getElementsByTag("poiType").text().trim();
				String tel=poi.getElementsByTag("tel").text().trim();
				String zip=poi.getElementsByTag("zip").text().trim();
				String x=poi.getElementsByTag("x").text().trim();
				String y=poi.getElementsByTag("y").text().trim();
				
				Elements comps=doc.select("addressComponent");
				
				for (org.jsoup.nodes.Element comp:comps) {
					String streetNumber=comp.getElementsByTag("streetNumber").text().trim();
					String street=comp.getElementsByTag("street").text().trim();
					String district=comp.getElementsByTag("district").text().trim();
					String city=comp.getElementsByTag("city").text().trim();
					String province=comp.getElementsByTag("province").text().trim();
				}
				
				String	lat=doc.select("lat").text().trim();
				String	lng=doc.select("lng").text().trim();
				String	formatted_address=doc.select("formatted_address").text().trim();
				String	business=doc.select("business").text().trim();
			}
		}
	}
	 
}

 

 

 

几个实体

package com.app.entity.duapp;

import java.io.Serializable;

public class Address implements Serializable{
	private String streetNumber;
	private String street;
	private String district;
	private String city;
	private String province;
	private String cityCode;
	public String getCityCode() {
		return cityCode;
	}
	public void setCityCode(String cityCode) {
		this.cityCode = cityCode;
	}
	public String getStreetNumber() {
		return streetNumber;
	}
	public void setStreetNumber(String streetNumber) {
		this.streetNumber = streetNumber;
	}
	public String getStreet() {
		return street;
	}
	public void setStreet(String street) {
		this.street = street;
	}
	public String getDistrict() {
		return district;
	}
	public void setDistrict(String district) {
		this.district = district;
	}
	public String getCity() {
		return city;
	}
	public void setCity(String city) {
		this.city = city;
	}
	public String getProvince() {
		return province;
	}
	public void setProvince(String province) {
		this.province = province;
	}
	
}

封装型解析:

package com.app.duapp;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.app.common.AppDbUtil;
import com.app.entity.duapp.Address;
import com.app.entity.duapp.Geocoder;
import com.app.entity.duapp.Location;
import com.app.entity.duapp.Point;
import com.app.entity.duapp.Pois;

@SuppressWarnings("all")
public class DeocoderDao {
	/**
	 * 
	 * @param url xml地址
	 * @return
	 */
	public  List<Geocoder> readXml(String url) {
		List<Geocoder> list=new ArrayList<Geocoder>();
		try {
			SAXReader reader = new SAXReader();
			Document document =reader.read(url);//如果是本地的xml就new File(filename);
			Element root = document.getRootElement();//获取根节点
			Geocoder g=new Geocoder();
			g.setStatus(root.elementText("status"));//状态-->第一个大节点
		
			Iterator<Element> iter = root.elementIterator("result");//第二大节点
			for (Iterator iter1 =iter; iter1.hasNext();) {
				Element Node1=(Element)iter1.next();
				
				Location location=new Location();
				List<Location> listLocations=new ArrayList<Location>();
				
				Element locationNode=Node1.element("location");//location节点
				String lat=locationNode.elementText("lat");//纬度
				String lng=locationNode.elementText("lng");//经度
				String format_addr=Node1.elementText("formatted_address");
				String business=Node1.elementText("business");
				location.setLat(lat);
				location.setLng(lng);
				location.setBusiness(business);
				location.setFormattedAddress(format_addr);
				listLocations.add(location);//把location对象丢进集合里面
				g.setLocations(listLocations);//把集合丢进集合里面
				
				
				List<Address> listAddress=new ArrayList<Address>();
				Address address=new Address();
				Element addressComponent=Node1.element("addressComponent");//addressComponent节点
				if(addressComponent.elementText("streetNumber")!=""&&addressComponent.elementText("streetNumber")!=null)
				{
					address.setStreetNumber(addressComponent.elementText("streetNumber"));
				}
				address.setStreet(addressComponent.elementText("street"));
				address.setDistrict(addressComponent.elementText("district"));
				address.setCity(addressComponent.elementText("city"));
				address.setProvince(addressComponent.elementText("province"));
			    address.setCityCode(Node1.elementText("cityCode"));//cityCode节点
			    listAddress.add(address);//把address对象丢进集合里面

			    g.setAddress(listAddress);//把集合丢进集合里面
			    
			    Element poisNode=Node1.element("pois");//pois节点
			    
			    for (Iterator iter2 = poisNode.elementIterator(); iter2.hasNext();) {
			    	Pois pois=new Pois();
			    	List<Pois> listPois=new ArrayList<Pois>();
					Element poisNodes=(Element)iter2.next();
					
					pois.setAddr(poisNodes.elementText("addr"));
					pois.setDistance(poisNodes.elementText("distance"));
					pois.setName(poisNodes.elementText("name"));
					pois.setTel(poisNodes.elementText("tel"));
					if(poisNodes.elementText("zip")!=""&&poisNodes.elementText("zip")!=null)
			        {
						pois.setZip(poisNodes.elementText("zip"));
					}
					
					Element point=poisNodes.element("point");//point节点
					
					Point p=new Point();
					List<Point> listPoints=new ArrayList<Point>();
					p.setX(point.elementText("x"));
					p.setY(point.elementText("y"));
					listPoints.add(p);//point
					pois.setPoints(listPoints);
					listPois.add(pois);//把对象pois丢到集合
					g.setPois(listPois);//把集合丢到集合
				}
				list.add(g);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}
	
	/**
	 * 保存
	 */
	public static int batchsSaveData(List<Geocoder> list) {
		int index=0;
		String sqls[]=new String[list.size()];//多条SQL
		for (int i = 0; i < list.size(); i++) {
			StringBuffer buffer=new StringBuffer();
			Geocoder g=(Geocoder) list.get(i);
			String statue=g.getStatus();
			List<Location> listLocations=g.getLocations();//Locations
			List<Address> listAddress=g.getAddress();//Address
			List<Pois> listPois=g.getPois();//Pois
			
			for (Iterator iterator1 = listLocations.iterator(); iterator1.hasNext();) {
				Location location = (Location) iterator1.next();
				String lat=location.getLat();
				String lng=location.getLng();
			    String business=location.getBusiness();
			    String formattedAddress=location.getFormattedAddress();
			    
				for (Iterator iterator2 = listAddress.iterator(); iterator2.hasNext();) {
					Address addr = (Address) iterator2.next();
					
					String city=addr.getCity();
					String cityCode=addr.getCityCode();
					String district=addr.getDistrict();
					String province=addr.getProvince();
					String street=addr.getStreet();
					String StreetNumber=addr.getStreetNumber();
					
					for (Iterator iterator3 = listPois.iterator(); iterator3.hasNext();) {
						Pois p = (Pois) iterator3.next();
						String add=p.getAddr();
						String distance=p.getDistance();
						String name=p.getName();
						String poiType=p.getPoiType();
						String tel=p.getTel();
						String zip=p.getZip();
						
						List<Point> listPoints=p.getPoints();
						
						for (Iterator iterator4 = listPoints.iterator(); iterator4.hasNext();) {
							Point point = (Point) iterator4.next();
							String x=point.getX();
							String y=point.getY();
							
							buffer.append("Insert into GeocoderSearch(status,lat,lng,formatted_address,business,streetNumber,street,district,city,province,cityCode,addr,distance,name,poiType,tel,zip,x,y) values(");
						    buffer.append("'"+statue+"',").append("'"+lat+"',");
						    buffer.append("'"+lng+"',").append("'"+formattedAddress+"',");
						    buffer.append("'"+business+"',").append("'"+StreetNumber+"',");
						    buffer.append("'"+street+"',").append("'"+district+"',");
						    buffer.append("'"+city+"',").append("'"+province+"',");
						    buffer.append("'"+cityCode+"',").append("'"+add+"',");
						    buffer.append("'"+distance+"',").append("'"+name+"',");
						    buffer.append("'"+poiType+"',").append("'"+tel+"',");
						    buffer.append("'"+zip+"',").append("'"+x+"',").append("'"+y+"'");
						    buffer.append(")");
						    String sql=buffer.toString();
						    sqls[index]=sql;	
						}
					}
				}
			}
			index++;
		}
		int rows=AppDbUtil.getInstance().supportsBatch(sqls);
		return rows;
	}
}

 

package com.app.entity.duapp;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

public class Pois implements Serializable{
	private String addr;
	private String distance;
	private String name;
	private String poiType;
	private String tel;
	private String zip;
	private List<Point> points=new ArrayList<Point>();
	
	public String getAddr() {
		return addr;
	}
	public void setAddr(String addr) {
		this.addr = addr;
	}
	public String getDistance() {
		return distance;
	}
	public void setDistance(String distance) {
		this.distance = distance;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getPoiType() {
		return poiType;
	}
	public void setPoiType(String poiType) {
		this.poiType = poiType;
	}
	public String getTel() {
		return tel;
	}
	public void setTel(String tel) {
		this.tel = tel;
	}
	public String getZip() {
		return zip;
	}
	public void setZip(String zip) {
		this.zip = zip;
	}
	public List<Point> getPoints() {
		return points;
	}
	public void setPoints(List<Point> points) {
		this.points = points;
	}
	
}

 

package com.app.entity.duapp;

import java.io.Serializable;

public class Point implements Serializable{
	private String x;
	private String y;
	public String getX() {
		return x;
	}
	public void setX(String x) {
		this.x = x;
	}
	public String getY() {
		return y;
	}
	public void setY(String y) {
		this.y = y;
	}
	
}

 

package com.app.entity.duapp;

import java.io.Serializable;

public class Location implements Serializable{
	private  String lat;//纬度
	private  String lng;//经度
	private  String formattedAddress;//经度
	private  String business;//经度
	public String getLat() {
		return lat;
	}
	public void setLat(String lat) {
		this.lat = lat;
	}
	public String getLng() {
		return lng;
	}
	public void setLng(String lng) {
		this.lng = lng;
	}
	public String getFormattedAddress() {
		return formattedAddress;
	}
	public void setFormattedAddress(String formattedAddress) {
		this.formattedAddress = formattedAddress;
	}
	public String getBusiness() {
		return business;
	}
	public void setBusiness(String business) {
		this.business = business;
	}
}

 

package com.app.entity.duapp;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

public class Geocoder  implements Serializable{
	private String status;
	private List<Location> locations=new ArrayList<Location>();
	private List<Address> address=new ArrayList<Address>();
	private List<Pois> pois=new ArrayList<Pois>();
	public String getStatus() {
		return status;
	}
	public void setStatus(String status) {
		this.status = status;
	}
	public List<Location> getLocations() {
		return locations;
	}
	public void setLocations(List<Location> locations) {
		this.locations = locations;
	}
	public List<Address> getAddress() {
		return address;
	}
	public void setAddress(List<Address> address) {
		this.address = address;
	}
	public List<Pois> getPois() {
		return pois;
	}
	public void setPois(List<Pois> pois) {
		this.pois = pois;
	}
}

 

 

连接数据库:

package com.app.common;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.hibernate.SQLQuery;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
@SuppressWarnings("all")
public class AppDbUtil  extends HibernateDaoSupport{
	private static String Driver=PropertyUtil.getProperty("jdbc.driver");
	private static String url=PropertyUtil.getProperty("jdbc.url");
	private static String url1=PropertyUtil.getProperty("jdbc.url");
	private static String username=PropertyUtil.getProperty("jdbc.username");
	private static String password=PropertyUtil.getProperty("jdbc.password");
	
	private static AppDbUtil instance=null;
	private static Connection con = null;
	private static Statement stmt = null;
	private static PreparedStatement  pst = null;
	private static ResultSet rs = null;
	/**
	 * Single
	 * @return
	 */
	public static AppDbUtil getInstance(){
		if (instance == null) {
			synchronized (AppDbUtil.class) {
				instance = new AppDbUtil();
			}
		}
		return instance;
	}
	
	/**
	 * 通过过文件处理流加载配置,读key获取value值
	 * @return
	 */
	public static Connection getConnection() {
		Connection conn=null;
		try {
			Class.forName(Driver);
			conn=DriverManager.getConnection(url, username, password);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return conn;
	}
	
	/**
	 * @return
	 */
	public static Connection getConn() {
		Connection conn=null;
		try {
			Class.forName(Driver);
			conn=DriverManager.getConnection(url1, username, password);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return conn;
	}
	
	/**
	 * 调用log4通过key值去获取value值
	 * @return
	 */
	public static Connection getConfigConnection() {
		try {
			Class.forName(Driver);
			con = DriverManager.getConnection(url1, username, password);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return con;
	}
	/**
	 * 支持批量处理delete update insert
	 * @param sqls
	 * @return
	 */
	public  int supportsBatch(Object [] sqls){
		
		try {
			con=AppDbUtil.getInstance().getConnection();
			con.setAutoCommit(false);
			DatabaseMetaData dma=con.getMetaData();
			
			if(dma.supportsBatchUpdates()){
				stmt=con.createStatement();
				for (int i = 0; i < sqls.length; i++) {
					stmt.addBatch(sqls[i]+"");
				}
				int [] rows=stmt.executeBatch();
				con.commit();
				return rows.length;
			}else{
				//HQL或SQL
				for (int i = 0; i < sqls.length; i++) {
					SQLQuery query=this.getSession().createSQLQuery(sqls[i]+"");
					query.list();
				}
				return sqls.length;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			Relesae(null, stmt, con);
		}
		return 0;
	}
	
	/***
	 * 释放资源...
	 * @param rs
	 * @param st
	 * @param conn
	 */
	public static void Relesae(ResultSet rs, Statement st, Connection conn) {
		try {
			if (rs != null)
				rs.close();
			if (st != null)
				st.close();
			if (conn != null)
				conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	 
}

 

 

 

 

 

package com.app.common;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Properties;

import org.apache.log4j.PropertyConfigurator;

public class PropertyUtil {
	
	protected static Properties pro = null;
	protected static InputStream is = null;
	private static File file = null;
	private static long fileLastModified = 0L;

	public static synchronized Properties getInstance() {
		if(pro==null){
			  pro=new Properties();
		}
		return pro;
	}
	/**
	 * 初始化
	 */
	private static void init() {
		URL url = PropertyUtil.class.getClassLoader().getResource(
				"/jdbc.properties");
		file = new File(url.getFile());
		fileLastModified = file.lastModified();
		pro = new Properties();
		load();
	}
	/**
	 * 加载
	 */
	private static void load() {
		try {
			pro.load(new FileInputStream(file));
			fileLastModified = file.lastModified();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	/**
	 * 获取key
	 * @param key
	 * @return
	 */
	public static String getProperty(String key) {
		if ((file == null) || (pro == null)) {
			init();
		}
		if (file.lastModified() > fileLastModified) {
			load();
		}
		return pro.getProperty(key);
	}

	/**
	 * @param key
	 * @return
	 */
	public static String getLog4jConfigKey(String key) {
		String strVal = "";
		String path="/jdbc.properties";
		try {
			// is=PropertyUtil.class.getClass().getResourceAsStream(path);
			is = new FileInputStream(new File(path));
			pro = new Properties();
			pro.load(is);

			PropertyConfigurator.configure(pro);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		strVal = (String) pro.getProperty(key);
		return strVal;
	}
	
}

 数据库配置:jdbc.properties

#################################MYSQL#############################################
jdbc.url=jdbc:mysql://localhost:3306/moa?characterEncoding=GBK
jdbc.username=root
jdbc.password=root
jdbc.driver=com.mysql.jdbc.Driver

 

 

spring定时器配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">

        <!-- 要调用的工作类 -->
        <bean id="duApp" class="com.app.timer.DuApp"/>
        
         <bean id="taskDuApp" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
            <property name="targetObject" ref="duApp"/>
            <property name="targetMethod" value="doDeocoder"/>
        </bean>
        
        
        <bean id="TriggerDuApp" class="org.springframework.scheduling.quartz.CronTriggerBean">
		<property name="jobDetail">
			<ref bean="taskDuApp"/>
		</property>
              <property name="cronExpression">
				<!--<value>0 0 12 ? * *</value> -->
				<value>0 33 20 * * ?</value>
            </property>
        </bean>
        
        <!-- 总管理类 如果将lazy-init='false'那么容器启动就会执行调度程序  -->
        <bean autowire="no" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
            <property name="triggers">
                <list>
			<!--   <ref bean="TriggerQuart"/>
		 	  <ref bean="TriggerSpider"/> -->
		 	  <ref bean="TriggerDuApp"/>
                </list>
            </property>
        </bean>
    
</beans>

 数据库脚步

-- ----------------------------
-- Table structure for `geocodersearch`
-- ----------------------------
DROP TABLE IF EXISTS `geocodersearch`;
CREATE TABLE `geocodersearch` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `lat` varchar(25) CHARACTER SET gbk DEFAULT '',
  `lng` varchar(25) CHARACTER SET gbk DEFAULT NULL,
  `formatted_address` varchar(150) CHARACTER SET gbk DEFAULT '',
  `business` varchar(150) DEFAULT NULL,
  `streetNumber` varchar(25) CHARACTER SET gbk DEFAULT '',
  `street` varchar(35) CHARACTER SET gbk DEFAULT '',
  `district` varchar(25) CHARACTER SET gbk DEFAULT '',
  `city` varchar(25) CHARACTER SET gbk DEFAULT '',
  `province` varchar(25) CHARACTER SET gbk DEFAULT '',
  `cityCode` varchar(25) CHARACTER SET gbk DEFAULT '',
  `addr` varchar(150) CHARACTER SET gbk DEFAULT '',
  `distance` varchar(150) CHARACTER SET gbk DEFAULT '',
  `name` varchar(150) CHARACTER SET gbk DEFAULT '',
  `poiType` varchar(100) CHARACTER SET gbk DEFAULT '',
  `tel` varchar(15) CHARACTER SET gbk DEFAULT '',
  `zip` varchar(15) CHARACTER SET gbk DEFAULT '',
  `x` varchar(25) CHARACTER SET gbk DEFAULT '',
  `y` varchar(25) CHARACTER SET gbk DEFAULT '',
  `status` varchar(5) CHARACTER SET gbk DEFAULT '',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

 web.xml配置

 

<context-param>
	<param-name>contextConfigLocation</param-name>
	<param-value>/WEB-INF/spring/applicationContextion.xml</param-value>
</context-param>

<listener>
	<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

 定时器测试类

 

package com.app.timer;

import java.util.List;

import com.app.duapp.DeocoderDao;
import com.app.entity.duapp.Geocoder;

/**
 *@DEMO:napp
 *@Author:jilongliang
 *@Date:2013-7-15
 */
public class DuApp {
	public void doDeocoder() {
		DeocoderDao dao=new DeocoderDao();
		String url = "http://api.map.baidu.com/geocoder/v2/?ak=E4805d16520de693a3fe707cdc962045&callback=renderReverse&location=39.983424,116.322987&output=xml&pois=1";
		List<Geocoder> list=dao.readXml(url);
		int result=dao.batchsSaveData(list);
		if(result>0){
			System.out.println("成功保存"+result+"条数据");
		}else{
			System.out.println("保存失败..");
		}
	}
}

 源代码:https://github.com/jilongliang/JL_NAPP.git

  • 大小: 7.2 KB
分享到:
评论

相关推荐

    spring quartz定时任务demo

    在Java开发中,Spring框架与Quartz库的结合使用能够帮助开发者实现强大的定时任务功能。本文将详细解析“spring quartz定时任务demo”这个项目,它提供了实现Java定时任务的实例,便于快速理解和应用。 首先,...

    Spring Quartz定时任务 jar包

    Spring Quartz定时任务是Java开发中常见的一种任务调度框架,它结合了Spring的优秀特性与Quartz的灵活性,使得开发者能够方便地在应用中实现定时任务的管理。在本压缩包中,包含的是`log4j-1.2.14.jar`这个日志处理...

    Spring quartz定时调度jar包

    Spring Quartz 定时调度是Java应用中广泛使用的任务调度框架,它允许开发者在Spring应用程序上下文中定义和管理定时任务。这个jar包包含了Spring与Quartz的整合,使得开发者能够利用Quartz的强大功能,同时享受...

    spring注解Quartz定时执行功能

    Spring通过其优秀的依赖注入(DI)和AOP(面向切面编程)特性,与Quartz相结合,简化了定时任务的配置和管理。下面我们将深入探讨如何利用Spring注解实现Quartz定时执行功能。 首先,我们需要引入Quartz和Spring的...

    Spring Quartz定时作业

    Spring Quartz是一款广泛应用于Java环境下的任务调度框架,它与Spring框架深度集成,使得在Spring应用中配置和管理定时任务变得非常便捷。本项目提供了一套完整的Spring Quartz定时作业的实现,包括任务、触发器和...

    SpringQuartz的使用文档

    总的来说,SpringQuartz结合了Quartz的强大功能和Spring的灵活性,使开发者能够轻松地在应用程序中实现复杂或简单的定时任务调度。通过这种方式,开发人员可以专注于编写业务逻辑,而不用过多关心任务如何被调度和...

    spring之定时任务实现(spring-task和quartz等不同方式)

    Spring框架提供了一系列工具来支持定时任务的实现,其中包括Spring自带的`spring-task`模块和第三方的Quartz库。下面我们将详细探讨这两种方式以及如何通过注解和非注解的方式进行配置。 首先,`spring-task`是...

    spring+quartz定时小例子

    在 "spring+quartz定时小例子" 中,我们主要关注的是如何将这两个框架结合使用,创建一个可以执行定时任务的应用。这个例子包含了相关的框架包和文档,帮助开发者理解并实践这一整合过程。 1. **Spring 配置**: ...

    完美解决多应用服务器负载均衡环境下spring quartz同一定时任务重复执行问题

    Spring Quartz是一个强大的、开源的作业调度框架,允许开发者定义和执行复杂的定时任务。然而,当多个服务器实例并行运行时,如果不采取适当的策略,同一定时任务可能会在每个服务器上都执行,导致数据不一致和资源...

    Spring quartz 定时 实例

    总的来说,Spring Quartz 提供了一种灵活的方式来在Spring应用中调度和执行定时任务,结合了Quartz的强大功能和Spring的IoC特性,使得任务的定义和管理更加简便。在这个实例中,我们看到了如何定义一个简单的任务,...

    spring3配置quartz定时任务

    Quartz提供了一个灵活的API,允许开发者定义作业(Job)和触发器(Trigger),并将其关联到一起,从而实现定时执行。 **一、引入依赖** 要在Spring 3中使用Quartz,首先需要在项目中添加Quartz库的依赖。如果你...

    quartz整合springbatch动态集群定时实现mysql参考

    在这个“quartz_springbatch_dynamic”项目中,我们将看到如何将这两个强大的工具结合起来,以实现动态集群环境中的定时任务执行,并使用MySQL作为数据存储。 Quartz是一个开源的作业调度框架,允许开发者创建、...

    spring整合quartz定时任务调度

    Spring框架作为Java领域广泛使用的轻量级框架,提供了与第三方库Quartz的整合,使得开发者能够轻松地在Spring应用中实现复杂的定时任务调度。Quartz是一款开源的作业调度框架,支持丰富的调度策略,可以满足各种定时...

    Spring Quartz 动态暂停、恢复、修改定时任务

    Spring Quartz 动态暂停、恢复、修改定时任务的一个demo,使用maven构建,框架采用spring springmvc jpa,数据库mysql,含数据库脚本,运行可用,页面访问地址http://localhost:8080/quartz_demo/quartz/list

    spring-quartz定时设置详细说明

    将它们结合使用,我们可以实现基于 Spring 的应用程序中的定时任务管理。以下是对 "spring-quartz 定时设置详细说明" 的详细解释。 一、Quartz 简介 Quartz 是一个开源的作业调度框架,可以用来创建、调度和执行...

    spring+quartz动态定时任务创建 +mybatis

    总的来说,Spring、MyBatis和Quartz的结合,为Java开发者提供了一套强大的工具集,可以方便地构建和管理具有动态定时任务功能的企业级应用。这种技术栈的使用,不仅可以提高开发效率,还能保证应用的稳定性和扩展性...

    java spring quartz 动态定时任务

    Spring与Quartz的结合使用,使得我们可以方便地在Spring框架下管理定时任务,同时还能实现任务的动态添加、修改和删除。 Quartz是一个开源的作业调度框架,支持丰富的调度策略,包括简单的定时执行、按日程表执行...

    Spring quartz 定时任务调度

    Spring Quartz 是一个强大的开源任务调度框架,它允许开发者在Java应用程序中定义和执行定时任务。在Spring框架中集成Quartz,可以充分利用Spring的IoC(Inversion of Control)和AOP(Aspect Oriented Programming...

Global site tag (gtag.js) - Google Analytics