springMVC+Hibernate+cxf+druid

小弟初写博文,有些东东还在摸索中。

各位大哥,大姐,有钱的捧个钱场,没钱的捧个人场,小弟献丑了!

最近闲来无事,用springMVC+Hibernate+druid 搭建了一个webService的框架,这个框架已经在用。还有一些不满意的地方,希望大家及时提出来,共同进步哦!

废话不多说,直接上代码:

首先来看下 web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	id="unimng" metadata-complete="true" version="2.5">
	<display-name>taxrefund</display-name>
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>
			classpath:applicationContext.xml
		</param-value>
	</context-param>

	<!-- log4j 配置文件 -->
	<context-param>
		<param-name>log4jConfigLocation</param-name>
		<param-value>classpath:log4j.properties</param-value>
	</context-param>

	<context-param>
		<param-name>log4jRefreshInterval</param-name>
		<param-value>3000</param-value>
	</context-param>
	<listener>
		<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
	</listener>
	
	<!-- 字符集 配置文件 -->
	<filter>
		<filter-name>encodingFilter</filter-name>
		<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
		<init-param>
			<param-name>encoding</param-name>
			<param-value>UTF-8</param-value>
		</init-param>
		<init-param>
			<param-name>forceEncoding</param-name>
			<param-value>true</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>encodingFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

	<!-- spring 监听文件 -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	<listener>
		<listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
	</listener>

	<!-- cxf 配置文件 -->
	<servlet>
		<servlet-name>CXFServlet</servlet-name>
		<servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:applicationContext-service.xml</param-value>
		</init-param>
		<load-on-startup>0</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>CXFServlet</servlet-name>
		<url-pattern>/services/*</url-pattern>
	</servlet-mapping>

	<!-- springMVC 配置文件 -->
	<servlet>
		<servlet-name>springmvc</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:springmvc-servlet.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>springmvc</servlet-name>
		<url-pattern>/*</url-pattern>
	</servlet-mapping>

	<!-- Druid 数据源 配置文件-->
	<servlet>
		<servlet-name>DruidStatView</servlet-name>
		<servlet-class>com.alibaba.druid.support.http.StatViewServlet</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>DruidStatView</servlet-name>
		<url-pattern>/druid/*</url-pattern>
	</servlet-mapping>
 	
 	<welcome-file-list>
 		<welcome-file>index.jsp</welcome-file>
 	</welcome-file-list>
</web-app>
然后呢,是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:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="
     http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-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/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
     http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"
       default-lazy-init="true"> 

	<!-- 加载xml文件 -->
	<import resource="classpath:applicationContext-main.xml"/>     <!-- properties资源 -->
	<import resource="classpath:applicationContext-db.xml"/>       <!-- 数据库连接 -->
	<import resource="classpath:springmvc-servlet.xml"/>           <!-- springMvc配置 -->
	<import resource="classpath:applicationContext-service.xml"/>  <!-- spring-cxf-service配置 -->
	<import resource="classpath:applicationContext-dubbo.xml" />   <!-- 调用外部的服务 -->
</beans> 
接下来一个一个介绍配置文件 

1、 applicationContext-main.xml 

jdbc.properties 这个属性文件里的内容就不提供了。

<?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"
	xmlns:context="http://www.springframework.org/schema/context"
	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/aop
                        http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">

	<!-- 属性文件读入,使用Spring中的PropertyPlaceholderConfigurer则可以读取配置信息 -->
	<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
		<property name="ignoreResourceNotFound" value="true" />
		<property name="locations">
			<list>
				<value>classpath:jdbc.properties</value>
			</list>
		</property>
	</bean>
	
</beans>
2、applicationContext-db.xml

<span style="font-size:10px;color:#330033;"><?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" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:task="http://www.springframework.org/schema/task"
	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/aop
						http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
						http://www.springframework.org/schema/task
						http://www.springframework.org/schema/task/spring-task-3.0.xsd
						http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
	
	
	<!-- 打开Spring的Annotation支持,设定Spring 去哪些包中找Annotation -->
	<context:component-scan base-package="com.tax,com.common.base">
		<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
	</context:component-scan>
	
	<!-- 配置druid数据源 -->
	<bean name="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
		init-method="init" destroy-method="close" >
		
		<property name="url" value="${jdbc.url}" />
		<property name="username" value="${jdbc.username}" />
		<property name="password" value="${jdbc.password}" />
		
		  <!-- 开启Druid的监控统计功能 -->  
        <property name="filters" value="stat" /> 
		 <!-- 配置初始化最大 连接数 -->  
		<property name="maxActive" value="20" />
		<!-- 配置初始化大小 -->    
        <property name="initialSize" value="2" />  
         <!-- 配置获取连接等待超时的时间 --> 
        <property name="maxWait" value="60000" />  
        <!-- 配置初始化最小连接数 --> 
        <property name="minIdle" value="5" />  
  
 		 <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 --> 
        <property name="timeBetweenEvictionRunsMillis" value="60000" />  
        <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->  
        <property name="minEvictableIdleTimeMillis" value="300000" />  
  
  		<!-- 检测连接是否有效的SQL -->  
        <property name="validationQuery" value="${cpool.preferredTestQuery}" />  
        <property name="testWhileIdle" value="true" />  
        <property name="testOnBorrow" value="false" />  
        <property name="testOnReturn" value="false" />  
        <!-- mysql 不支持 poolPreparedStatements-->  
        <!--<property name="poolPreparedStatements" value="true" />-->  
        <!--<property name="maxPoolPreparedStatementPerConnectionSize" value="20" />-->  
  
        <!-- 如果是Oracle/DB2/SQL Server之类支持游标的数据库需要加上以下配置 -->  
        <!-- <property name="maxPoolPreparedStatementPerConnectionSize" value="50"   
            /> -->  
  		
    </bean>  
	
	<!--创建Spring的SessionFactory工厂 -->
	<!-- 如果使用的是Annotation的方式,不能使用LocalSessionFactoryBean,
	而应该使用 org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean -->
	<bean id="sessionFactory"
		class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
		
		<!-- 注入数据源 -->
		<property name="dataSource" ref="dataSource" />
		
		<!-- 设置Spring取那个包中查找相应的实体类 -->
		<property name="packagesToScan">
			<list>
				<value>com.tax.entity</value>
			</list>
		</property>

		<!-- hibernate属性相关配置 -->
		<property name="hibernateProperties">
			<props>
				<prop key="hibernate.dialect">${hibernate.dialect}</prop>
				<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
				<prop key="hibernate.format_sql">true</prop>
				<prop key="hibernate.record_filter">true</prop>
				<prop key="hibernate.jdbc.fetch_size">10</prop>
				<prop key="hibernate.jdbc.batch_size">30</prop>
				<prop key="hibernate.jdbc.use_scrollable_resultset">true</prop>
				<!-- 开启hibernate查询缓存机制 enable the query cache -->
				<prop key="hibernate.cache.provider_class">net.sf.ehcache.hibernate.EhCacheProvider</prop>
				<prop key="hibernate.cache.use_query_cache">false</prop>
				<prop key="hibernate.query.factory_class">org.hibernate.hql.ast.ASTQueryTranslatorFactory</prop>

			</props>
		</property>
	</bean>
	
	<!-- 开启HibernateTemplate,并且为其注入SessionFactory
	使用HibernateTemplate不太方便的就是要获取session得通过getSessionFactory()方法获取 -->
	<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
		<property name="sessionFactory" ref="sessionFactory"/>
	</bean>
	
	<!-- 配置Spring的事务处理 -->
	<!-- 创建事务管理器-->
	<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
	   <property name="sessionFactory">
	    <ref local="sessionFactory"/>
	   </property>
	</bean>
	
	<!-- 配置AOP,Spring是通过AOP来进行事务管理的 -->
	<!-- 基于@Transactional注解方式的事务管理 -->
	<tx:annotation-driven transaction-manager="transactionManager"  proxy-target-class="true"/>
</beans>
</span>

3、springmvc-servlet.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:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
       http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd"
	default-lazy-init="true">

	<context:annotation-config />
	<!-- 让Spring通过自动扫描来查询和管理Bean -->
	<context:component-scan base-package="com.tax,com.common.base" />
	<bean
		class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />

	<!-- json转换器 begin -->
	<bean id="mappingJacksonHttpMessageConverter"
		class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
		<property name="supportedMediaTypes">
			<list>
				<value>application/json;charset=UTF-8</value>
			</list>
		</property>
	</bean>

	<bean
		class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
		<property name="messageConverters">
			<list>
				<ref bean="mappingJacksonHttpMessageConverter" />
			</list>
		</property>
	</bean>

	<!--  spring拦截器 
	<mvc:interceptors>
		<mvc:interceptor>
			<mvc:mapping path="/admin/**"/>
			<bean class="com.tax.interceptor.SslConnectInterceptor" /> 
		</mvc:interceptor>
	</mvc:interceptors>
-->
	<!-- json转换器 end -->

	<!-- 对模型视图名称的解析,即在模型视图名称添加前后缀 -->
	<bean id="viewResolver"
		class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
		<property name="contentType" value="text/html; charset=UTF-8" />
		<property name="suffix" value=".jsp" />
	</bean>

	<!-- 控制文件上传 -->
	<bean id="multipartResolver"
		class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<property name="defaultEncoding" value="UTF-8" />
		<property name="maxUploadSize" value="32505856" /><!-- 上传文件大小限制为31M,31*1024*1024 -->
		<property name="maxInMemorySize" value="4096" />
	</bean>

</beans>

4、接下来是 spring跟cxf的配置 applicationContext-service.xml

这里面定义了要发布的service,拦截器。

拦截器是为了安全认证,所有访问webServcie都需要有IP地址的认证和签名的认证

<?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:jaxws="http://cxf.apache.org/jaxws"
	xmlns:cxf="http://cxf.apache.org/core" xmlns:soap="http://cxf.apache.org/bindings/soap"
	xmlns:http-conf="http://cxf.apache.org/transports/http/configuration"

	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:task="http://www.springframework.org/schema/task"
	xsi:schemaLocation="http://cxf.apache.org/core 
						http://cxf.apache.org/schemas/core.xsd
						http://www.springframework.org/schema/beans 
						http://www.springframework.org/schema/beans/spring-beans.xsd 
						http://cxf.apache.org/jaxws 
						http://cxf.apache.org/schemas/jaxws.xsd 
						http://cxf.apache.org/transports/http/configuration 
						http://cxf.apache.org/schemas/configuration/http-conf.xsd ">


	<!-- 在服务器端设置响应超时限制,现在使用的是默认值60秒 -->
	<http-conf:destination name="*.http-conduit">
		<http-conf:server ReceiveTimeout="60000" />
	</http-conf:destination>

	<!-- 导入与CXF框架有关的xml 这些xml文件都在cxf.jar包下 -->
	<import resource="classpath:META-INF/cxf/cxf.xml" />
	<import resource="classpath:META-INF/cxf/cxf-extension-soap.xml" />
	<import resource="classpath:META-INF/cxf/cxf-servlet.xml" />

	<!-- cxf自带拦截器 -->
	<bean id="logIn" class="org.apache.cxf.interceptor.LoggingInInterceptor" />
	<bean id="logOut" class="org.apache.cxf.interceptor.LoggingOutInterceptor" />
	<bean id="saajIn" class="org.apache.cxf.binding.soap.saaj.SAAJInInterceptor" />

	<!-- CXF IP地址输入拦截器 -->
	<bean id="ipInterceptor" class="com.tax.interceptor.IpAddressInInterceptor" />
	<!-- CXF 签名输入拦截器 -->
	<bean id="signInterceptor" class="com.tax.interceptor.SignInInterceptor" />

	<bean id="ClientInterceptor" class="com.tax.interceptor.ClientInterceptor" />

	<!-- 公用的拦截器 用于服务端 -->
	<cxf:bus>
		<cxf:inInterceptors>
			<ref bean="logIn" />
			<ref bean="saajIn" />
			<ref bean="ipInterceptor" />
			<ref bean="signInterceptor" />
		</cxf:inInterceptors>

	</cxf:bus>

	<!-- webService接口开始 -->

	<!--xxxxx 接口服务 -->
	<jaxws:endpoint id="testService"
		implementor="com.tax.webService.impl.WTestServiceImpl" address="/TestService">
	</jaxws:endpoint>
	<!-- xxxxx 接口服务 -->
	
	<!-- webService接口结束 -->
</beans> 
至此,所有的配置文件加载完毕!

接下来咱们看看拦截器的实现,首先是IP地址拦截器  ipInterceptor.java

package com.tax.interceptor;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.message.Message;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase;
import org.apache.cxf.transport.http.AbstractHTTPDestination;
import org.apache.log4j.Logger;

import com.tax.entity.BaseAgentIp;
import com.tax.service.BaseAgentIpService;
import com.tax.util.HttpUtils;

/**
 * IP地址拦截器 IpAddressInInterceptor
 * 
 * @author <span style="font-family: Arial, Helvetica, sans-serif;">Mr.Zhang</span>
 *
 */
