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

flex3+struts2+spring3+hibernate3+mysql5+tomcat6项目实例

发布时间:2020-12-15 04:06:37 所属栏目:百科 来源:网络整理
导读:开发环境:myeclipse6.5+flex3 数据库:mysql5 服务器:tomcat6 下载blazeds-turnkey-4.0.0.14931.zip:解压此文件,里面有blazeds.war 1. 建立flex ?project项目: Next: Next: Flex ? WAR ?file:找到刚刚解压的blazeds.war Next: 最后finish: 2. 部署

开发环境:myeclipse6.5+flex3

数据库:mysql5

服务器:tomcat6

下载blazeds-turnkey-4.0.0.14931.zip:解压此文件,里面有blazeds.war

1. 建立flex ?project项目:



Next:




Next:

Flex ? WAR ?file:找到刚刚解压的blazeds.war



Next:



最后finish:




2. 部署项目tomcat上,测试项目是否能正常启动

在WebRoot下面建立一个index.jsp页面,将项目部署到tomcat上,看项目能否正常访问index.jsp页面


3. 项目正常启动后,加入相应的jar包


4. 配置web.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee?
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<context-param>
<param-name>
contextConfigLocation</param-name>
<param-value>
classpath:applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<display-name>FlexPro</display-name>
<description>LiveCycle Data Services Application</description>
<context-param>
<param-name>flex.class.path</param-name>
<param-value>
/WEB-INF/flex/hotfixes,/WEB-INF/flex/jars
</param-value>

