admin 管理员组文章数量: 887021
2024年1月12日发(作者:属于smart原则的是)
页码,1/29SpringMVC+BlzeDS+Flex框架实践:HelloWorld篇收收
一、环境配置:
MyEclipse7.0
Felx Builder3.0
JDK1.6
Flex sdk3.2
Tomcat6.0
二、创建JAVA Web工程
在MyEclipse中创建Web Project:TestProject
将相关JAR包拷贝到WEB-INF/lib下,并引入到项目的Build Path中
三、创建FLEX工程
在Flex Builder中创建Flex Project:TestProject
四、配置
配置JAVA Web工程中WebRoot/WEB-INF/
view plaincopy to clipboardprint?
1.
2. ="/xml/ns/j2ee" :xsi="/2001/XMLSchema-instance" :schemaLocation="/xml/ns/j2ee :///xml/ns/j2ee/web-app_2_"> 7. 8. 9. 10. 11. 12. 13. 14. ath:, classpath: 16. 17. 18. 19. 20. tLoaderListener 22. 23. 24. 25. ssionEventPublisher 27. 28. 29. 30. 31. 32. 33. 34. 35. 36. 37. 38. 39. 40. 41. 42. 43. 五、创建、 页码,2/29 在 里配置了初始化配置文件 ( 、 ) ,因此需要在 src 目录下创建相应的 xml 文件 ( 文件名需要与 中设置的配置文件名相同,否则加载时将会报错 ) 。 六、配置 + expand sourceview plaincopy to clipboardprint? 1. 2. xmlns="/schema/beans" 3. xmlns:xsi="/2001/XMLSchema-instance" 4. xmlns:flex="/schema/flex" 5. xmlns:aop="/schema/aop" 6. xsi:schemaLocation="/schema/beans 7. /schema/beans/ 8. /schema/aop 9. /schema/aop/ 10. /schema/flex 11. /schema/flex/"> 12. 13. 14. 七、Spring MVC配置 使用Spring MVC框架,将使用到两个配置文件、 [servlet-name]- WEB-INF/[servlet-name]-, 它被用于配置Web层、视图解析器、控制器、校验器以及其他所有MVC框架中必需的 Bean。[servlet-name]指的是在部署描述符中定义的Spring dispatcher servlet的名称。 根据在中定义的名称,我们的配置文件应该为。在 WEB-INF下创建。 配置 1. 2. :xsi="/2001/XMLSchema-instance" :schemaLocation=" :///schema/beans :///schema/beans/ :///schema/flex :///schema/flex/"> 9. 八、Spring+BlazeDS配置 BlazeDS是一种服务端使用java进行web通信的技术,其可以使开发人员方便地连接到后端分布式数据,推送数据到Flex或AIR应用,为RIA(rich Internet application)提供更好的体验。 Spring集成BlazeDS就是把spring的bean暴露成BlazeDS服务。在Spring BlazeDS Integration之前,BlazeDS要访问spring的bean,需要自己写代码。通过Spring BlazeDS Integration,当Flash来访问服务端时,spring会把请求转发给Flex message broker。同时,我们把spring中的一些bean暴露成Flex remoting service,那么Flash就能调用到spring中暴露成Flex remoting service的bean。 主要的BlazeDS组件是MessageBroker. Flex端传入的http信息将会通过Spring的DispatcherServlet来触发Spring-managed MessageBroker. 也就是说spring用DispatcherServlet来管理BlazeDS的MessageBroker。 配置 1. ="/schema/beans" xmlns:xsi="/2001/XMLSchema-instance" :flex="/schema/flex" :aop="/schema/aop" :schemaLocation="/schema/beans :///schema/beans/ :///schema/aop /schema/aop/ :///schema/flex :///schema/flex/"> 10. 11. 九、BlazeDS配置 页码,3/291)下载BlazeDS 下载地址:/wiki/display/blazeds/Release+Builds 2)解压,解压其中的,将其中flex目录下的四个xml文件(messaging- 、、、)拷贝到 l JAVA工程WebRoot/WEB-INF/flex下(flex目录需要手动创建) l FLEX工程src/config下(config目录需要手动创建) 3)修改FLEX 工程src/config/ 1. 2. 3. 4. 5. 6. 7. 8. 9. ="Tomcat"/> 11. 12. 13. ="my-amf" ="nnel"> 16. ="/TestWeb/messagebroker/amf" ="point"/> 19. 20. ="my-secure-amf" ="AMFChannel"> 23. 24. class="AMFEndpoint"/> 25. 26. 27. 28. 29. ="my-polling-amf" ="nnel"> 32. =" /TestWeb/messagebroker/amfpolling" ="point"/> 35. 36. 37. 38. 39. 40. 41. 42. 43. 44. 45. 46. 47. 48. 49. 50. 51. 52. 页码,4/2953. 54. 55. 56. 57. 58. 59. 60. 十、框架应用 1)创建 搭好框架后,需要在JAVA工程中创建JAVA类,并通过配置文件发布给FLEX应用,以此验证JAVA与FLEX的通信是否成功 在JAVA工程src下创建package:e,创建 package e; public class UserService { public String getMessage(){ n("Excute UserService :"+"hello world!"); return "Hello World"; } } 2)发布UserService 所有的JAVA类,如果想要发布给FLEX应用,就需要在Application-Flex中添加 3)FLEX引用UserService 对于所有JAVA工程发布的远程服务,如果需要调用,则必须在FLEX工程的配置文件中进行配置,在 中添加如下配置(这里的source必须和JAVA工程中发布远程服务时提供的bean id一致,否则调用将会失败): 4)创建FLEX应用程序 在FLEX工程src下创建modules/common目录,创建,在其中调用UserService + expand sourceview plaincopy to clipboardprint? 1. 2. 3. layout="vertical" 4. horizontalAlign="center" 5. creationComplete="initApp()" 6. fontSize="15"> 7. 8. 20. 21. 22. 23. 5)修改FLEX主应用 页码,5/29 在这里需要特别提一下,由于FLEX工程创建时会默认提供一个主应用程序,当我们希望主应用程序由我们自己决定时(在本例中主应用程序为moduls/common/),需要修改FLEX工程目录下的.actionScriptProperties文件。修改如下配置 6)修改JAVA主页 修改JAVA工程中的 <%direct(path+"/modules/common/");%> 十一、编译运行 1)编译FLEX工程 选择Project—>Clean—>TestProject 2)拷贝编译目录bin-debug/modules到JAVA工程的WebRoot下 3)在MyEclipse中启动Tomcat服务器 4)运行程序 服务器正常启动后,在浏览器中输入如下地址(其中9090为服务器端口号): localhost:9090/TestProject/modules/common/ 运行结果如下: 本例到此就实践结束,似乎有点长,下一次将在此基础上添加数据库配置。。。。。。 Spring MVC+BlazeDS+Flex框架实践:Database篇 收藏 在/meteorlWJ/archive/2009/09/12/ 中实践了此框架的基础搭建,本次的实践将在此基础上引入hibernate配置,并创建FLEX应用实现数据库操作。 一、环境配置 MyEclipse 7.0 Flex Builder 3.0 Tomcat 6.0 JDK1.6 Flex sdk 3.2 Oracle 10g :XE 二、Hibernate+Proxool配置 Hibernate管理JAVA类到数据库表的映射,并提供数据查询和获取的方法。Hibernate对JDBC进行了轻量级的对象封装,完成了数据持久化的重任。 这是一个Java SQL Driver驱动程序,提供了对你选择的其它类型的驱动程序的连接池封装。Proxool提供一个健壮、易用的连接池,最为关键的是这个连接池提供监控的功能,方便易用,便于发现连接泄漏的情况。 1)连接池配置: 在JAVA工程src下创建,添加如下配置: 其中参数详解如下: alias :数据源别名 页码,6/29 driver-url :连接字符串 driver-class :驱动类 statistics :连接池使用状态统计 driver-properties :数据库连接用户名/密码 house-keeping-sleep-time :house keeper保留线程处于睡眠状态的最长时间, house-keeper的职责就是检查各个连接的状态,并判断是否需要销毁或创建 maximum-new-connections :没有空闲连接时可以分配在队列中等待的最大请 求数 maximum-connection-count :最大连接数 minimum-connection-count :最小连接数 trace :每个被执行的SQL语句是执行期是否用被LOG记录 verbose :详细信息设置 + expand sourceview plaincopy to clipboardprint? 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 2)hibernate配置 在JAVA工程src目录下创建,添下如下配置 + expand sourceview plaincopy to clipboardprint? 1. 2. 3. :security="/schema/security" :xsi="/2001/XMLSchema-instance" xmlns:tx="/schema/tx" :schemaLocation="/schema/beans /schema/beans/ :///schema/security /schema/security/ :///schema/tx /schema/tx/"> 9. 10. 11. class="tionSessionFactoryBean"> 12. 13. 14. 15. 16. 9Dialect 18. 19. 20. 22. 24. 25. 26. 27. 28. 页码,7/2929. eProvider 31. 32. 33. 35. 37. 39. 40. 41. 42. 43. 44. ction-manager="transactionManager" /> 46. 47. 48. class="ateTrans Manager"> 50. 51. 3)配置 在上一篇中提到中配置了初始化时加载的文件,在添加了hibernate配置后,同样需要将其添加到的初始化文件列表中, 修改中的相关配置: + expand sourceview plaincopy to clipboardprint? 1. 2. 3. ath:, ath:, ath: 7. 8. 三、数据库对象映射配置 项目中使用 Hibernate 管理 JAVA 类到数据库表的映射,它可以实现 ORM(Object Relational Mapping) ,将关系数据库中表的数据映射成对象。 1)创建数据库对象 通过以下脚本创建数据库对象 + expand sourceview plaincopy to clipboardprint? 1.-- Create table table _USERS 3.( 4. USER_ID NUMBER not null, 5. USER_NAME VARCHAR2(100) not null, 6. USER_PASSWORD VARCHAR2(240), 7. USER_DESCRIPTION VARCHAR2(240), 8. EMAIL_ADDRESS VARCHAR2(240), 9. START_DATE_ACTIVE DATE, 10. END_DATE_ACTIVE DATE, 11. OBJECT_VERSION_NUMBER NUMBER, 12. CREATED_BY NUMBER not null, 13. CREATION_DATE DATE not null, 14. LAST_UPDATED_BY NUMBER not null, 15. LAST_UPDATE_DATE DATE not null 16.); unique index FWK_USERS_PK on fwk_users(USER_ID); sequence fwk_users_s start with 1000; 页码,8/292)创建Who字段映射类 如果你接触过ORACLE数据库,相信对WHO字段应该很熟悉了吧,这里就不多做解释了。本例中将WHO字段的映射独立出来,这样对所有的数据库映射类都能同样使用,而不用重复相同的代码。 在src下创建package ,创建 + expand sourceview plaincopy to clipboardprint? e ; izable; ; ; Superclass; 6.@MappedSuperclass class BaseWhoEntity implements Serializable{ 8. // DataType:NUMBER 9. @Column(name = "OBJECT_VERSION_NUMBER", nullable = true) 10. private Long objectVersionNumber; 11. // DataType:NUMBER 12. @Column(name = "CREATED_BY", nullable = false) 13. private Long createdBy; 14. // DataType:DATE 15. @Column(name = "CREATION_DATE", nullable = false) 16. private Date creationDate; 17. // DataType:NUMBER 18. @Column(name = "LAST_UPDATED_BY", nullable = false) 19. private Long lastUpdatedBy; 20. // DataType:DATE 21. @Column(name = "LAST_UPDATE_DATE", nullable = false) 22. private Date lastUpdateDate; 23. public Long getObjectVersionNumber() { 24. return objectVersionNumber; 25. } 26. public void setObjectVersionNumber(Long objectVersionNumber) { 27. VersionNumber = objectVersionNumber; 28. } 29. public Long getCreatedBy() { 30. return createdBy; 31. } 32. public void setCreatedBy(Long createdBy) { 33. dBy = createdBy; 34. } 35. public Date getCreationDate() { 36. return creationDate; 37. } 38. public void setCreationDate(Date creationDate) { 39. onDate = creationDate; 40. } 41. public Long getLastUpdatedBy() { 42. return lastUpdatedBy; 43. } 44. public void setLastUpdatedBy(Long lastUpdatedBy) { 45. datedBy = lastUpdatedBy; 46. } 47. public Date getLastUpdateDate() { 48. return lastUpdateDate; 49. } 50. public void setLastUpdateDate(Date lastUpdateDate) { 51. dateDate = lastUpdateDate; 52. } 53.} 3)创建数据库实体类 在创建完数据库表FwkUsers后,我们需要创建与之对应的JAVA实体类,通过Hibernate的annotation实现对象映射 在JAVA工程src下创建package ,创建 + expand sourceview plaincopy to clipboardprint? e ; 页码,9/ ; ; ; tedValue; tionType; ; ceGenerator; ; oEntity; 11.@Entity 12.@Table(name = "FWK_USERS") class FrameworkUser extends BaseWhoEntity{ 14. // DataType:NUMBER 15. @Id 16. @GeneratedValue(strategy = CE, generator = "FWK_USERS_S") 17. @SequenceGenerator(name = "FWK_USERS_S", sequenceName = "FWK_USERS_S") 18. @Column(name = "USER_ID", nullable = false) 19. private Long userId; 20. // DataType:VARCHAR2 21. @Column(name = "USER_NAME", nullable = false, length = 100) 22. private String userName; 23. // DataType:VARCHAR2 24. @Column(name = "USER_PASSWORD", nullable = true, length = 240) 25. private String userPassword; 26. // DataType:VARCHAR2 27. @Column(name = "USER_DESCRIPTION", nullable = true, length = 240) 28. private String userDescription; 29. // DataType:VARCHAR2 30. @Column(name = "EMAIL_ADDRESS", nullable = true, length = 240) 31. private String emailAddress; 32. // DataType:DATE 33. @Column(name = "START_DATE_ACTIVE", nullable = true) 34. private Date startDateActive; 35. // DataType:DATE 36. @Column(name = "END_DATE_ACTIVE", nullable = true) 37. private Date endDateActive; 38. public Long getUserId() { 39. return userId; 40. } 41. public void setUserId(Long userId) { 42. = userId; 43. } 44. public String getUserName() { 45. return userName; 46. } 47. public void setUserName(String userName) { 48. me = userName; 49. } 50. public String getUserPassword() { 51. return userPassword; 52. } 53. public void setUserPassword(String userPassword) { 54. ssword = userPassword; 55. } 56. public String getUserDescription() { 57. return userDescription; 58. } 59. public void setUserDescription(String userDescription) { 60. scription = userDescription; 61. } 62. public String getEmailAddress() { 63. return emailAddress; 64. } 65. public void setEmailAddress(String emailAddress) { 66. ddress = emailAddress; 67. } 页码,10/2968. public Date getStartDateActive() { 69. return startDateActive; 70. } 71. public void setStartDateActive(Date startDateActive) { 72. ateActive = startDateActive; 73. } 74. public Date getEndDateActive() { 75. return endDateActive; 76. } 77. public void setEndDateActive(Date endDateActive) { 78. eActive = endDateActive; 79. } 80.} 4)创建对象扫描类 项目中使用Hibernate映射数据库对象,在做CUDI(Create、Update、Delete、Insert)时希望能够通过对象名自动找到对应的DAO进行事务处理。 在JAVA工程src目录下创建package ,创建 + expand sourceview plaincopy to clipboardprint? e ; ist; ; ce; tchingResourcePatternResolver; cePatternResolver; gMetadataReaderFactory; taReader; taReaderFactory; tils; class ExtSpringPackageScan { 12. static ResourcePatternResolver resourcePatternResolver=new PathMatchingResourcePatternResolver(); static List 14. List 15. if(packagesToScan != null) 16. try 17. { 18. int len = ; 19. for(int i = 0; i < len; i++) 20. { 21. String pkg =packagesToScan[i]; 22. String pattern = (new StringBuilder()).append("classpath*:").append(tClassNameToResourcePath(pkg)).append("**/*.class").toString(); 23. Resource resources[] = ources(pattern); 24. MetadataReaderFactory readerFactory = new CachingMetadataReaderFactory(resourcePatternResolver); 25. Resource arr$[] = resources; 26. int len$ = arr$.length; 27. for(int i$ = 0; i$ < len$; i$++) 28. { 29. Resource resource = arr$[i$]; 30. if(!able()) 31. continue; 32. MetadataReader reader = adataReader(resource); 33. String className = ssMetadata().getClassName(); 34. (className); 35. } 36. } 37. } 38. catch(Exception ex) 39. { 40. tackTrace(); 41. } 42. return classNames; 43.} 44.} 页码,11/29四、DAO设计 DAO层的设计采用的是泛型设计。泛型是Java SE 1.5的新特性,泛型的本质是参数化类型,也就是说所操作的数据类型被指定为一个参数。泛型的好处是在编译的时候检查类型安全,并且所有的强制转换都是自动和隐式的,提高代码的重用率。 1)DAO接口设计 在JAVA 工程src下创建package ate,创建 + expand sourceview plaincopy to clipboardprint? e ate; izable; tionTargetException; ; ; ateCallback; interface GenericDao 8. public PK save(T value) throws Exception; 9. public T get(PK id, Class 10. public T beforeSave(T value) throws Exception; 11.} 2)DAO接口实现 在JAVA工程ate下创建 view plaincopy to clipboardprint? e ate; izable; imal; eption; ; p; ; ; ; ils; ; ia; ateException; ; ry; n; e; tions; ed; ateCallback; ateDaoSupport; oEntity; class GenericDaoImpl 24. public T beforeSave(T value) throws Exception { 25. if (value instanceof BaseWhoEntity) { 26. BaseWhoEntity temp = (BaseWhoEntity) value; 27. Map map = new HashMap(); 28. ("createdBy", new Long(7)); 29. ("creationDate", new Date()); 30. ("lastUpdatedBy", new Long(7)); 31. ("lastUpdateDate", new Date()); 32. ("objectVersionNumber", new Long(1)); 33. try { 34. te(value, map); 35. } catch (Exception e) { 36. ("将Map转化为对像时出错", e); 37. throw e; 38. } 39. } 40. return value; 41. } 42. @Profiled(tag = "") 页码,12/2943. public PK save(T value) throws Exception { 44. try { 45. n("执行保存!"); 46. return (PK) ernateTemplate().save(beforeSave(value)); 47. } catch (Exception e) { 48. throw e; 49. } 50. } 51. @Profiled(tag = "") 52. @SuppressWarnings("unchecked") 53. public T get(PK id, Class 54. return (T) getHibernateTemplate().get(klass, id); 55. } 56.} 五、Service设计 通过设计Service层,实现与FLEX之间的数据传递。 1)在JAVA 工程src下创建package e,创建 + expand sourceview plaincopy to clipboardprint? e ate; izable; ist; p; ; ; ; tory; nFactory; lizingBean; ateCallback; ingPackageScan; class GenericService implements InitializingBean { 14. private static final Log logger = (); 15. private SessionFactory sessionFactory; 16. private String[] packagesToScan; 17. @SuppressWarnings("unchecked") 18. private Map 19. private List 20. public Map 21. return daoMap; 22. } 23. public void setDaoMap(Map 24.{ 25. = daoMap; 26. } 27. public String[] getPackagesToScan() { 28. return packagesToScan; 29. } 30. public void setPackagesToScan(String[] packagesToScan) 31.{ 32. esToScan = packagesToScan; 33. } 34. @SuppressWarnings("unchecked") 35. public void afterPropertiesSet() throws Exception { 36. (sses(packagesToScan)); 37. StringBuffer sb = new StringBuffer(); 38. for (String className : classList) 39. (className + ","); 40. ("初始化完成Pojo与表的映射:" + ng()); 41. ("初始化完成DaoMap:" + daoMap); 42. } 43. public SessionFactory getSessionFactory() { 44. return sessionFactory; 45. } 页码,13/2946. public void setSessionFactory(SessionFactory sessionFactory) { 47. nFactory = sessionFactory; 48. } 49. @SuppressWarnings("unchecked") 50. public 51. try { 52. GenericDao gd = getDao(ss().getName()); 53. if (gd != null) { 54. return (PK) (value); 55. } else { 56. ("保存错误,无法找到相应的DAO来处理,请确认配置信息是否正确!"); 57. return null; 58. } 59. } catch (Exception e) { 60. throw e; 61. } 62. } 63. public String getClass(String className) { 64. for (String classInList : classList) { 65. if (th(className) || (className)) 66. return classInList; 67. } 68. return null; 69. } 70. @SuppressWarnings("unchecked") 71. public GenericDao getDao(String fullClassName) { 72. GenericDao gd = null; 73. if ((fullClassName) == null) { 74. ("使用缺省的Dao"); 75. gd = ("default"); 76. } else { 77. gd = (fullClassName); 78. ("使用Dao:" + ss().getName()); 79. } 80. return gd; 81. } 82. @SuppressWarnings("unchecked") 83. public 84. try { 85. String fullClassName = getClass(className); 86. Class 87. GenericDao gd = getDao(fullClassName); 88. return (T) (id, klass); 89. } catch (ClassNotFoundException e) { 90. tackTrace(); 91. } catch (NullPointerException ne) { 92. ("传入类型:" + className + "不存在!"); 93. tackTrace(); 94. } 95. return null; 96. } 97.} 2)创建具体应用类 在JAVA工程e下创建 + expand sourceview plaincopy to clipboardprint? e e; ; ; ils; tUtils; tyUtilsBean; nverter; ation; ctional; 页码,14/ cService; class BaseService { 12. GenericService genericService; 13. private PropertyUtilsBean pb = new PropertyUtilsBean(); 14. static { 15. ster(); 16. DateConverter dateConverter = new DateConverter(null); 17. er(dateConverter, ); 18. } 19. public GenericService getGenericService() { 20. return genericService; 21. } 22. public void setGenericService(GenericService genericService) { 23. cService = genericService; 24. } 25. @Transactional(propagation = TS) 26. @SuppressWarnings("unchecked") 27. public Map save(Map map) throws Exception { 28. try { 29. if (("className") != null) { 30. Object value = ToObject(map); 31. (value); 32. return be(value); 33. } 34. } catch (Exception e) { 35. tackTrace(); 36. throw e; 37. } 38. return null; 39. } 40. public Object popMapToObject(Map proerties) throws Exception { 41. n("组装POJO参数:" + proerties); 42. if (("className") != null) { 43. String className = (String) ("className"); 44. Object value = e(ss(className)).newInstance(); 45. te(value, proerties); 46. n("组装后的class:" + be(value)); 47. return value; 48. } 49. return null; 50. } 51.} 3)完成DAO与Service层的设计后,需要修改hibernate配置 修改,添加如下配置: + expand sourceview plaincopy to clipboardprint? 1. 2. ="cService"> 4. 6. 7. 8. 9. 10. 11. 12. 13. 14. 16. 17. 18. 19. 页码,15/2920. 21. ="cDaoImpl"> 23. 25. 26. 六、远程服务应用 1)发布BaseService 修改,添加如下配置: + expand sourceview plaincopy to clipboardprint? 1. 2. 3. 4. 5. 2)FLEX引用BaseService 修改FLEX工程,添加如下配置: + expand sourceview plaincopy to clipboardprint? 1. 2. 3. 4. 5. 3)创建 在FLEX工程src/modules下创admin目录,创建,通过RemoteObject调用远程服务 + expand sourceview plaincopy to clipboardprint? 1. 2. 3. 4. 24. 25. 26. 27. idth="100"> 29. 30. 31. idth="100"> 页码,16/2933. yAsPassword="true"/> 35. 36. idth="100"> 38. 39. 40. 41. 42. ="saveRecord()" 44.x="761" y="277" cornerRadius="9"/> 45. 46. 47. 4)修改,添加如下内容: + expand sourceview plaincopy to clipboardprint? 1. ="50%" height="50%"/> 七、编译运行 1)编译FLEX工程 选择Project—>Clean—>TestProject 2)拷贝编译目录bin-debug/modules到JAVA工程WebRoot下 3)启动本地数据库 4)启动Tomcat服务器 5)服务器正常启动后,在浏览器中输入地址(其中9090为服务器端口) localhost:9090/TestProject/modules/common/ 运行结果如下: 首页: 保存数据,检查JAVA与FLEX通信是否正常: 页码,17/29 访问数据库,检查数据是否保存成功: 在Spring MVC+BlazeDS+Flex框架实践:Database篇的基础上,这次要加入的是Spring Security的配置与应用。至于Spring Security的原理及配置详解网上已经有很多可参考的文章,在这里就不再重复了。 一、Spring Security配置 1)添加 在JAVA工程src下创建 + expand sourceview plaincopy to clipboardprint? 1. 2. 3. xmlns="/schema/security" 4. xmlns:xsi="/2001/XMLSchema-instance" 5. xsi:schemaLocation="/schema/beans /schema/beans/ 6. /schema/security /schema/security/ 7. "> 8. 9. 10. default-target-url="/modules/common/" /> 页码,18/2911. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23. 24. 25. 26. 27. 28. 29. 30. 31. 32. 33. 34. 35. 36. 37. 38. 39. 40. 41. 42. 2)修改 在添加后,需要在中将其添加到初始化加载列表中 修改以下配置: + expand sourceview plaincopy to clipboardprint? 1. 2. 3. 4. classpath:,classpath:,classpath:,classpath: 5. 6. 二、Security类创建 在JAVA工程src下创建package ty 创建 + expand sourceview plaincopy to clipboardprint? e ty; ; p; ; ; ; tory; ationEvent; ationListener; ctAuthenticationEvent; ticationSuccessEvent; ctiveAuthenticationSuccessEvent; 页码,19/ henticationDetails; ssionApplicationEvent; ssionDestroyedEvent; cService; ntext; class SecurityLogListener implements ApplicationListener { 19. private static final Log logger = (); 20. GenericService genericService; 21. public GenericService getGenericService() { 22. return genericService; 23. } 24. public void setGenericService(GenericService genericService) { 25. cService = genericService; 26. } 27. public void onApplicationEvent(ApplicationEvent event) { 28. if (event instanceof AbstractAuthenticationEvent) { 29. try { 30. AbstractAuthenticationEvent authEvent = (AbstractAuthenticationEvent) event; 31. if (event instanceof AuthenticationSuccessEvent) { 32. Object obj = hentication().getPrincipal(); 33. if (obj instanceof FlexUserDetails) { 34. 35. n("Username: "+((FlexUserDetails) obj).getUsername()); 36. n("Login Date: "+new Date()); 37. n("Session Id: "+xSession().getId()); 38. } 39. } else if (event instanceof InteractiveAuthenticationSuccessEvent) 40. ("InteractiveAuthenticationSuccessEvent:" + hentication().getDetails()); 41. } catch (Exception e) { 42. // TODO Auto-generated catch block 43. tackTrace(); 44. } 45. } else if (event instanceof HttpSessionApplicationEvent) { 46. HttpSessionApplicationEvent sessionEvent = (HttpSessionApplicationEvent) event; 47. if (event instanceof HttpSessionDestroyedEvent) { 48. ("[destroy]"+sion().getId()); 49. Map 50. ("sessionId", sion().getId()); 51. n("Session Id: "+sion().getId()); 52. n("Session remove date: "+new Date()); 53. 54. }else 55. ("[create]"+sion().getId()); 56. } 57. } 58.} 创建 + expand sourceview plaincopy to clipboardprint? e ty; ; p; ; ; rvletRequest; rvletResponse; ; tory; tication; tyContextLogoutHandler; cService; class SecurityLogoutHandler extends SecurityContextLogoutHandler { 14. private static final Log logger = (); 15. GenericService genericService; 16. public SecurityLogoutHandler() { 页码,20/2917. super(); 18. } 19. public GenericService getGenericService() { 20. return genericService; 21. } 22. public void setGenericService(GenericService genericService) { 23. cService = genericService; 24. } 25. public void logout(HttpServletRequest httpservletrequest, HttpServletResponse httpservletresponse, 26. Authentication authentication) { 27. try { 28. Map 29. ("sessionId", sion().getId()); 30. 31. } catch (Exception e) { 32. // TODO Auto-generated catch block 33. tackTrace(); 34. } 35. (httpservletrequest, httpservletresponse, authentication); 36. } 37.} 创建 此类中的信息与数据库的结构有关 + expand sourceview plaincopy to clipboardprint? e ty; ; dAuthority; tails; orkUser; class FlexUserDetails implements UserDetails { 7. private FrameworkUser fu; 8. private GrantedAuthority[] authorities; 9. public FlexUserDetails(FrameworkUser user,GrantedAuthority[] roles){ 10. =user; 11. ities=roles; 12. 13. } 14. public GrantedAuthority[] getAuthorities() { 15. return authorities; 16. } 17. public String getPassword() { 18. return rPassword(); 19. } 20. public String getUsername() { 21. // TODO Auto-generated method stub 22. return rName(); 23. } 24. public boolean isAccountNonExpired() { 25. return true; 26. } 27. public boolean isAccountNonLocked() { 28. // TODO Auto-generated method stub 29. return true; 30. } 31. public boolean isCredentialsNonExpired() { 32. // TODO Auto-generated method stub 33. return true; 34. } 35. public boolean isEnabled() { 36. Date now=new Date(); 37. return rtDateActive().before(now)&&(DateActive()==null||DateActive().after(now)); 38. } 39. public FrameworkUser getFu() { 页码,21/2940. return fu; 41. } 42. public void setFu(FrameworkUser fu) { 43. = fu; 44. } 45. public void setAuthorities(GrantedAuthority[] authorities) { 46. ities = authorities; 47. } 48.} 创建 此类中具体执行了用户登录时的授权等操作,其中明确了当用户为"admin"时,为其授予ROLE_ADMIN、ROLE_USER、ROLE_ANONYMOUS权限;而其他用户则只有ROLE_USER、ROLE_ANONYMOUS权限。不同权限的访问范围在中进行控制。本例中只有ROLE_ADMIN权限的角色才能访问modules/admin下的页面。 + expand sourceview plaincopy to clipboardprint? e ty; ist; p; ; ; ; eSourceAccessor; cessException; dAuthority; dAuthorityImpl; SecurityMessageSource; tails; tailsService; meNotFoundException; orkUser; cService; class FlexUserDetailsService implements UserDetailsService { 18. private static final Logger logger = ger(); 19. private GenericService genericService; 20. private String userNameProperty; 21. protected MessageSourceAccessor messages; 22. private String authoritiesbyUsernameQuery; 23. public FlexUserDetailsService() { 24. messages = essor(); 25. } 26. public GenericService getGenericService() { 27. return genericService; 28. } 29. public void setGenericService(GenericService genericService) { 30. cService = genericService; 31. } 32. public String getUserNameProperty() { 33. return userNameProperty; 34. } 35. public void setUserNameProperty(String userNameProperty) { 36. meProperty = userNameProperty; 37. } 38. public String getAuthoritiesbyUsernameQuery() { 39. return authoritiesbyUsernameQuery; 40. } 41. public void setAuthoritiesbyUsernameQuery(String authoritiesbyUsernameQuery) { 42. itiesbyUsernameQuery = authoritiesbyUsernameQuery; 43. } 44. public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException, DataAccessException { 45. n("UserDetails: loadUserByUsername"); 46. List users = new ArrayList(); 47. try { 48. users = ersByUsername(name); 49. } catch (Exception e) { 50. // TODO Auto-generated catch block 页码,22/2951. tackTrace(); 52. } 53. if (() == 0) 54. throw new UsernameNotFoundException(sage("nd", new Object[] { name }, 55. "Username {0} not found"), name); 56. FrameworkUser user = (FrameworkUser) (0); 57. GrantedAuthority[] roles = loadUserAuthorities(name); 58. if (roles == null) 59. throw new UsernameNotFoundException(sage("ority", new Object[] { name }, 60. "User {0} has no GrantedAuthority"), name); 61. ("roles " + ); 62. ("login in success," + rName()); 63. return new FlexUserDetails(user, roles); 64. } 65. private List 66. n("List 67. Map 68. (meProperty, name); 69. return Property(e(), params); 70. } 71. private GrantedAuthority[] loadUserAuthorities(String name) { 72. Map params = new HashMap(); 73. ("userName", name); 74. 75. List 76. 77. if(("admin")){ 78. (new GrantedAuthorityImpl(name)); 79. (new GrantedAuthorityImpl("ROLE_ANONYMOUS")); 80. (new GrantedAuthorityImpl("ROLE_ADMIN")); 81. (new GrantedAuthorityImpl("ROLE_USER")); 82. n("授权: ROLE_ADMIN,ROLE_ANONYMOUS"); 83. }else{ 84. (new GrantedAuthorityImpl(name)); 85. (new GrantedAuthorityImpl("ROLE_ANONYMOUS")); 86. (new GrantedAuthorityImpl("ROLE_USER")); 87. n("授权: ROLE_USER,ROLE_ANONYMOUS"); 88. } 89. GrantedAuthority[] authoritiesarray = new GrantedAuthority[()]; 90. y(authoritiesarray); 91. return authoritiesarray; 92. } 93.} 创建 此类在用户登录时被调用 + expand sourceview plaincopy to clipboardprint? e ty; p; ; ; tication; ticationManager; dAuthority; tyContextHolder; mePasswordAuthenticationToken; tails; ntext; class AuthenticationHelper { 13. private static final Logger logger = ger(); 14. private AuthenticationManager authenticationManager; 15. public AuthenticationManager getAuthenticationManager() { 16. return authenticationManager; 页码,23/2917. } 18. public void setAuthenticationManager(AuthenticationManager authenticationManager) { 19. ticationManager = authenticationManager; 20. } 21. public void authenticatePrincipal(String username, String password) { 22. //try{ 23. ("user login system! username:" + username); 24. UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken( 25. username, password); 26. Authentication authentication = ticate(usernamePasswordAuthenticationToken); 27. text().setAuthentication(authentication); 28. GrantedAuthority[] authorities = text().getAuthentication().getAuthorities(); 29. int numAuthorities = ; 30. String[] grantedRoles = new String[numAuthorities]; 31. for (int counter = 0; counter < numAuthorities; counter++) { 32. grantedRoles[counter] = authorities[counter].getAuthority(); 33. } 34. String name = text().getAuthentication().getName(); 35. ("登录成功!"); 36. //}catch(Exception e){tackTrace();} 37. } 38. public Map getCurrentUser() { 39. if (text() == null 40. || text().getAuthentication() == null 41. || text().getAuthentication().getPrincipal() == null) { 42. Map temp = new HashMap(); 43. ("userName", "System"); 44. ("userId", 0); 45. return temp; 46. } 47. Map user = new HashMap(); 48. Object obj = text().getAuthentication().getPrincipal(); 49. if (obj instanceof UserDetails) { 50. ("userDescription", ((FlexUserDetails) obj).getFu().getUserDescription()); 51. ("userId", ((FlexUserDetails) obj).getFu().getUserId()); 52. ("userName", ((FlexUserDetails) obj).getUsername()); 53. } else { 54. ("userName", ng()); 55. ("userId", -100); 56. } 57. (user); 58. return user; 59. } 60. public Long getCurrentUserId() { 61. if (rentUser().get("userId") != null) 62. return f(rentUser().get("userId").toString()); 63. return new Long(-100); 64. } 65.} 三、配置AuthenticationHelper 1)发布AuthenticationHelper 在中添加如下配置: + expand sourceview plaincopy to clipboardprint? 1. 2. 3. 4. 2)创建 在FLEX工程modules/common目录下创建,用以实现Security验证 页码,24/29+ expand sourceview plaincopy to clipboardprint? 1. 2. 3. 4. 5. 3)引用authenticationHelper 在FLEX工程中添加如下配置: + expand sourceview plaincopy to clipboardprint? 1. 2. 3. 4. 5. 3)修改 在中调用authenticationHelper,修改后的内容如下: + expand sourceview plaincopy to clipboardprint? 1. 2. 3. layout="vertical" 4. horizontalAlign="center" 5. creationComplete="initApp()" 6. fontSize="15" > 7. 8. 9. 58. 59. 60. 61. 62. 63. 64. 65. 66. 67. 68. 69. 70. 71. 72. 73. 74. 75. 76. 77. 78. 79. 80. 81. 82. 83. 84. 85. 86. 87. 88. 89. 90. 91. 92. 93. 94. 四、编译运行 1)编译FLEX工程 选择Project—>Clean—>TestProject 2)拷贝FLEX编译目录bin-debug/modules到JAVA工程WebRoot下 3)启动本地数据库 4)启动服务器 5)服务器正常启动后,在浏览器内输入(其中9090为服务器端口号) localhost:9090/TestProject/modules/common/ 页码,26/29运行结果: 以Sky用户登录 登录首页 查看modules/admin/,由于权限控制将无法访问 页码,27/29 查看modules/common/ 以admin用户登录 页码,28/29 查看modules/admin/UserModule/swf,由于已经为该用户授予了权限,因此可以访问 查看modules/common/ 页码,29/29 到此Spring MVC+BlzeDS+Flex框架的搭建三个过程都已经结束,如果今后还有新的内容我会及时和大家分享
版权声明:本文标题:Spring_MVC_BlazeDS_Flex 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.freenas.com.cn/free/1705035149h470621.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论