加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Flex+BlazeDS+Spring+Hibernate架构整合示例

发布时间:2020-12-15 00:59:24 所属栏目:百科 来源:网络整理
导读:? ?如下图所示建立工程: 所需lib包一览: 代码如下: StsHibernateTemplate.java package com.stswg.dao.base;import org.hibernate.SessionFactory;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.orm.hibern
?

?如下图所示建立工程:

所需lib包一览:

代码如下:

StsHibernateTemplate.java

package com.stswg.dao.base;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateTemplate;

public class StsHibernateTemplate extends HibernateTemplate {

	@Autowired
	@Override
	public void setSessionFactory(SessionFactory sessionFactory){   
	  super.setSessionFactory(sessionFactory);   
	}
}


CustomerDaoImpl.java

package com.stswg.dao.impl;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.hibernate.Criteria;
import org.hibernate.criterion.Restrictions;

import com.stswg.dao.CustomerDao;
import com.stswg.dao.base.StsHibernateTemplate;
import com.stswg.entity.Customer;

public class CustomerDaoImpl extends StsHibernateTemplate implements CustomerDao {

	private String[] data = {
			"富士康电子","仁宝电脑","富士通软件","太极实业","万科地产","中铁2局","海南航空","德赛电池","东湖高新","哈药集团","太平洋保险","平安保险","太极集团","中粮地产","世贸股份","中国中铁","金山软件","中国银行","建设银行","华阳软件"
	};
	
	@Override
	public int insertCustomer() {
		
		int index = new Double(Math.floor(Math.random() * data.length)).intValue();
		
		Customer customer = new Customer();
		customer.setName(data[index]);
		customer.setAddress(data[index] + "公司所在地址");
		customer.setTelephone("021-67376464");
		save(customer);
		
		return 1;
	}

	@Override
	public int selectCustomerCount() {
		
		Criteria criteria = getSession().createCriteria(Customer.class);
		return criteria.list().size();
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public List<Customer> selectCustomer(String name) {
		
		Criteria criteria = getSession().createCriteria(Customer.class);
		if(StringUtils.isNotEmpty(name)) {
			criteria.add(Restrictions.like("name","%" + name + "%"));
		}
		return criteria.list();
	}

	@Override
	public int deleteCustomer() {
		
		deleteAll(selectCustomer(null));
		
		return 1;
	}
}


?

CustomerDao.java

package com.stswg.dao;

import java.util.List;

import com.stswg.entity.Customer;

public interface CustomerDao {

	public int deleteCustomer();
	
	public int insertCustomer();
	
	public int selectCustomerCount();
	
	public List<Customer> selectCustomer(String name);
}


?

BaseEntity.java

package com.stswg.entity.base;

import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;

@MappedSuperclass
public class BaseEntity {

	@Id
	@GeneratedValue(strategy=GenerationType.IDENTITY)
	private Integer id;
	
	public void setId(Integer id) {
		this.id = id;
	}

	public Integer getId() {
		return id;
	}

	public boolean isNew() {
		return (this.id == null);
	}
}


?

Customer.java

package com.stswg.entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;

import com.stswg.entity.base.BaseEntity;

@Entity
@Table(name="t_customer")
public class Customer extends BaseEntity {

	@Column(name="name")
	private String name;
	
	@Column(name="address")
	private String address;
	
	@Column(name="telephone")
	private String telephone;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	public String getTelephone() {
		return telephone;
	}

	public void setTelephone(String telephone) {
		this.telephone = telephone;
	}
}


?

NoCacheFilter.java

package com.stswg.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

public class NoCacheFilter implements Filter {
	
	public void doFilter(ServletRequest request,ServletResponse response,FilterChain chain) throws IOException,ServletException {
		try {
			HttpServletResponse res = (HttpServletResponse) response;
			res.addHeader("Cache-Control","no-store");
			res.addHeader("Pragma","no-store");
			chain.doFilter(request,response);
		} catch(Exception e) {
		}
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
	}

	@Override
	public void destroy() {
	}
}


?

CustomerServiceImpl.java

package com.stswg.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.flex.remoting.RemotingDestination;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.stswg.dao.CustomerDao;
import com.stswg.entity.Customer;
import com.stswg.service.CustomerService;

@RemotingDestination
public class CustomerServiceImpl implements CustomerService {