<!-- Http Flex Session attribute and binding listener support -->
<listener-class>flex.messaging.HttpFlexSession</listener-class>
<!-- MessageBroker Servlet -->
<servlet>
<servlet-name>MessageBrokerServlet</servlet-name>
<servlet-class>
flex.messaging.MessageBrokerServlet
</servlet-class>
<init-param>
<param-name>services.configuration.file</param-name>
<param-value>/WEB-INF/flex/services-config.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<url-pattern>/messagebroker/*</url-pattern>
</servlet-mapping>
<!-- 定义struts2的核心filter --> ?
? ? <filter> ?
? ? ? ? <filter-name>struts2</filter-name> ?
? ? ? ? <filter-class> ?
? ? ? ? ? ? org.apache.struts2.dispatcher.FilterDispatcher ? ? ? ? ? ? ?
? ? ? ? </filter-class> ?
? ? </filter> ?
? ? <!-- 让struts定义的核心filter拦截所有请求 --> ?
? ? <filter-mapping> ?
? ? ? ? <filter-name>struts2</filter-name> ?
? ? ? ? <url-pattern>/controller/*</url-pattern>?
? ? ? ? <!--?
<dispatcher>FORWARD</dispatcher>
<dispatcher>REQUEST</dispatcher>
-->?
? ? </filter-mapping> ?
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>


5. 配置数据库

建立数据库test,建立usr表:

usr ? ? CREATE TABLE `usr` ( ? ? ? ? ? ? ? ? ?
? ? ? ? ? `usrid` varchar(20) NOT NULL,? ? ??
? ? ? ? ? `pwd` varchar(20) NOT NULL,? ? ? ??
? ? ? ? ? KEY `usrid` (`usrid`) ? ? ? ? ? ? ??
? ? ? ? ) ENGINE=MyISAM DEFAULT CHARSET=utf8 ?



src下建立application.properties:

sql.type=mysql
#jdbc mysql
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&amp;characterEncoding=utf-8
jdbc.username=root
jdbc.password=root
#dbcp settings
dbcp.initialSize=5
dbcp.maxActive=20
dbcp.maxIdle=10
#hibernate settings
hibernate.dialect=org.hibernate.dialect.MySQLDialect
hibernate.show_sql=true
hibernate.format_sql=true
hibernate.hbm2ddl.auto=update
hibernate.cache.use_second_level_cache=true
hibernate.cache.provider_class=org.hibernate.cache.EhCacheProvider
hibernate.cache.use_query_cache=true


配置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:context="http://www.springframework.org/schema/context"
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/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">


<!-- 支持元注释 -->
<context:annotation-config />


<!-- 扫描包目录 -->
<context:component-scan base-package="com.samples"></context:component-scan>


<bean
class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer">
<property name="locations" value="classpath*:/application.properties" />
</bean>


<bean class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" id="dataSource">?
<!-- Connection Info -->
<property name="driverClassName" value="${jdbc.driver}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />


<!-- Connection Pooling Info -->
<property name="maxActive" value="${dbcp.maxActive}" />
<property name="maxIdle" value="${dbcp.maxIdle}" />
<property name="defaultAutoCommit" value="false" />
<!-- 连接Idle一个小时后超时 -->
<property name="timeBetweenEvictionRunsMillis" value="3600000" />
<property name="minEvictableIdleTimeMillis" value="3600000" />
</bean>


<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="packagesToScan">
<value>com.*.model</value>
</property>
<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">${hibernate.show_sql}</prop>
? ? ? ? ? ? ? ? <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
? ? ? ? ? ? ? ? <prop key="hibernate.cache.use_second_level_cache">${hibernate.cache.use_second_level_cache}</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>
</props>
</property>


</bean>

<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
? <property name="sessionFactory" ref="sessionFactory"/>
? </bean>
??
? <tx:annotation-driven transaction-manager="transactionManager"/>

<!--
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
? ? -->
</beans>

测试spring+hibernate是否成功


6. 再整合struts2


建model:

package com.samples.model;


import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;


import org.springframework.stereotype.Component;


@Component
@Entity(name="usr")


public class Usr {
private String usrid;
private String pwd;


@Id
public String getUsrid() {
return usrid;
}


public void setUsrid(String usrid) {
this.usrid = usrid;
}


@Column(name="pwd")
public String getPwd() {
return pwd;
}


public void setPwd(String pwd) {
this.pwd = pwd;
}
}


dao:

package com.samples.dao;




import java.util.List;


import javax.annotation.Resource;


import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import com.samples.model.Usr;


import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;




@Service("userDao")
@Transactional
public class UserDao {


private static final Logger logger = Logger.getLogger(UserDao.class);
@Resource
? ? private SessionFactory sessionFactory;


public Usr getUsr_hbm(String usrid) {
Session session = sessionFactory.getCurrentSession();
Usr usr= (Usr)session.get(Usr.class,usrid);
return usr;
}

public boolean isUsrValid(String usrid,String password) {
Usr user = this.getUsr_hbm(usrid);
if (user == null) {
return false;
}
if (!user.getPwd().equals(password)) {
return false;
}
return true;
}

public List queryUserList()
{
Session session = sessionFactory.getCurrentSession();
Query query = ?session.createQuery("from usr");
List list=query.list();
return list;
}

public void updateUser(String usrid,String pwd)
{
Session session = sessionFactory.getCurrentSession();
Usr usr=(Usr)session.get(Usr.class,usrid);
usr.setPwd(pwd);
try {
//session.beginTransaction();//开启事务
session.saveOrUpdate(usr);
//session.getTransaction().commit();// 提交事务
} catch (Exception e) {
//session.getTransaction().rollback();// 回滚事务
}
finally{
//session.close();
}
}
}


建service:


package com.samples.service;


import javax.annotation.Resource;


import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import com.samples.dao.UserDao;
import com.samples.model.Usr;


@Service
@Transactional
public class UserService {

@Resource
private UserDao userDao;
private static final Logger logger = Logger.getLogger(UserService.class);


public Usr getModel()
{
//userDao.getList();
return userDao.getUsr_hbm("1");
}


}


建action:

package com.samples.action;


import javax.annotation.Resource;


import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;


import com.opensymphony.xwork2.ActionSupport;
import com.samples.model.Usr;
import com.samples.service.UserService;;


@Controller
@Scope("prototype")
public class UserAction extends ActionSupport {


/**
*?
*/
private static final long serialVersionUID = 8542035684950417689L;
private Usr usr;

@Resource
private UserService userService;?


@Override
public String execute() throws Exception {
usr=userService.getModel();
return SUCCESS;
}




