728x90
반응형
앞글( http://tylee82.tistory.com/62 )에 이어서 클라이언트 작성을 알아보도록 한다.
이글은 머그초보의 블로그( http://mudchobo.tomeii.com/tt/239?category=8 ) 의 글을 참고로 작성됨을 알려드리며, 문제가 발생시 자삭 하겠습니다.

<< service-config.xml파일을 수정 >>

<factories>
  <factory id="springfactory" class="flex.messaging.factory.SpringFactory" /> 
</factories>
를 추가합니다.

<< remote-config.xml 파일을 수정 >>
<destination id="productmanager">
 <properties>
  <factory>springfactory</factory> 
  <source>productManager</source>
 </properties>
</destination> 

자세히 보시면 factory는 위에 service-config.xml파일에 정의한 놈이고, source는 bean이름입니다.
즉 applicationContext.xml파일에 정의한 그 bean이름을 저기에 적어 놓으면 됩니다.
그러면 그 bean을 flex로 가져와서 쓸 수 있습니다.


아 그리고 프로젝트에서 이상하게 contextroot가 WebContent로 되어있는데 프로젝트이름으로 고쳐줍시다-_-; 
---> (원래 WebContent 나오는게 정상 아닌가?? 뭐 난 아무것도 모르는 초보니깐.. 그냥 시키는데로...)

프로젝트 이름에 대고 마우스오른쪽버튼(alt+enter) properties를 선택, Flex Server부분 클릭.
context root를 프로젝트이름(SpringAndBlazeds)으로 바꿔줍시다.


<< FLEX 작성 >>
자 그러면 flex_src에 있는 SpringAndBlazeds.mxml을 수정해봅시다.
SpringAndBlazeds.mxml


<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"
 
applicationComplete="init();">
 
 
<mx:Script>
  <![CDATA[
   import mx.controls.Alert;
   import mx.rpc.events.FaultEvent;
   import mx.rpc.events.ResultEvent;
   import mx.rpc.remoting.RemoteObject;
   
   private function init():void {
    var remoteObject:RemoteObject = new RemoteObject();
    remoteObject.destination = "productmanager";
    remoteObject.addEventListener(ResultEvent.RESULT, resultHandler);
    remoteObject.addEventListener(FaultEvent.FAULT, faultHandler);
    remoteObject.getProducts();
   }
   
   private function resultHandler(event:ResultEvent):void{        
       dg.dataProvider = event.result;  
      }      
   
      private function faultHandler(event:FaultEvent):void{        
       Alert.show("실패 메세지 : " + event.fault.message);  
      }  
  ]]>
 
</mx:Script>
 
 
<mx:DataGrid id="dg" width="100%" height="100%" />
</mx:Application>

간단하게 Manager에 있는 getProducts를 호출해서 DataGrid에 넣는 코드입니다.

<< 실행 >>
이클립스 오른쪽아래에 server에다가 SpringAndBlazeds프로젝트를 추가합니다.
서버에 대고, 오른쪽버튼누르면, Add and Remove Project클릭해서 추가하면 됩니다.
서버를 가동합니다.
Run Flex Application을 실행해봅시다!


 - 후기
이번 예제를 실행하면서 나의 실력에 부족한점을 알아냈다.
  • Spring 프레임워크의 부족한 점 보안 
  • Flex에서 DataBase의 연동시 처리 방법 보안
  • iBatis의 데이터 베이스 정의 및 사용방법 보안
실질적으로 사용을 하기위한 프로젝트로 만들기 위해서는 많은 점을 보안해야 겠지만, 일단 오늘 돌려본 이 예제가 엄청난 도움이 될거라 생각한다. 아직 Spring 프로젝트 경험도 공부도 해본적이 없지만, EJB시스템 및 좀더 거대한 프로젝트를 위해서는 아무래도 공부를 해야겠다.

개인적으로 참 괜찮다고 생각한 DB 처리 java 소스들이 있어서 언제나 그것을 가지고 개발을 했는데, 아무래도 이제는 iBatis를 이용해 봐야겠다. 

FLEX의 컴포넌트 구조도 아는것이 없었는데, 일단 DB와 연동을 시켜봤으니 게시판부터 한번 개발 해보려 한다.

다시한번 머그초보님에게 감사를 표시합니다.

728x90
반응형
728x90
반응형

앞글 ( http://tylee82.tistory.com/61 )에 이은 포스트입니다.
이 글은 머드초보의 블로그 ( http://mudchobo.tomeii.com/tt/238?category=8 )의 글을 기초로 작성 됨을 알려드리며, 문제 발생시 자삭하겠습니다.

<< Manager클래스 작성 >>
실제로 BlazeDS를 이용해서 가져오는 놈은 이 Manager클래스가 됩니다.
Java Resources: src에서 오른쪽버튼 클릭하고, New를 해서 interface를 구현합니다.

package springapp.service;

import java.util.List;
import springapp.domain.Product;

public interface ProductManager {
 
public List<Product> getProducts();
}

getProducts라는 메소드가 하나 있군요! 구현해봅시다!!!

package springapp.service;

import java.util.List;

import springapp.dao.ProductDao;
import springapp.domain.Product;

public class ProductManagerImpl implements ProductManager {

 
private ProductDao productDao;
 
 
@Override
 
public List<Product> getProducts() {
 
return productDao.getProductList();
 
}

 
public void setProductDao(ProductDao productDao) {
 
this.productDao = productDao;
 
}
}

getProducts라는 함수는 Dao에서 getProductList를 호출하는 놈이네요.
요 아래에는 setter가 있네요. 이건 spring에서 DI를 하기위해 존재하는 setter입니다^^
서비스도 완성이 되었네요! 이제 설정파일을 작성해봅시다.

WEB-INF/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: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/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"
>

 
<!-- Enable @Transactional support -->
 
<tx:annotation-driven />

 
<!-- Enable @AspectJ support -->
 
<aop:aspectj-autoproxy />

 
<aop:config>
 
<aop:advisor pointcut="execution(* *..ProductManager.*(..))"
   
advice-ref="txAdvice" />
 
</aop:config>

 
<tx:advice id="txAdvice">
 
<tx:attributes>
   
<tx:method name="save*" />
   
<tx:method name="get*" read-only="true" />
 
</tx:attributes>
 
</tx:advice>

 
<bean id="productManager"
 
class="springapp.service.ProductManagerImpl">
 
<property name="productDao" ref="productDao" />
 
</bean>

</beans>

Dao부분의 설정파일인 applicationContext-ibatis.xml파일을 봅시다.
WEB-INF/applicationContext-ibatis.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: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/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"
 
p:location="classpath:properties/jdbc.properties" />

 
<bean id="dataSource"
 
class="org.springframework.jdbc.datasource.DriverManagerDataSource"
 
p:driverClassName="${jdbc.driverClassName}" p:url="${jdbc.url}"
 
p:username="${jdbc.username}" p:password="${jdbc.password}" />

 
<!-- Transaction manager for iBATIS Daos -->
 
<bean id="transactionManager"
 
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
 
<property name="dataSource" ref="dataSource" />
 
</bean>

 
<!-- SqlMap setup for iBATIS Database Layer -->
 
<bean id="sqlMapClient"
 
class="org.springframework.orm.ibatis.SqlMapClientFactoryBean">
 
<property name="dataSource" ref="dataSource" />
 
<property name="configLocation"
   
value="classpath:springapp/dao/SqlMapConfig.xml" />
 
</bean>

 
<!-- Add additional Dao definitions here -->
 
<bean id="productDao"
 
class="springapp.dao.ProductDaoImpl">
 
<property name="sqlMapClient" ref="sqlMapClient" />
 
</bean>
 
</beans>

jdbc.properties파일은 properties라는 package를 만들고, jdbc.properties파일을 넣어버립시다.

jdbc
.driverClassName=com.mysql.jdbc.Driver
jdbc
.url=jdbc:mysql://DB주소
jdbc
.username=DB아이디
jdbc
.password=DB비밀번호

이 설정들의 bean들의 관계를 보고 싶다면-_-;
Spring Elements에서 오른쪽버튼 클릭하고 properties를 선택.
Bean Support를 선택, Add한 뒤 두개의 설정파일(applicationContext.xml, applicationContext-ibatis.xml)선택.
Config set에서 New하고 Name에 applicationContext라고 하고, 두개다 체크 오케이~
그럼 이제 스프링 설정파일에서 에러를 찾아낼 수 있어요!
bean들의 관계를 그래프로도 볼 수 있네요!
Config set에 추가한 applicationContext에다가 마우스오른쪽버튼을 클릭하면 open graph로 볼 수 있어요!

이제 클라이언트 구현으로....다음 시간에-_-;
728x90
반응형
728x90
반응형

세팅 ( http://tylee82.tistory.com/60 )이 완료되면 이제 코딩을 해보겠습니다.
머드초보의 블러그의 글을 참고로 작성된 글임을 다시한번 강조합니다.



<< MySQL >>
일단 DB 구조입니다. 
CREATE TABLE `products` (

  `id` int(11) NOT NULL,
  `description` varchar(255) default NULL,
  `price` decimal(15,2) default NULL,
  PRIMARY KEY  (`id`),
  KEY `products_description` (`description`)
) ENGINE=MyISAM DEFAULT CHARSET=UTF8;

INSERT INTO `products` (`id`, `description`, `price`) VALUES 
(1, 'Lamp', 391.50),
(2, 'Table', 2918.85),
(3, 'Chair', 884.27);

※ mysql 설치시 charset을 utf-8로 설정을 하였기때문에 UTF8로 charset을 잡았습니다.

<< 프로젝트 구조 >>

그냥 src폴더는 자바서버단 폴더구요. flex_src폴더는 플렉스클라이언트단 폴더입니다.



<< web.xml 의 수정 (스프링 설정) >>

web.xml 아래 코드 추가
<context-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>/WEB-INF/applicationContext*.xml</param-value>
</context-param>


<listener>
 <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

applicationContext*라고 적어 놓은 이유가 ibatis랑 분리를 하려고 합니다.
설정파일은 applicationContext.xml과 applicationContext-ibatis.xml 두개를 사용할껍니다.

※ 위 코드 추가시 주의 사항 : web.xml의 엘리먼트의 위치는 순서가 있습니다. 순서가 맞지 않는다면 에러가 납니다. ( 참고글 : http://woongbox.tistory.com/tag/The%20content%20of%20element%20type%20"web-app"%20must%20match )

<< 소스코딩 >>
src에다가 코딩을 해봅시다.
java는 perspective를 Java EE로 바꾸고 합시다.


우선 domain부분에 ValueObject를 하나 만들어봅시다.
Java Resources:src에다가 New를 하고 class를 선택합니다.
package는 springapp.domain이라고 하구요.
Name은 Product라고 하고 Finish

Product.java

package springapp.domain;

public class Product {

 
private int id;
 
private String description;
 
private Double price;

 
public int getId() {
 
return id;
 
}

 
public void setId(int id) {
 
this.id = id;
 
}

 
public String getDescription() {
 
return description;
 
}

 
public void setDescription(String description) {
 
this.description = description;
 
}

 
public Double getPrice() {
 
return price;
 
}

 
public void setPrice(Double price) {
 
this.price = price;
 
}
}

ProductDao를 만들어봅시다.
Java Resource:src에 New해서 interface를 추가합시다.
package에다가 springapp.dao라고 써놓고, 
Name에다가 ProductDao라고 씁시다.

package springapp.dao;

import java.util.List;
import springapp.domain.Product;

public interface ProductDao {
 
public List<Product> getProductList();
}

딸랑 ProductList만 가져오는 메소드가 있어요! 
저 Dao인터페이스를 구현해봅시다!!!

package springapp.dao;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;

import springapp.domain.Product;

public class ProductDaoImpl extends SqlMapClientDaoSupport implements
 
ProductDao {

 
protected final Log logger = LogFactory.getLog(getClass());

 
@SuppressWarnings("unchecked")
 
@Override
 
public List<Product> getProductList() {
  logger
.info("Getting products!");
 
return getSqlMapClientTemplate().queryForList("getProductList");
 
}
}

<< ibatis >>
ibatis부분인데요. 설정파일을 보도록 하겠습니다.

src/springapp/dao/SqlMapConfig.xml

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

<!DOCTYPE sqlMapConfig      
    PUBLIC "-//ibatis.apache.org//DTD SQL Map Config 2.0//EN"      
    "http://ibatis.apache.org/dtd/sql-map-config-2.dtd">


<sqlMapConfig>
 
<typeAlias alias="Product" type="springapp.domain.Product"/>

 
<sqlMap resource="springapp/dao/MySQLProduct.xml" />
</sqlMapConfig>

alias지정해주고, resource는 src/springapp/dao/MySQLProduct.xml파일입니다.

MySQLProduct.xml

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

<!DOCTYPE sqlMap      
    PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN"      
    "http://ibatis.apache.org/dtd/sql-map-2.dtd">


<sqlMap namespace="Product">

 
<resultMap id="ProductMap" class="Product">
 
<result property="id" column="id" />
 
<result property="description" column="description" />
 
<result property="price" column="price" />
 
</resultMap>

 
<select id="getProductList" resultMap="ProductMap">
  select id, description, price from products
 
</select>

</sqlMap>

getProductList라는 것은 products테이블에서 내용을 select하는 것이네요.
Dao가 완성되었네요! 너무 길어지니 다음이시간에 ...

728x90
반응형
728x90
반응형
스프링프레임워크에 플렉스를 연동하는 간단한 예제를 만들어 보겠다. 

이 포스트는 머드초보님의 블로그(http://mudchobo.tomeii.com)를 기반으로 작성하였으며, 난 스프링프레임워크에 대한 지식이 많지 않다.. 물로 플렉스도.. 배우는 과정이기 때문에 그냥 따라해본다.

머드초보님 글 감사합니다.

일단 세팅부터 하자.

<< 준비물 >>
Eclipse IDE for Java EE Developers  :http://www.eclipse.org/downloads/

Flex Builder 3 Eclipse Plug-in(로그인후받을 수 있음) : 
http://www.adobe.com/cfusion/tdrc/index.cfm?product=flex_eclipse

Spring Framework 2.5.6 : http://www.springframework.org/download

Spring과 BlazeDS연동라이브러리 : blazeds-spring-beta1.jar 현재 beta1이군요.
http://www.igenko.org/archiva/repository/igenko/com/adobe/flex/blazeds-spring/

↑ 위 링크 없졌다..그래서 Sewon On Software 블로그 ( http://sewony.tistory.com/entry/BlazeDS-와-스프링Spring-연동하기 ) 에서 다운 받았다. 외국사이트에서 구하면 된다고 하는데, 구글에서 찾다보니 이곳이 나와 난 여기서 다운 받았음..이거 말고 다른 라이브러리가 존재하는것 같지만, 일단 이것을 사용하도록 한다. 난 아무것도 모르고 하는것 이기에...;;;

설치는 모두 알아서 설치 하도록 한다. 뭐 그냥 깔고 압축풀고 ....


Blazeds 프로젝트 생성
1. File -> New -> Project선택, Flex Project선택 후 Next
Project : SpringAndBlazeds
Application Type : Web Application
Application server type : J2EE

2. J2EE 세팅 설정
Target runtime : Tomcat
설정이 안되어 있다면 New 한다음에 Apache폴더에 Tomcat 6.0을 선택하고, 해당 톰캣의 경로를 지정하고, Finish를 클릭한다.
 flex WAR파일을 선택하라고 하는데 받아놓은 blazeds.war파일을 선택한다.
Finish를 클릭하면 끝난다.


- 스프링IDE 설치

1. 이클립스메뉴에서 Help -> Software Updates -> Find And Install 선택
Search for new features to install를 선택 후 Next
New Remote Site선택 Name은 Spring IDE, url은 http://dist.springframework.org/release/IDE고 쓴다.




추가한 것만 체크된 상태에서 Finish클릭!

몇개는 설치 못하는데 설치 못하는 것은 체크해제를 시킨다...ㅡ.ㅡ;;
Dependencies에서 Spring IDE Dependencies 체크해제
Integration에서 Spring IDE AJDT Intergration 체크해제
AspectJ Development Tools도 설치하려면 하면된다. 난 사용할줄 모름...
Next -> agree -> finish하면 설치가 됩니다.
설치가 다 되면 이클립스ide를 restart하라고 나와서 리스타트^^

근데 지금 회사에서는 외부인터넷 접속에 문제가 있어서 그런지 몰라도...저 주소가 안된다...


2. 만든 프로젝트에  마우스 오른쪽버튼을 클릭해서 Spring Tools -> Add Spring Project Nature선택 하면 완료!!



3. 필요한 라이브러리를 복사한다. ( 근데 어디다가 복사 하라는거지??음...일단 WEB-INF/lib 에 복사 한다... 어찌됬건 모두 라이브러리 파일이니깐...)

dist/spring.jar : 스프링프레임워크를 쓰기 위해 꼭 필요한 놈.

dist/module/spring-test.jar : 스프링테스트 할 때 필요한 놈.

lib/jakarta-commons/commons-logging.jar : 로그찍을 때 필요한 놈.

lib/ibatis/ibatis-2.3.0.677.jar : ibatis쓸 때 필요한 놈.

lib/cglib/cglib-nodep-2.2.jar : Junit으로 테스트 할 때 필요한데, JUnit테스트를 할 때에는 Interface가 구현이 안되어있어서(aop를 사용하려면 interface가 구현이 되어있어야 한다고 하더군요) 필요한 놈. --> http://sourceforge.net/project/showfiles.php?group_id=56933

lib/aspectj/aspectjweaver.jar : aop때문에 필요한 놈 같은데-_-;  
lib/junit/junit-4.5.jar : JUnit을 사용하기 위해 필요한 놈.

mysql-connector-java-5.1.7-bin.jar : mysql Connector. db가 다른거면 다른 Connector가 있으면 돼요!
blazeds-spring-beta1.jar : 위에서 설명한 spring과 blazeDS와 연동할 때 필요한 놈.


여기까지하면 세팅완료!!
728x90
반응형

+ Recent posts