	@Autowired
	private CustomerDao customerDao;

	@Transactional(propagation=Propagation.REQUIRED)
	public int insertCustomer() {
		
		return customerDao.insertCustomer();
	}

	@Transactional(readOnly=true)
	public int selectCustomerCount() {
		
		return customerDao.selectCustomerCount();
	}
	
	@Transactional(readOnly=true)
	public List<Customer> selectCustomer(String name) {
		
		return customerDao.selectCustomer(name);
	}

	@Transactional(propagation=Propagation.REQUIRED)
	public int deleteCustomer() {
		
		return customerDao.deleteCustomer();
	}
}


?

CustomerService.java

package com.stswg.service;

import java.util.List;

import com.stswg.entity.Customer;

public interface CustomerService {

	public int deleteCustomer();
	
	public int insertCustomer();
	
	public int selectCustomerCount();
	
	public List<Customer> selectCustomer(String name);
}


?

jdbc.properties

#DataSource(C3P0)
jdbc.driverClassName=org.hsqldb.jdbcDriver
jdbc.url=jdbc:hsqldb:mem:.
jdbc.username=sa
jdbc.password=
jdbc.initialPoolSize=10
jdbc.minPoolSize=5
jdbc.maxPoolSize=30
jdbc.acquireIncrement=5
jdbc.maxIdleTime=10
jdbc.maxStatements=0

#Hibernate
hibernate.dialect=org.hibernate.dialect.HSQLDialect
hibernate.show_sql=false
hibernate.jdbc.batch_size=20
hibernate.generate_statistics=true
hibernate.cache.provider_class=org.hibernate.cache.EhCacheProvider
hibernate.cache.use_query_cache=true
hibernate.cache.use_second_level_cache=true
hibernate.cache.use_structured_entries=true
hibernate.hbm2ddl.auto=create-drop


log4j.properties

#Log4j
#Configuring loggers
log4j.rootLogger=error,console,file

#Configuring Appenders
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=C://logs.log

#Configuring layouts
log4j.appender.console.layout=org.apache.log4j.SimpleLayout
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} [%t] [%c] [%p] - %m%n


remoting-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<service id="remoting-service" class="flex.messaging.services.RemotingService">

	<adapters>
		<adapter-definition id="java-object" class="flex.messaging.services.remoting.adapters.JavaAdapter" default="true"/>
	</adapters>

	<default-channels>
		<channel ref="my-amf"/>
		<channel ref="my-secure-amf"/>
	</default-channels>
	
</service>


services-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<services-config>

    <services>
        <service-include file-path="remoting-config.xml" />
    </services>

    <channels>
		<channel-definition id="my-amf" class="mx.messaging.channels.AMFChannel" >
            <endpoint url="http://{server.name}:{server.port}/{context.root}/spring/messagebroker/amf" class="flex.messaging.endpoints.AMFEndpoint"/>	
		</channel-definition>
		<channel-definition id="my-secure-amf" class="mx.messaging.channels.SecureAMFChannel">
            <endpoint url="https://{server.name}:{server.port}/{context.root}/spring/messagebroker/amfsecure" class="flex.messaging.endpoints.SecureAMFEndpoint"/>
            <properties>
				<add-no-cache-headers>false</add-no-cache-headers>
			</properties>
        </channel-definition>
    </channels>

    <logging>
        <target class="flex.messaging.log.ConsoleTarget" level="Error">
            <properties>
                <prefix>[BlazeDS] </prefix>
                <includeDate>false</includeDate>
                <includeTime>false</includeTime>
                <includeLevel>false</includeLevel>
                <includeCategory>false</includeCategory>
            </properties>
            <filters>
                <pattern>Endpoint.*</pattern>
                <pattern>Service.*</pattern>
                <pattern>Configuration</pattern>
            </filters>
        </target>
    </logging>

    <system>
        <redeploy>
            <enabled>false</enabled>
        </redeploy>
    </system>