public void setUsr(Usr usr)
{
this.usr=usr;
}



public Usr getUsr()
{
return usr;
}


}


建立jsp页面:

WEB-INF下面家里jsp文件夹,在jsp文件夹里建user.jsp

<%@ page language="java" ?contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
?<%@ taglib prefix="s" uri="/struts-tags"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
? <head>
? ? <base href="<%=basePath%>">
? ??
? ? <title>My JSP 'user.jsp' starting page</title>
? ??
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0"> ? ?
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->


? </head>
??
? <body>
? ? 基本信息: <br>
? ? ID号:<s:property value="usr.usrid"/>
? ?
? </body>
</html>



配置struts.xml

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


<!DOCTYPE struts PUBLIC
? ? "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN"
? ? "http://struts.apache.org/dtds/struts-2.1.dtd">


<struts>
<!-- action交给spring管理?
? ? <constant name="struts.objectFactory" value="spring"/>
? ? -->
? ??
? ? <package name="zhenghe" namespace="/controller" extends="struts-default" >
? ? ? ?<action name="usertest" class="userAction">
? ? ? ? <result>/WEB-INF/jsp/user.jsp</result>
? ? ? ?</action>
? ? </package>
? ??
? ? ?
</struts>

启动项目,能正常访问




7. 整合flex3

建立SpringFactory.java

package com.samples.factories;


import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import flex.messaging.FactoryInstance;
import flex.messaging.FlexFactory;
import flex.messaging.config.ConfigMap;
import flex.messaging.services.ServiceException;


public class SpringFactory implements FlexFactory {
private static final String SOURCE = "source";


/**
* This method can be used to initialize the factory itself. It is called
* with configuration parameters from the factory tag which defines the id
* of the factory.
*/
public void initialize(String id,ConfigMap configMap) {
}


/**
* This method is called when we initialize the definition of an instance
* which will be looked up by this factory. It should validate that the
* properties supplied are valid to define an instance. Any valid properties
* used for this configuration must be accessed to avoid warnings about
* unused configuration elements. If your factory is only used for
* application scoped components,this method can simply return a factory
* instance which delegates the creation of the component to the
* FactoryInstance's lookup method.
*/
public FactoryInstance createFactoryInstance(String id,ConfigMap properties) {
SpringFactoryInstance instance = new SpringFactoryInstance(this,id,
properties);
instance.setSource(properties.getPropertyAsString(SOURCE,instance
.getId()));
System.out.println("SpringSpringSpring" + instance.toString());
return instance;
} // end method createFactoryInstance()


/**
* Returns the instance specified by the source and properties arguments.
* For the factory,this may mean constructing a new instance,optionally
* registering it in some other name space such as the session or JNDI,and
* then returning it or it may mean creating a new instance and returning
* it. This method is called for each request to operate on the given item
* by the system so it should be relatively efficient.
* <p>
* If your factory does not support the scope property,it report an error
* if scope is supplied in the properties for this instance.
*/
public Object lookup(FactoryInstance inst) {
SpringFactoryInstance factoryInstance = (SpringFactoryInstance) inst;
return factoryInstance.lookup();
}


static class SpringFactoryInstance extends FactoryInstance {
SpringFactoryInstance(SpringFactory factory,String id,
ConfigMap properties) {
super(factory,properties);
}


public String toString() {
return "SpringFactory instance for id=" + getId() + " source="
+ getSource() + " scope=" + getScope();
}


public Object lookup() {
ApplicationContext appContext = WebApplicationContextUtils
.getWebApplicationContext(flex.messaging.FlexContext
.getServletConfig().getServletContext());
String beanName = getSource();
try {
return appContext.getBean(beanName);
} catch (NoSuchBeanDefinitionException nexc) {
ServiceException e = new ServiceException();
String msg = "Spring service named '" + beanName
+ "' does not exist.";
e.setMessage(msg);
e.setRootCause(nexc);
e.setDetails(msg);
e.setCode("Server.Processing");
throw e;
} catch (BeansException bexc) {
ServiceException e = new ServiceException();
String msg = "Unable to create Spring service named '"
+ beanName + "' ";
e.setMessage(msg);
e.setRootCause(bexc);
e.setDetails(msg);
e.setCode("Server.Processing");
throw e;
}
}
}
}


