`
kingxss
  • 浏览: 969547 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论
收藏列表
标题 标签 来源
Hibernate3+Spring3+Oracle10声明事务
<?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:context="http://www.springframework.org/schema/context"
	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.5.xsd
           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
           http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">

	<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="locations">
			<list>
				<value>classpath:jdbc.properties</value>
			</list>
		</property>
	</bean>

	<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
		<property name="driverClass"><value>${db.driver}</value></property>
		<property name="jdbcUrl"><value>${db.url}</value></property>
		<property name="user"><value>${db.username}</value></property>
		<property name="password"><value>${db.password}</value></property>
		<property name="minPoolSize" value="5" />
		<property name="maxPoolSize" value="30" />
		<property name="initialPoolSize" value="10" />
		<property name="maxIdleTime" value="60" />
		<property name="acquireIncrement" value="5" />
		<property name="maxStatements" value="0" />
		<property name="idleConnectionTestPeriod" value="60" />
	</bean>

	<!--	Hibernate start -->
	<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
		<property name="dataSource">  
            <ref bean="dataSource" />  
        </property> 
		<property name="mappingDirectoryLocations">
			<list>
				<value>classpath:hibernate-cfg</value>
			</list>
		</property>
		<property name="hibernateProperties">
			<props>
				<prop key="hibernate.dialect">${db.dialect}</prop>
				<prop key="hibernate.jdbc.fetch_size">50</prop>
				<prop key="hibernate.jdbc.batch_size">10</prop>
				<prop key="hibernate.show_sql">false</prop>
				<prop key="hibernate.cache.provider_class">org.hibernate.cache.HashtableCacheProvider</prop>
			</props>
		</property>
	</bean>

	<bean id="HibernateTransactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory" />
	</bean>
	
	<tx:advice id="HibernateTxAdvice" transaction-manager="HibernateTransactionManager">
		<tx:attributes>
			<tx:method name="*" read-only="true" />
			<tx:method name="add*" propagation="REQUIRED" rollback-for="java.lang.Exception" />
			<tx:method name="save*" propagation="REQUIRED" rollback-for="java.lang.Exception" />
			<tx:method name="modify*" propagation="REQUIRED" rollback-for="java.lang.Exception" />
			<tx:method name="update*" propagation="REQUIRED" rollback-for="java.lang.Exception" />
			<tx:method name="delete*" propagation="REQUIRED" rollback-for="java.lang.Exception" />
			<tx:method name="del*" propagation="REQUIRED" rollback-for="java.lang.Exception" />
			<tx:method name="up*" propagation="REQUIRED" rollback-for="java.lang.Exception" />
			<tx:method name="join*" propagation="REQUIRED" rollback-for="java.lang.Exception" />
			<tx:method name="out*" propagation="REQUIRED" rollback-for="java.lang.Exception" />
			<tx:method name="*Register" propagation="REQUIRED" rollback-for="java.lang.Exception" />
		</tx:attributes>
	</tx:advice>

	<aop:config>
		<aop:pointcut expression="execution(* com.whty.zhgy.web.service..*.*(..))" id="HibernateTransactionPointCut" />
		<aop:advisor advice-ref="HibernateTxAdvice" pointcut-ref="HibernateTransactionPointCut" />
	</aop:config>
	<!-- Hibernate end -->
</beans>
iBatis+Spring3+MySql5.2声明式事务
<!------------------------------- applicationContext.xml -------------------------------->
<?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:p="http://www.springframework.org/schema/p"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xsi:schemaLocation="
           http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
           http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd
           http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">

	<!-- 如果需要数据库能够回滚需要注意如下地方:
		1:需要在方法中捕获mybatis抛出的异常,然后在catch语句中抛出一个Exception,这个时候Spring容器的事务管理就会起作用,会回滚事务。
        2:如果用mysql数据库,需要查看表的Engine是否设置为InnoDB,自动建表的格式为:MyISAM,这中格式的是不支持事务管理的。
   具体参考:http://www.iteye.com/topic/1123069  -->
	
	<!-- 加载资源文件 -->
	<bean id="propertyConfig" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="locations">
			<list>
				<value>classpath:spring-jdbc.properties</value>
			</list>
		</property>
	</bean>
	<!-- 这里的defaultAutoCommit一定要手动设置为false,默认为true。
	     具体可以参考:http://itboat.net/thread-3410-1-1.html -->
	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
		destroy-method="close" 
		p:driverClassName="${db.driver}" 
		p:url="${db.url}"
		p:username="${db.username}" 
		p:password="${db.password}" 
		p:maxActive="10"
		p:maxWait="100" 
		p:poolPreparedStatements="true" 
		p:defaultAutoCommit="false">
	</bean>
	
	<bean id="rmsSqlMapClient" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean">
		<property name="configLocation">
			<value>classpath:ibatis/sql-map-config.xml</value>
		</property>
		<property name="dataSource" ref="dataSource" />
	</bean>
	
	<bean id="rmsBaseSqlMapClientDAO" abstract="true">
		<property name="sqlMapClient" ref="rmsSqlMapClient" />
	</bean>
	
	<bean id="TmRiskRuleDAOImpl" class="com.masapay.rms.domain.dao.impl.TmRiskRuleDAOImpl"	parent="rmsBaseSqlMapClientDAO" />
	<bean id="TtGatewayAcquiringDAOImpl" class="com.masapay.rms.domain.dao.impl.TtGatewayAcquiringDAOImpl"	parent="rmsBaseSqlMapClientDAO" />
	<bean id="TtGatewayOrderDAOImpl" class="com.masapay.rms.domain.dao.impl.TtGatewayOrderDAOImpl"	parent="rmsBaseSqlMapClientDAO" />
	<bean id="TtInstOrderDAOImpl" class="com.masapay.rms.domain.dao.impl.TtInstOrderDAOImpl"	parent="rmsBaseSqlMapClientDAO" />
	<bean id="TtInstOrderResultDAOImpl" class="com.masapay.rms.domain.dao.impl.TtInstOrderResultDAOImpl"	parent="rmsBaseSqlMapClientDAO" />
	<bean id="TtPayInstrutionDAOImpl" class="com.masapay.rms.domain.dao.impl.TtPayInstrutionDAOImpl"	parent="rmsBaseSqlMapClientDAO" />
	<bean id="TtPaymentOrderDAOImpl" class="com.masapay.rms.domain.dao.impl.TtPaymentOrderDAOImpl"	parent="rmsBaseSqlMapClientDAO" />
	<bean id="TtRiskOrderDAOImpl" class="com.masapay.rms.domain.dao.impl.TtRiskOrderDAOImpl"	parent="rmsBaseSqlMapClientDAO" />
	<bean id="TtRiskOrderDetailDAOImpl" class="com.masapay.rms.domain.dao.impl.TtRiskOrderDetailDAOImpl"	parent="rmsBaseSqlMapClientDAO" />
	
	<!-- 由spring管理mybatis的事物 -->
	<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource"></property>
	</bean>

	<!-- 哪些方法的写操作需要事务 -->
	<tx:advice id="ibatisTransaction" transaction-manager="transactionManager">
		<tx:attributes>
			<tx:method name="save*" read-only="false" propagation="REQUIRED" rollback-for="java.lang.Exception"/>
			<tx:method name="insert*" read-only="false" propagation="REQUIRED" rollback-for="java.lang.Exception"/>
			<tx:method name="update*" read-only="false" propagation="REQUIRED" rollback-for="java.lang.Exception"/>
			<tx:method name="delete*" read-only="false" propagation="REQUIRED" rollback-for="java.lang.Exception"/>
		</tx:attributes>
	</tx:advice>
	
	<!-- 配置哪些类的需要进行事务管理 -->
	<aop:config>	
		<aop:advisor pointcut="execution(* com.service.impl.*.*(..))" advice-ref="ibatisTransaction" />
	</aop:config>

</beans>

<!-------------------------- pom.xml -------------------------------->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>demo</groupId>
  <artifactId>spring-mybatis</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>spring-mybatis</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <dependency>
    	<groupId>org.springframework</groupId>
    	<artifactId>spring-aop</artifactId>
    	<version>3.1.2.RELEASE</version>
    </dependency>
    <dependency>
    	<groupId>org.springframework</groupId>
    	<artifactId>spring-beans</artifactId>
    	<version>3.1.2.RELEASE</version>
    </dependency>
    <dependency>
    	<groupId>org.springframework</groupId>
    	<artifactId>spring-context</artifactId>
    	<version>3.1.2.RELEASE</version>
    </dependency>
    <dependency>
    	<groupId>org.springframework</groupId>
    	<artifactId>spring-context-support</artifactId>
    	<version>3.1.2.RELEASE</version>
    </dependency>
    <dependency>
    	<groupId>org.springframework</groupId>
    	<artifactId>spring-core</artifactId>
    	<version>3.1.2.RELEASE</version>
    </dependency>
    <dependency>
    	<groupId>org.springframework</groupId>
    	<artifactId>spring-web</artifactId>
    	<version>3.1.2.RELEASE</version>
    </dependency>
    <dependency>
    	<groupId>org.springframework</groupId>
    	<artifactId>spring-tx</artifactId>
    	<version>3.1.2.RELEASE</version>
    </dependency>
    <dependency>
    	<groupId>org.springframework</groupId>
    	<artifactId>spring-ibatis</artifactId>
    	<version>2.0.8</version>
    </dependency>
    <dependency>
    	<groupId>mysql</groupId>
    	<artifactId>mysql-connector-java</artifactId>
    	<version>5.1.23</version>
    </dependency>
    <dependency>
    	<groupId>log4j</groupId>
    	<artifactId>log4j</artifactId>
    	<version>1.2.12</version>
    </dependency>
    <dependency>
    	<groupId>commons-dbcp</groupId>
    	<artifactId>commons-dbcp</artifactId>
    	<version>1.4</version>
    </dependency>
    <dependency>
    	<groupId>org.aspectj</groupId>
    	<artifactId>aspectjweaver</artifactId>
    	<version>1.6.5</version>
    </dependency>
    <dependency>
    	<groupId>cglib</groupId>
    	<artifactId>cglib-nodep</artifactId>
    	<version>2.2</version>
    </dependency>
	
	<dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.6</version>
      <scope>test</scope>
    </dependency>
	<dependency>
    	<groupId>org.springframework</groupId>
    	<artifactId>spring-test</artifactId>
    	<version>3.1.2.RELEASE</version>
		<scope>test</scope>
    </dependency>
  </dependencies>
</project>
程序中自动加载ApplicationContext对象
<!-- Load applicationContext for the Java project rms-domain -->
<bean id="applicationContextHelper" class="com.masapay.rms.domain.common.util.ApplicationContextHelper"></bean>
     
/** 代码  */
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * ApplicationContextHelper
 * 
 * @Description 系统启动时候自动加载
 * @author Watson Xu
 * @date 2013-3-5 下午5:10:43
 * 
 */
public class ApplicationContextHelper implements ApplicationContextAware {
    private static ApplicationContext appCtx;
    
    /**
     * 此方法可以把ApplicationContext对象inject到当前类中作为一个静态成员变量。
     * @param applicationContext ApplicationContext 对象.
     * @throws BeansException
     */
    @Override
    public void setApplicationContext( ApplicationContext applicationContext ) throws BeansException {
        appCtx = applicationContext;
    }
    
    /**
     * 这是一个便利的方法,帮助我们快速得到一个BEAN
     * @param beanName bean的名字
     * @return 返回一个bean对象
     */
    public static Object getBean(String beanName) throws Exception{
    	if(appCtx == null) {
    		throw new Exception("ApplicationContext do not success inject");
    	} 
        return appCtx.getBean(beanName);
    }
    
}
解析SOAP并使用内省
package com.whty.cityappweb.action;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;

import javax.xml.soap.MessageFactory;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPConnection;
import javax.xml.soap.SOAPConnectionFactory;
import javax.xml.soap.SOAPElement;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPMessage;
import javax.xml.soap.SOAPPart;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.whty.cityappweb.bean.AltWaterFeeInfo;
import com.whty.cityappweb.common.page.BusinessAction;

/**
 * 阿勒泰水费查询
 * 
 * @author Watson Xu
 * @date 2012-12-26 下午08:55:09
 */
public class AltWaterFeeWebAction extends BusinessAction {
	private static final long serialVersionUID = 1L;
	private static final Logger logger = Logger.getLogger(AltWaterFeeWebAction.class);
	
	/**
	 * 初始化应用
	 * @return
	 */
	public String init() {
		if(StringUtils.isEmpty(getAreaCode())) {
			super.areaCode = "654300";
			session.put("areacode", super.areaCode);
		}
		return "initwap";
	}
	
	/**
	 * 水费查询
	 * @return
	 */
	public String infoList() {
		String returnResult =  "infoList";
		try {
			if(StringUtils.isEmpty(roomId) || StringUtils.isEmpty(waterId)) {
				message = "请输入房屋和水表编号";
				returnResult = "initwap";
			} else {
				SOAPMessage sm = sendMessage(getSoapRequest(roomId, waterId));
				/*OutputStream os = new ByteArrayOutputStream();
				sm.writeTo(os);
				System.out.println(os.toString());*/
				
				SOAPBody sb = sm.getSOAPBody();
				NodeList nl = sb.getChildNodes().item(0).getChildNodes().item(0).getChildNodes();
				water = new AltWaterFeeInfo();
				
				Node node = null;
				for (int i = 0 ; i < nl.getLength(); i++) {
					node = nl.item(i);
					if(node.getFirstChild() != null) {
						setProperty(node.getNodeName(), water, node.getFirstChild().getNodeValue());
					}
				}
			}
		} catch (Exception e) {
			//e.printStackTrace();
			logger.info("=========阿勒泰水务查询异常:" + e.toString());
		}
			
		return returnResult;
	}
	
	/**
	 * 打包请求的 SOAPMessage
	 * 
	 * @param roomID
	 * @param waterID
	 * @return
	 * @throws Exception
	 */
	private SOAPMessage getSoapRequest(String roomID, String waterID) throws Exception {
		SOAPMessage message = null;
		MessageFactory messagefactory = MessageFactory.newInstance();
		message = messagefactory.createMessage();
		SOAPPart soappart = message.getSOAPPart();
		SOAPEnvelope se = soappart.getEnvelope();
		se.setAttribute("xmlns:quer","http://queryinfo.yhbest.com");
		
		SOAPBody body = se.getBody();
		SOAPElement be = body.addChildElement(se.createName("QueryWaterFeeInfo", "quer","http://queryinfo.yhbest.com"));
		be.addChildElement("RoomID").addTextNode(roomID);
		be.addChildElement("WaterID").addTextNode(waterID);
		
		message.saveChanges();
		return message;
	}

	/**
	 * 发送请求,获取返回的SOAPMessage
	 * 
	 * @param message
	 * @return
	 * @throws Exception
	 */
	private SOAPMessage sendMessage(SOAPMessage message) throws Exception {
		SOAPConnection connection = SOAPConnectionFactory.newInstance().createConnection();
		SOAPMessage reply = connection.call(message, dest);
		return reply;
	}
	
	
	/**
	 * 描述 : 使用内省.
	 * 
	 * @param <T>  泛型
	 * @param propertyName 属性名称
	 * @param object 要赋值的对象
	 * @param value 属性值
	 * @throws Exception
	 * 
	 */
	private <T> void setProperty(String propertyName, T object, Object value) throws Exception {
		PropertyDescriptor pd2 = new PropertyDescriptor(propertyName, object.getClass());
		Method methodSet = pd2.getWriteMethod();
		methodSet.invoke(object, value);
	}

	/*========================================constants=================================*/
	private final String dest = "http://120.205.99.78/yhbest/services/QueryInfo";
	
	
	/*========================================getter setter=================================*/
	private String roomId;
	private String waterId;
	private AltWaterFeeInfo water;
	private String message;
	
	public String getRoomId() {
		return roomId;
	}

	public void setRoomId(String roomId) {
		this.roomId = roomId.trim();
	}

	public String getWaterId() {
		return waterId;
	}

	public void setWaterId(String waterId) {
		this.waterId = waterId.trim();
	}

	public AltWaterFeeInfo getWater() {
		return water;
	}

	public String getMessage() {
		return message;
	}
	
}
利用CSS使层始终保持在页面底部
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"  xml:lang="zh-CN" lang="zh-CN">
	<head>
		<style type="text/css">
			html,body {
				width:100%;
				height:100%;
				margin:0px;
				padding:0px;
				overflow:hidden;
			}
			#Main {
				position:absolute;
				bottom:0px;
				left:0px;
				width:100%;
				height:100%;
				overflow:auto;
				z-index:1;
			}
			#ToolBar {
				position:absolute;
				bottom:0px;
				right:16px;
				width:100%;
				height:20px;
				text-align:center;
				background:#ccc;
				z-index:2;
				overflow:hidden;
			}
		</style>
	</head>
	<body>
		<div id="ToolBar">固定在页面底部不动</div>
		<div id="Main">
			<p><strong>09即将流行的经典语录</strong></p>
			<div class="clear"> </div>
			<div class="info clearfix">
				<p class="date"> </p>
			</div>
			<div class="blog_content" id="blog_content">TOP1 <br />
				人生的最大遗憾莫过于错误地坚持了不该坚持的,轻易地放弃了不该放弃的…… <br />
				TOP2 <br />
				新式morning call——生前何必久睡,死后自会长眠. <br />
				TOP3 <br />
				使你疲劳的不是远方的高山,而且是你鞋里面的一粒砂子. <br />
				TOP4 <br />
				有时在饭堂排队打饭时最大的欣慰不是前面的人越来越少而是后面等的人越来越多. <br />
				TOP5 <br />
				逆风的方向,更适合飞翔。我不怕万人阻挡,只怕自己投降. <br />
				TOP6 <br />
				酒,装在瓶里像水,喝到肚里闹鬼,说起话来走嘴,走起路来闪腿,半夜起来找水,早上起来后悔,中午酒杯一端还是挺美。 <br />
				TOP7 <br />
				你要不理我我就成包子了…而且还是天津最有名的…嘿嘿… <br />
				TOP8 <br />
				妈妈说人最好不要错过两样东西,最后一班回家的车和一个深爱你的人. <br />
				TOP9 <br />
				我问一个在深圳工作了二十年的朋友:“如果你死后,你的墓志铭打算写点啥?”他说:“我解决了住房问题!” <br />
				TOP10 <br />
				那天看到一位大妈在烧纸,边烧边嘟囔着:收到了全都买基金吧~~ TOP11 <br />
				学问之美,在于使人一头雾水;诗歌之美,在于煽动男女出轨;女人之美,在于蠢得无怨无悔;男人之美,在于说谎说得白日见鬼. <br />
				TOP12 <br />
				如果你看到面前的阴影,别怕,那是因为你的背后有阳光. <br />
				TOP13 <br />
				诸葛亮出山前,也没带过兵!凭啥我就要工作经验? <br />
				TOP14 <br />
				本人made in china,出厂日期1981年X月X日,长180cm,净重67kg。采用人工智能,各部分零件齐全,运转稳定,经二十多年的运行,属信得过产品。该产品手续齐全,无限期包退包换。现因发展需要,诚招志同道合者共同研制开发第二代产品,有意者请联系! <br />
				TOP15 <br />
				干掉熊猫,我就是国宝! <br />
				TOP16 <br />
				我能容忍身材是假的,脸是假的,胸是假的,臀是假的!!!但就是不容忍钱是假的!!!! <br />
				TOP17 <br />
				脱机的人永远不知道联机的人等了她多久…… <br />
				TOP18 <br />
				还能冲动,表示你还对生活有激情,总是冲动,表示你还不懂生活. <br />
				TOP19 <br />
				命运负责洗牌,但是玩牌的是我们自己! <br />
				TOP20 <br />
				问世间情为何物,不过一物降一物~ <br />
				TOP21 <br />
				如果中了一千万,我就去买30套房子租给别人,每天都去收一次房租。哇咔咔~~充实! <br />
				TOP22 <br />
				上帝欲使人灭亡,必先使其疯狂;上帝欲使人疯狂,必先使其买房. <br />
				TOP23 <br />
				我们走得太快,灵魂都跟不上了…… <br />
				TOP24 <br />
				问:你喜欢我哪一点?答:我喜欢你离我远一点! <br />
				TOP25 <br />
				你看得见我打在屏幕上的字,却看不到我掉在键盘上的泪
				<br />
				<br />
			</div>
		</div>
	</body>
</html>
使用HttpURLConnection进行WS通信
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

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;

public class WeatherReport {
	/**
	 * 获取SOAP的请求头,并替换其中的标志符号为用户输入的城市
	 * 
	 * 编写者:watson
	 * 
	 * @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请求发送给服务器端,并返回服务器点返回的输入流
	 * 
	 * 编写者:watson
	 * 
	 * @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");
			HttpURLConnection conn = (HttpURLConnection)url.openConnection();
			conn.setRequestMethod("POST");
			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");
			conn.setUseCaches(false);
			conn.setDoInput(true);
			conn.setDoOutput(true);
			
			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进行解析
	 * 
	 * 编写者:watson
	 * 
	 * @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();
			for (int count = 0; count < nl.getLength(); count++) {
				Node n = nl.item(count);
				Node temp = n.getFirstChild();
				if(temp == null || "查询结果为空!".equals(temp.getNodeValue())) {
					sb = new StringBuffer("#") ;
					break ;
				}
				sb.append(n.getFirstChild().getNodeValue() + "#\n");
			}
			is.close();
			return sb.toString();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	public static void main(String[] args) {
		Map<String, String> cities;
		cities = new HashMap<String, String>();
		cities.put("440100", "南宁"); 
		//cities.put("440300", "柳州"); 
		//cities.put("441900", "玉林"); 
		//cities.put("440700", "桂林");

		Set<?> set = cities.keySet();

		for (Object object : set) {
			String weather = null;
			int count = 0;
			do{
				weather = WeatherReport.getWeather(cities.get(object));
				System.out.println(weather);
				count++;
			}while(count < 10 && ((weather == null) || (weather.equals("")) || ("#".equals(weather))));
			
			if((weather != null) && (!weather.equals("")) && (!"#".equals(weather))) {
				//JDBCDemo.insertWeather(weather, object.toString(), cities.get(object));
			}
		}
	}
}
使用JDK的soap包进行Web Service通信
import javax.xml.soap.MessageFactory;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPConnection;
import javax.xml.soap.SOAPConnectionFactory;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPMessage;
import javax.xml.soap.SOAPPart;

public class WeatherReport2 {
	private final String dest = "http://www.webxml.com.cn/WebServices/WeatherWebService.asmx";
	
	public SOAPMessage getSoapRequest(String cityName) throws Exception {
		SOAPMessage message = null;
		MessageFactory messagefactory = MessageFactory.newInstance();
		message = messagefactory.createMessage();
		SOAPPart soappart = message.getSOAPPart();
		SOAPEnvelope se = soappart.getEnvelope();
		se.setAttribute("xmlns:web","http://WebXml.com.cn/");
		
		SOAPBody body = se.getBody();
		body.addChildElement(se.createName("getWeatherbyCityName", "web","http://WebXml.com.cn/"))
		.addChildElement("theCityName","web")
		.addTextNode(cityName);
		
		message.saveChanges();
		return message;
	}

	public SOAPMessage sendMessage(SOAPMessage message) throws Exception {
		SOAPConnection connection = SOAPConnectionFactory.newInstance().createConnection();
		SOAPMessage reply = connection.call(message, dest);
		return reply;
	}
	
	public static void main(String[] args) {
		WeatherReport2 wr = new WeatherReport2();
		try {
			SOAPMessage sendMessage = wr.getSoapRequest("上海");
			SOAPMessage replyMessage = wr.sendMessage(sendMessage);
			replyMessage.writeTo(System.out);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
HibernateTemplate通用DAO
import java.io.Serializable;
import java.sql.SQLException;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.springframework.dao.DataAccessException;

public interface ICommonDao<T> {
	/**
	 * SQL通用操作
	 * 
	 * @param sql
	 * @throws HibernateException
	 * @throws SQLException
	 */
	public void excuteBySql(String sql) throws HibernateException, SQLException;
	
	/**
	 * SQL通用操作
	 * 
	 * @param sql
	 * @param parameters
	 * @throws HibernateException
	 * @throws SQLException
	 */
	public void excuteBySql(String sql, HashMap<String, Object> parameters) throws HibernateException, SQLException;
	
	/**
	 * 用SQL查询,返回列表
	 * 
	 * @param sql
	 * @return
	 * @throws HibernateException
	 * @throws SQLException
	 */
	public List<Object[]> findListBySql(String sql) throws HibernateException, SQLException;
	
	/**
	 * 用SQL和参数查询,返回列表
	 * 
	 * @param sql
	 * @param parameters
	 * @return
	 * @throws HibernateException
	 * @throws SQLException
	 */
	public List<Object[]> findListBySql(String sql, HashMap<String, Object> parameters) throws HibernateException, SQLException;
	
	/**
	 * 用SQL、页码和页大小查询,返回分页列表
	 * 
	 * @param sql
	 * @param currentPage
	 * @param maxPerPage
	 * @return
	 * @throws HibernateException
	 * @throws SQLException
	 */
	public List<Object[]> pageListBySql(String sql, Integer currentPage, Integer maxPerPage) throws HibernateException, SQLException;
	
	/**
	 * 用SQL、参数、页码和页大小查询,返回分页列表
	 * @param sql
	 * @param parameters
	 * @param currentPage
	 * @param maxPerPage
	 * @return
	 * @throws HibernateException
	 * @throws SQLException
	 */
	public List<Object[]> pageListBySql(String sql, HashMap<String, Object> parameters, Integer currentPage, Integer maxPerPage) throws HibernateException, SQLException;
	
	/**
	 * 使用SQL查询记录总数
	 * 
	 * @param sql
	 * @param parameters
	 * @return
	 * @throws HibernateException
	 * @throws SQLException
	 */
	public Integer getRecordNumberBySql(String sql, HashMap<String, Object> parameters) throws HibernateException, SQLException;
	
	/**
	 * HQL通用操作
	 * 
	 * @param sql
	 * @throws HibernateException
	 * @throws SQLException
	 */
	public void excuteByHql(String hql) throws HibernateException, SQLException;	
	
	/**
	 * HQL通用操作
	 * 
	 * @param sql
	 * @throws HibernateException
	 * @throws SQLException
	 */
	public void excuteByHql(String hql,HashMap<String, Object> parameters) throws HibernateException, SQLException;
	
	/**
	 * 用HQL查询,返回列表
	 * 
	 * @param sql
	 * @param parameters
	 * @return
	 * @throws HibernateException
	 * @throws SQLException
	 */
	public List<T> findListByHql(String hql) throws HibernateException, SQLException;
	
	/**
	 * 用HQL和参数查询,返回列表
	 * 
	 * @param sql
	 * @param parameters
	 * @return
	 * @throws HibernateException
	 * @throws SQLException
	 */
	public List<T> findListByHql(String hql, HashMap<String, Object> parameters) throws HibernateException, SQLException;
	
	/**
	 * 用HQL、页码和页大小查询,返回分页列表
	 * @param sql
	 * @param parameters
	 * @param currentPage
	 * @param maxPerPage
	 * @return
	 * @throws HibernateException
	 * @throws SQLException
	 */
	public List<T> pageListByHql(String hql, Integer currentPage, Integer maxPerPage) throws HibernateException, SQLException;	
	
	/**
	 * 用HQL、参数、页码和页大小查询,返回分页列表
	 * @param sql
	 * @param parameters
	 * @param currentPage
	 * @param maxPerPage
	 * @return
	 * @throws HibernateException
	 * @throws SQLException
	 */
	public List<T> pageListByHql(String hql, HashMap<String, Object> parameters, Integer currentPage, Integer maxPerPage) throws HibernateException, SQLException;	
	
	/**
	 * 使用HQL查询记录总数
	 * 
	 * @param sql
	 * @param parameters
	 * @return
	 * @throws HibernateException
	 * @throws SQLException
	 */
	public Integer getRecordNumberByHql(String hql, HashMap<String, Object> parameters) throws HibernateException, SQLException;
	
	/**
	 * 根据类型和ID获取对象
	 * 
	 * @param clazz
	 * @param id
	 * @return
	 * @throws DataAccessException
	 */
	public Object get(Class<T> clazz, Serializable id) throws DataAccessException;
	
	/**
	 * 删除对象
	 * 
	 * @param obj
	 * @throws DataAccessException
	 */
	public void delete(Object obj) throws DataAccessException;
	
	/**
	 * 根据类型和ID删除对象
	 * 
	 * @param clazz
	 * @param id
	 * @throws DataAccessException
	 */
	public void delete(Class<T> clazz, Serializable id) throws DataAccessException;
	
	/**
	 * 保存对象
	 * 
	 * @param obj
	 * @throws DataAccessException
	 */
	public void save(Object obj) throws DataAccessException;
	
	/**
	 * 更新对象,对象在库中必须有对应的ID
	 * 
	 * @param obj
	 * @throws DataAccessException
	 */
	public void update(Object obj) throws DataAccessException;
	
	/**
	 * 更新或插入
	 * 
	 * @param obj
	 * @throws DataAccessException
	 */
	public void saveOrUpdate(Object obj) throws DataAccessException;
	
	/**
	 * 批量更新或插入
	 * 
	 * @param entities
	 * @throws DataAccessException
	 */
	public void saveOrUpdateAll(Collection<Object> entities) throws DataAccessException;
	
	/**
	 * 获取hibernate的session
	 * 
	 * @return
	 * @throws HibernateException
	 */
	public Session getsSession() throws HibernateException;
}







import java.io.Serializable;
import java.sql.SQLException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

/**
 * 数据库操作通用类
 * 
 * @author Watson Xu
 * @date 2012-11-20 下午03:25:24
 */
public class CommonDaoT<T> extends HibernateDaoSupport implements ICommonDao<T> {	
	@Override
	public void excuteBySql(final String sql) throws HibernateException, SQLException {
		excuteByHql(sql, null);
	}
	
	@Override
	public void excuteBySql(final String sql, final HashMap<String, Object> parameters) throws HibernateException, SQLException {
		getHibernateTemplate().executeWithNativeSession(new HibernateCallback() {
			public Object doInHibernate(Session session) throws HibernateException {
				Query query = session.createSQLQuery(sql);
				if(parameters != null) {
					Iterator<String> it = parameters.keySet().iterator();
					while (it.hasNext()) {
						String key = (String) it.next();
						query.setParameter(key, parameters.get(key));
					}
				}
				return query.executeUpdate();
			}
		});
	}
	
	@Override
	public List<Object[]> findListBySql(String sql) throws HibernateException, SQLException {
		return pageListBySql(sql, null, null, null);
	}
	
	@Override
	public List<Object[]> findListBySql(String sql, HashMap<String, Object> parameters) throws HibernateException, SQLException {
		return pageListBySql(sql, parameters, null, null);
	}
	
	@Override
	public List<Object[]> pageListBySql(String sql, Integer currentPage, Integer maxPerPage) throws HibernateException, SQLException {
		return pageListBySql(sql, null, currentPage, maxPerPage);
	}
	
	@Override
	@SuppressWarnings("unchecked")
	public List<Object[]> pageListBySql(final String sql, final HashMap<String, Object> parameters, final Integer currentPage, final Integer maxPerPage) throws HibernateException, SQLException {
		return (List<Object[]>) this.getHibernateTemplate().executeWithNativeSession(new HibernateCallback() {
			public List<Object[]> doInHibernate(Session session) throws HibernateException, SQLException {
				List<Object[]> list = null;
				Query query = session.createSQLQuery(sql);
				
				if(parameters != null) {
					Iterator<String> it = parameters.keySet().iterator();
					while (it.hasNext()) {
						String key = (String) it.next();
						query.setParameter(key, parameters.get(key));
					}
				}
				
				if(currentPage != null && maxPerPage != null) {
					int start;
					if (currentPage <= 0) {
						start = 0;
					} else {
						start = (currentPage - 1) * maxPerPage;
					}
					query.setFirstResult(start);
					query.setMaxResults(maxPerPage);
				}
				list = query.list();
				return list;
			}
		});
	}
	
	@Override
	public Integer getRecordNumberBySql(final String sql, final HashMap<String, Object> parameters) throws HibernateException, SQLException{
		return (Integer)getHibernateTemplate().execute(new HibernateCallback(){
			public Integer doInHibernate(Session session) throws HibernateException, SQLException {
				int fromIndex = sql.indexOf("from");
				if(fromIndex < 0) fromIndex = sql.indexOf("FROM");
				
				String q = "SELECT COUNT(*) " + sql.substring(fromIndex);
				Query query =  session.createSQLQuery(q);
				if(parameters != null) { 
					Iterator<String> it = parameters.keySet().iterator();
					while (it.hasNext()) {
						String key = (String) it.next();
						query.setParameter(key, parameters.get(key));
					}
				}
				return Integer.parseInt(query.uniqueResult().toString());
			}
		});
	}
	
	
	@Override
	public void excuteByHql(final String hql) throws HibernateException, SQLException {
		excuteByHql(hql, null);
	}
	
	@Override
	public void excuteByHql(final String hql, final HashMap<String, Object> parameters) throws HibernateException, SQLException {
		getHibernateTemplate().executeWithNativeSession(new HibernateCallback() {
			public Object doInHibernate(Session session) throws HibernateException, SQLException {
				Query query = session.createQuery(hql);
				if(parameters != null) {
					Iterator<String> it = parameters.keySet().iterator();
					while (it.hasNext()) {
						String key = (String) it.next();
						query.setParameter(key, parameters.get(key));
					}
				}
				return query.executeUpdate();
			}
		});
	}
	
	@Override
	public List<T> findListByHql(String hql) throws HibernateException, SQLException {
		return pageListByHql(hql, null, null, null);
	}

	@Override
	public List<T> findListByHql(String hql, HashMap<String, Object> parameters) throws HibernateException, SQLException {
		return pageListByHql(hql, parameters, null, null);
	}

	@Override
	public List<T> pageListByHql(String hql, Integer currentPage, Integer maxPerPage) throws HibernateException, SQLException {
		return pageListByHql(hql, null, currentPage, maxPerPage);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<T> pageListByHql(final String hql, final HashMap<String, Object> parameters, final Integer currentPage, final Integer maxPerPage) throws HibernateException, SQLException {
		return (List<T>) this.getHibernateTemplate().executeWithNativeSession(new HibernateCallback() {
			public List<T> doInHibernate(Session session) throws HibernateException, SQLException {
				List<T> list = null;
				Query query = session.createQuery(hql);
				if(parameters != null) {
					Iterator<String> it = parameters.keySet().iterator();
					while (it.hasNext()) {
						String key = (String) it.next();
						query.setParameter(key, parameters.get(key));
					}
				}
				
				if(currentPage != null && maxPerPage != null) {
					int start;
					if (currentPage <= 0) {
						start = 0;
					} else {
						start = (currentPage - 1) * maxPerPage;
					}
					query.setFirstResult(start);
					query.setMaxResults(maxPerPage);
				}
				list = query.list();
				return list;
			}
		});
	}
	
	@Override
	public Integer getRecordNumberByHql(final String hql, final HashMap<String, Object> parameters) throws HibernateException, SQLException {
		return (Integer)getHibernateTemplate().execute(new HibernateCallback(){
			public Integer doInHibernate(Session session) throws HibernateException, SQLException {
				int fromIndex = hql.indexOf("from");
				if(fromIndex < 0) fromIndex = hql.indexOf("FROM");
				
				String q = "SELECT COUNT(*) " + hql.substring(fromIndex);
				Query query = session.createQuery(q);
				if(parameters != null) {
					Iterator<String> it = parameters.keySet().iterator();
					while (it.hasNext()) {
						String key = (String) it.next();
						query.setParameter(key, parameters.get(key));
					}
				}
				return Integer.parseInt(query.uniqueResult().toString());
			}
		});
	}
	
	@Override
	public Object get(Class<T> clazz, Serializable id) throws DataAccessException {
		Object o = getHibernateTemplate().get(clazz, id);
		return o;
	}

	@Override
	public void delete(Object obj) throws DataAccessException {
		getHibernateTemplate().delete(obj);
	}
	
	@Override
	public void delete(Class<T> clazz, Serializable id) throws DataAccessException {
		Object o = getHibernateTemplate().get(clazz, id);
		getHibernateTemplate().delete(o);
	}
	
	@Override
	public void save(Object obj) throws DataAccessException {
		getHibernateTemplate().save(obj);
	}
	
	@Override
	public void update(Object obj) throws DataAccessException {
		getHibernateTemplate().update(obj);

	}
	
	@Override
	public void saveOrUpdate(Object obj) throws DataAccessException {
		getHibernateTemplate().saveOrUpdate(obj);
	}
	
	@Override
	public void saveOrUpdateAll(Collection<Object> entities) throws DataAccessException {
		getHibernateTemplate().saveOrUpdateAll(entities);
	}

	@Override
	public Session getsSession() throws HibernateException {
		return getSessionFactory().openSession();
	}

}
Global site tag (gtag.js) - Google Analytics