</services-config>


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:aop="http://www.springframework.org/schema/aop"
		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:flex="http://www.springframework.org/schema/flex"
		xsi:schemaLocation="
			http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
			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/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
			http://www.springframework.org/schema/flex http://www.springframework.org/schema/flex/spring-flex-1.0.xsd">

	<context:property-placeholder location="classpath:jdbc.properties" />
  	
  	<context:annotation-config/>
  	
  	<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close" 
  		p:driverClass="${jdbc.driverClassName}" 
		p:jdbcUrl="${jdbc.url}" 
		p:user="${jdbc.username}"
		p:password="${jdbc.password}"
		p:initialPoolSize="${jdbc.initialPoolSize}" 
		p:minPoolSize="${jdbc.minPoolSize}" 
		p:maxPoolSize="${jdbc.maxPoolSize}"
		p:acquireIncrement="${jdbc.acquireIncrement}" 
		p:maxIdleTime="${jdbc.maxIdleTime}"
		p:maxStatements="${jdbc.maxStatements}" />
		
	<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"
			p:dataSource-ref="dataSource">
		<property name="annotatedClasses">
			<list>
				<value>com.stswg.entity.Customer</value> 
			</list>
		</property>
		<property name="hibernateProperties">
			<props>
				<prop key="hibernate.dialect">
					${hibernate.dialect}
				</prop>
				<prop key="hibernate.show_sql">
					${hibernate.show_sql}
				</prop>
				<prop key="hibernate.jdbc.batch_size">
					${hibernate.jdbc.batch_size}
				</prop>
				<prop key="hibernate.generate_statistics">
					${hibernate.generate_statistics}
				</prop>
				<prop key="hibernate.cache.provider_class">
					${hibernate.cache.provider_class}
				</prop>
				<prop key="hibernate.cache.use_query_cache">
					${hibernate.cache.use_query_cache}
				</prop>
				<prop key="hibernate.cache.use_second_level_cache">
					${hibernate.cache.use_second_level_cache}
				</prop>
				<prop key="hibernate.cache.use_structured_entries">
					${hibernate.cache.use_structured_entries}
				</prop>
				<prop key="hibernate.hbm2ddl.auto">
					${hibernate.hbm2ddl.auto}
				</prop>
			</props>
		</property>
		<property name="eventListeners">
			<map>
				<entry key="merge">
					<bean class="org.springframework.orm.hibernate3.support.IdTransferringMergeEventListener"/>
				</entry>
			</map>
		</property>
	</bean>

	<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"
			p:sessionFactory-ref="sessionFactory"/>

	<tx:annotation-driven transaction-manager="transactionManager"/>
	
	<bean id="customerDao" class="com.stswg.dao.impl.CustomerDaoImpl" />

	<bean id="customerService" class="com.stswg.service.impl.CustomerServiceImpl" />

	<flex:message-broker services-config-path="/WEB-INF/flex/services-config.xml" />  	
<!--
	<flex:remoting-destination ref="customerService" />
-->

</beans>


web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

	<display-name>Spring-Flex-BlazeDS DEMO</display-name>

	<filter>
        <filter-name>noCacheFilter</filter-name>
        <filter-class>
            com.stswg.filter.NoCacheFilter
        </filter-class>
    </filter>
    
    <filter-mapping>
        <filter-name>noCacheFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

	<listener>
        <listener-class>flex.messaging.HttpFlexSession</listener-class>
    </listener>

	<servlet> 
        <servlet-name>Spring MVC Dispatcher Servlet</servlet-name> 
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 
        <init-param> 
            <param-name>contextConfigLocation</param-name> 
            <param-value>
                /WEB-INF/applicationContext.xml
            </param-value> 
        </init-param> 
        <load-on-startup>1</load-on-startup> 
    </servlet> 

    <servlet-mapping> 
        <servlet-name>Spring MVC Dispatcher Servlet</servlet-name> 
        <url-pattern>/spring/*</url-pattern> 
    </servlet-mapping>
    
    <welcome-file-list>
    	<welcome-file>FlexDemo.html</welcome-file>
    </welcome-file-list>

</web-app>


接下来是创建Flex端工程,如下图所示:

代码如下:

style.css

/* CSS file */
Application
{
	fontSize: 14;
}