配置WEB-INF下面的flex文件夹里面的services-config.xml,在<services-config>里面加入

<factories>

? <factory id="spring" ?class="com.samples.factories.SpringFactory" />
</factories>


配置remoting-config.xml文件,在<service>里面加入,此处Id用于flex.mxml中

<destination id="usrlogin">
<properties>
<factory>spring</factory>
<source>userDao</source>
<scope>application</scope>
</properties>
</destination>


8. 在flex-src下面建立mxml文件

在flex-src下面建立mycmpt文件夹,在mycmpt下面建立Login.mxml

<?xml version="1.0" encoding="utf-8"?>


<mx:Panel xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" width="275"
height="150">
<mx:Script>
<![CDATA[
import mx.rpc.events.ResultEvent;
import mx.controls.Alert;
private function handleLogin():void
{
lblTest.text="login in ...";
var usrname:String = userid.text;
var password:String = pwd.text;
//re_usrlogin.welcome(usrname);
//re_usrlogin.addEventListener(ResultEvent.RESULT,showWelcome);
re_usrlogin.isUsrValid(usrname,password);
re_usrlogin.addEventListener(ResultEvent.RESULT,showWelcome);
}
private function showWelcome(e:ResultEvent):void
{
//Alert.show(e.result.toString());
var isvalid:Boolean = e.result as Boolean;
var url:URLRequest;
if(isvalid)
{
url= new URLRequest("http://www.google.com");//成功跳转到google!
}
else
{
url = new URLRequest("http://www.baidu.com");
}
navigateToURL(url,"_self");
}
]]>
</mx:Script>
<mx:RemoteObject destination="usrlogin" id="re_usrlogin"></mx:RemoteObject>
<mx:Label x="10" y="12" text="Username:"/>
<mx:Label x="10" y="42" text="Password:"/>
<mx:TextInput x="74" y="10" id="userid"/>
<mx:TextInput x="74" y="40" id="pwd" displayAsPassword="true"/>
<mx:Button label="Login" x="178" y="70" click="handleLogin();"/>
<mx:Label x="74" y="70" text="" id="lblTest"/>
</mx:Panel>



在flex-src下面建立main.mxml

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" xmlns:mp="mycmpt.*">
<mx:Panel title="User Login" x="50" y="50" width="375" height="300">
<mp:Login x="80" y="80"/>
</mx:Panel>
</mx:Application>

此时访问main.mxml:


输入用户名,密码登录


9. 测试add,update,select

在flex-src下面建立user_list.mxml

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete="initApp()">
<mx:Script>
<![CDATA[
private function initApp():void
{
user.queryUserList();
}

private function update():void
{
var usrid:String=usridtx.text;
var pwd:String=pwdtx.text;
user.updateUser(usrid,pwd);
dg.selectedItem.pwd=pwd;
}

]]>
</mx:Script>




<mx:RemoteObject destination="usrlogin" id="user" />
<mx:Form width="290" height="115" y="10" x="359">
<mx:FormItem label="用户ID:">
<mx:TextInput text="{dg.selectedItem.usrid}" width="179" id="usridtx" />
</mx:FormItem>
<mx:FormItem label="密码:">
<mx:TextInput text="{dg.selectedItem.pwd}" width="180" id="pwdtx"/>
</mx:FormItem>
</mx:Form>
<mx:DataGrid id="dg" dataProvider="{user.queryUserList.lastResult}" x="92" y="10" width="259" height="200">
<mx:columns>
<mx:DataGridColumn headerText="用户ID" dataField="usrid"/>
<mx:DataGridColumn headerText="用户密码" dataField="pwd"/>
</mx:columns>
</mx:DataGrid>
<mx:Button x="359" y="147" label="更新" click="update()"/>
</mx:Application>


访问:



至此,项目已完整建立



(编辑:李大同)

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

    推荐文章
      热点阅读