public class IpAddressInInterceptor extends AbstractPhaseInterceptor<Message> {

	private Logger logger = Logger.getLogger(IpAddressInInterceptor.class);

	/* 注入用于获取IP地址的service */
	@Resource(name = "baseAgentIpService")
	private BaseAgentIpService agentIpService;

	public IpAddressInInterceptor(String phase) {
		super(phase);
	}

	public IpAddressInInterceptor() {
		super(Phase.RECEIVE);
	}

	public void handleMessage(Message message) throws Fault {

		System.out.println("进入 ipInterceptor.......................");

		HttpServletRequest request = (HttpServletRequest) message.get(AbstractHTTPDestination.HTTP_REQUEST);
		
		List<BaseAgentIp> allowedList = agentIpService.findAll(); // 从数据库获取允许访问的IP地址

		String ipAddress = HttpUtils.getIpAddr(request); // 取客户端IP地址

		// 如果访问的集合非空,继续处理,否则认为全部IP地址均合法
		if (allowedList.size() > 0) {
			boolean contains = false;
			for (BaseAgentIp allowedIpAddress : allowedList) {
				if (allowedIpAddress.getIpAddress().equals(ipAddress)) {
					contains = true;
					break;
				}
			}
			if (!contains) {
				throw new Fault(new IllegalAccessException("请求Ip地址错误!"));
			}
		}
	}