FlexDemo.mxml

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
	verticalAlign="top"
	layout="vertical"
	initialize="prerender()"
	paddingTop="5" 
	paddingBottom="5"
	paddingRight="5"
	paddingLeft="5"
	>
	<mx:Style source="assets/css/style.css" />

	<mx:AMFChannel id="myamf" uri="/demo/spring/messagebroker/amf"/>     
 	<mx:ChannelSet id="channelSet" channels="{[myamf]}"/>     

	<mx:RemoteObject id="customerService" destination="customerService" channelSet="{channelSet}">
		<mx:method name="selectCustomerCount" result="resultSelectCustomerCount(event);" fault="faultError(event);" />
		<mx:method name="insertCustomer" result="resultInsertCustomer(event);" fault="faultError(event);" />
		<mx:method name="selectCustomer" result="resultSelectCustomer(event);" fault="faultError(event);" />
		<mx:method name="deleteCustomer" result="resultDeleteCustomer(event);" fault="faultError(event);" />
	</mx:RemoteObject>

	<mx:Script>
		<!--[CDATA[
			import mx.collections.ArrayCollection;
			import mx.rpc.events.ResultEvent;
			import mx.rpc.events.FaultEvent;
			import mx.controls.Alert;
			
			private function prerender() : void {
				
				customerService.selectCustomerCount();
			}
			
			public function searchCustomer() : void {
			
				var name : String = txtName.text;
				customerService.selectCustomer(name);
			}
			
			public function resultSelectCustomerCount(event:ResultEvent) : void {
	
				var count : int = event.result as int;
				if(count == 0) {
					customerService.insertCustomer();
				}
				customerService.selectCustomer("");
			}
			
			public function resultSelectCustomer(event:ResultEvent) : void {
				
				var dataset : ArrayCollection = event.result as ArrayCollection;
				dataGrid.dataProvider = dataset;
			}
			
			public function insertCustomer() : void {
				
				customerService.insertCustomer();
			}
			
			public function resultInsertCustomer(event:ResultEvent) : void {
				
				customerService.selectCustomer("");
			}
			
			public function deleteCustomer() : void {
				
				customerService.deleteCustomer();
			}
			
			public function resultDeleteCustomer(event:ResultEvent) : void {
				
				customerService.selectCustomer("");
			}
			
			private function faultError(event:FaultEvent) : void {
		
				Alert.show("错误信息:" + event.fault.toString());
			}
		]]-->
	</mx:Script>

	<mx:Panel width="100%" height="100%" horizontalAlign="center">
		<mx:Label text="智能运营监控管理平台Flex版演示程序" />
		<mx:VBox verticalGap="5" paddingTop="10" paddingLeft="10" paddingRight="10" paddingBottom="10" borderStyle="solid" borderThickness="1" cornerRadius="6">
			<mx:HBox width="600">
				<mx:Label text="客户名称:" />
				<mx:TextInput id="txtName" width="180"/>
				<mx:Button label="查询" click="searchCustomer()" />
				<mx:Button label="随机插入1条记录" click="insertCustomer()" />
				<mx:Button label="清空数据" click="deleteCustomer()" />
			</mx:HBox>
			<mx:HBox width="600" horizontalScrollPolicy="off">
				<mx:AdvancedDataGrid headerHeight="25" variableRowHeight="true" width="100%" height="400" id="dataGrid" doubleClickEnabled="true" horizontalScrollPolicy="auto" headerWordWrap="true" wordWrap="true" sortExpertMode="true">
					<mx:columns>
						<mx:AdvancedDataGridColumn width="50" textAlign="center" headerText="ID" dataField="id"/>	
			  			<mx:AdvancedDataGridColumn width="120" textAlign="center" headerText="客户名称" dataField="name"/>
						<mx:AdvancedDataGridColumn width="260" textAlign="center" headerText="客户地址" dataField="address"/>
						<mx:AdvancedDataGridColumn width="120" textAlign="center" headerText="客户电话" dataField="telephone"/>
					</mx:columns>
				</mx:AdvancedDataGrid>
			</mx:HBox>
		</mx:VBox>
	</mx:Panel>
</mx:Application>


设置Flex工程参数如下:

1.Compile参数设置

2.Deploy位置:

启动Demo工程的Tomcat即可访问。

转自:http://www.voidcn.com/article/p-tdcsvlov-wq.html

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读