	@Override
	public void handleFault(Message msg) {
		Exception exeption = msg.getContent(Exception.class);
		logger.error(exeption.getMessage(), exeption);
	}

}
其次是 signInterceptor

package com.tax.interceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPHeader;
import javax.xml.soap.SOAPMessage;

import org.apache.cxf.binding.soap.SoapMessage;
import org.apache.cxf.binding.soap.saaj.SAAJInInterceptor;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.message.Message;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase;
import org.apache.cxf.transport.http.AbstractHTTPDestination;
import org.apache.log4j.Logger;
import org.w3c.dom.NodeList;

import com.sun.xml.internal.messaging.saaj.SOAPExceptionImpl;
import com.tax.entity.BaseAgentIp;
import com.tax.service.BaseAgentIpService;
import com.tax.util.HttpUtils;
import com.tax.util.SessionConstants;
import com.tonghui.tras.rpc.TrarpcException;

/**
 * 【验证soapHead的签名信息】 SignInInterceptor
 * 
 * @author Mr.Zhang
 */
public class SignInInterceptor extends AbstractPhaseInterceptor<SoapMessage> {

	private final Logger logger = Logger.getLogger(SignInInterceptor.class);

	/* 注入用于获取IP地址的service */
	@Resource(name = "baseAgentIpService")
	private BaseAgentIpService agentIpService;

	private SAAJInInterceptor saajIn = new SAAJInInterceptor();
	

	private String localPart = "authHeader";

	public SignInInterceptor() {
		super(Phase.PRE_INVOKE);
		getAfter().add(SAAJInInterceptor.class.getName());
	}

	@Override
	public void handleMessage(SoapMessage mess)  throw <span style="font-family: Arial, Helvetica, sans-serif;">Fault</span><span style="font-family: Arial, Helvetica, sans-serif;">{</span>

		logger.info(">>>>>>>>>>>>>>>>>>signInInterceptor start<<<<<<<<<<<<<<<<<<<<");
		HttpServletRequest request = (HttpServletRequest) mess
				.get(AbstractHTTPDestination.HTTP_REQUEST);
		try {
			SOAPMessage doc = mess.getContent(SOAPMessage.class);
			if (doc == null) {
				saajIn.handleMessage(mess);
				doc = mess.getContent(SOAPMessage.class);
			}

			SOAPHeader head = doc.getSOAPHeader();
			if (head == null) {
				SOAPException soapExc = new SOAPException("没有head信息");
				throw new Fault(soapExc);
			}
			
			NodeList nodes = head.getElementsByTagName(localPart);
			if(nodes == null) {
				SOAPException soapExc = new SOAPException("没有head信息");
				throw new Fault(soapExc);
			}
			
			/*
			 *  读取自定义的节点
			 */
			// 版本号
			NodeList version = head.getElementsByTagName("version"); 
			String versionStr = version.item(0).getTextContent();
			
			// 接口ID
			NodeList serviceId = head.getElementsByTagName("serviceId"); 
			String serviceIdStr = serviceId.item(0).getTextContent();
			
			// 渠道编号
			NodeList canalId = head.getElementsByTagName("canalId"); 
			String canalIdStr = canalId.item(0).getTextContent();
			
			// 请求时间
			NodeList requestdate = head.getElementsByTagName("requestDate"); 
			String requestdateStr = requestdate.item(0).getTextContent();
			
			/**
			 * 保证与服务器时间前后相差不大于2分钟     当前时间 -请求时间  <= 2
			*/
			long nd = 1000*24*60*60;//一天的毫秒数
			long nh = 1000*60*60;//一小时的毫秒数
			long nm = 1000*60;//一分钟的毫秒数
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date nowDate =  new Date();
			Date requestDate = df.parse(requestdateStr);
			long ddff = nowDate.getTime() - requestDate.getTime();
			long min = ddff%nd%nh/nm;//计算差多少分钟
			if(min > 2){
				SOAPException soapExc = new SOAPException("认证超时!");
				throw new Fault(soapExc);
			}
			
			// 字符编码
			NodeList charset = head.getElementsByTagName("charset"); 
			String charsetStr = charset.item(0).getTextContent();
			
			// 签名
			NodeList signature = head.getElementsByTagName("signature"); 
			String signStr = signature.item(0).getTextContent();
			
			//随机数
			NodeList nonce = head.getElementsByTagName("nonce");
			String nonceStr = nonce.item(0).getTextContent();
			
			// 根据IP地址获取secret_key
			String ipAddress = HttpUtils.getIpAddr(request); // 取客户端IP地址
			Integer port = request.getRemotePort(); // 获取端口号
			BaseAgentIp baseAgentIp = agentIpService.getTokenByIp(ipAddress);
			String secretKey = baseAgentIp.getSecretKey();

			// 拼接签名信息
			String[] getSignStr = null;

			// a
			if (canalIdStr.equals("a")) {
				getSignStr = new String[] { "version=" + versionStr,
						"&serviceId=" + serviceIdStr, "&canalId=a",
						"&requestDate=" + requestdateStr, "&signMethod=MD5",
						"&charset=" + charsetStr,"&nonce="+nonceStr,
						"&secret_key=" + secretKey.toUpperCase() };
			}
			//b
			if (canalIdStr.equals("b")) {
				getSignStr = new String[] { "version=" + versionStr,
						"&serviceId=" + serviceIdStr, "&canalId=b",
						"&requestDate=" + requestdateStr, "&signMethod=MD5",
						"&charset=" + charsetStr,"&nonce="+nonceStr,
						"&secret_key=" + secretKey.toUpperCase() };
			}
			//o2o
			if (canalIdStr.equals("c")) {
				getSignStr = new String[] { "version=" + versionStr,
						"&serviceId=" + serviceIdStr, "&canalId=c",
						"&requestDate=" + requestdateStr, "&signMethod=MD5",
						"&charset=" + charsetStr,"&nonce="+nonceStr,
						"&secret_key=" + secretKey.toUpperCase() };
			}
			if (getSignStr == null) {
				SOAPException soapExc = new SOAPException("签名错误");
				throw new Fault(soapExc);
			} else {
				if (HttpUtils.checkSign(getSignStr, signStr)) {
					// 将请求的信息保存在session中
					SessionConstants.clearValues();
					SessionConstants.setValues(requestdateStr, canalIdStr,
							ipAddress, port.toString());
					logger.info("认证成功");
				} else {
					SOAPException soapExc = new SOAPException("签名错误");
					throw new Fault(soapExc);
				}
			}
			logger.info(">>>>>>>>>>>>>>>>>>signInInterceptor end<<<<<<<<<<<<<<<<<<<<");

		} catch (Exception e) {
			throw new Fault(e);
		}
	}
	
}

未完待续............
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值