안드로이드에서 ID/PW 는 어떻게 저장할까요?

어플리케이션 별로 알아서 저장해도 상관은 없지요.

 

그러나 안드로이드에서는 이러한 로그인 정보를 통합적으로 관리 할 수 있도록 Authenticator Service 를 제공합니다.

안드로이드의 설정에 “Accounts & Sync” 메뉴에 가보면 이렇게 관리되는 계정을 확인 할 수 있습니다.

 

아마 대부분 Google 계정만 등록되어 있을텐데 이번 포스트에서는 내가 만든 Authenticator Service 를 등록해 보도록 하겠습니다.

 

 

먼저 설정의 “Accounts & Sync” 메뉴의 계정리스트에 나오도록 해야하는데 이것은 서비스 구현으로 이루어 집니다.

 

1. manifest 에 서비스 등록하기

   - AndroidManifest.xml 파일에 다음과 같이 서비스를 등록합니다.

<service android:name=".authenticator.AuthenticationService"> 
<intent-filter>
<action
android:name="android.accounts.AccountAuthenticator"
/>
</intent-filter>
<meta-data
android:name="android.accounts.AccountAuthenticator"
android:resource="@xml/authenticator"
/>
</service>


 

2. xml 리소스 등록하기

   - xml/authenticator.xml 파일을 만들고 아래 내용을 입력합니다.

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


<account-authenticator xmlns:android="http://schemas.android.com/apk/res/android"
android:accountType="net.cranix.android.cranixsyncsample"
android:icon="@drawable/icon"
android:smallIcon="@drawable/icon"
android:label="@string/app_name"
/>


 

3. sample 서비스 만들기

   - 일단 등록이 되는지 확인을 위해 아래와같이 빈 Service 를 만듭니다.

package net.cranix.android.cranixsyncsample.authenticator;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;

public class AuthenticationService extends Service {
@Override
public void onCreate() {
// TODO Auto-generated method stub
}

@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}

}


 

   - 그후 설정에 “Accounts & Sync” 에 가보면 등록이 되어 있는것을 볼 수 있습니다.

image

 

 

자신이 추가한 계정을 클릭하면 아무 반응이 없는것을 알 수 있습니다.

서비스를 구현하지 않았으니 당연한 결과 입니다.

 

3번에서 만든 서비스를 구현해서 로그인 정보 기록이나 나아가서 주소록 싱크 어플 등을 만들수 있게 됩니다.

다음에는 이 서비스를 실제로 구현하는 방법을 알아보도록 하겠습니다.

by cranix 2010. 12. 23. 14:53

안드로이드 sync 를 사용하기 위해서는 계정접근을 위한 Service 와 sync 를 위한 Service 가 필요합니다.

 

 

1. 계정 접근을 위한 Service

   - 아래와 같은 형태로 Service 를 추가하게 됩니다.

<service
    android:name=".authenticator.AuthenticationService"
    android:exported="true">
    <intent-filter>
        <action
            android:name="android.accounts.AccountAuthenticator" />
    </intent-filter>
    <meta-data
        android:name="android.accounts.AccountAuthenticator"
        android:resource="@xml/authenticator" />
</service>

 

   - 위와 같은 형태로 서비스를 등록하면 안드로이드 설정메뉴중 “Accounts & Sync” 메뉴에 자동으로 등록됩니다.image

 

   - 여기 나오는 메뉴의 형태는 @xml/authenticator 에서 정의합니다.

<account-authenticator xmlns:android="http://schemas.android.com/apk/res/android"
    android:accountType="com.example.android.samplesync"
    android:icon="@drawable/icon"
    android:smallIcon="@drawable/icon"
    android:label="@string/label"
/>

 

  - 로그인후 받은 토큰을 내부에 저장하고 다음번 로그인시에 그 토큰으로 자동으로 로그인합니다.

 

 

 

2. Sync 를 위한 Service

  - 아래와 같은 형태로 Service 를 추가하게 됩니다.

<service
    android:name=".syncadapter.SyncService"
    android:exported="true">
    <intent-filter>
        <action
            android:name="android.content.SyncAdapter" />
    </intent-filter>
    <meta-data
        android:name="android.content.SyncAdapter"
        android:resource="@xml/syncadapter" />
    <meta-data
        android:name="android.provider.CONTACTS_STRUCTURE"
        android:resource="@xml/contacts" />
</service>

 

   - 싱크가 실행될때 위의 서비스가 자동으로 호출되게 됩니다.

   - 싱크는 저장된 토큰으로 외부와 통신해서 업데이트된 데이터를 받아와서 내부에 맞게 가공해서 업데이트 하도록 합니다.

by cranix 2010. 12. 20. 11:39

 

contacts-2.png

 

- Contact

   - 현재 계정의 상태

   - 표시되는 이름

   - 전화번호를 가지고 있는지 유무

 

- RawContact

   - 계정 (ex-google,daum,naver,custom …)

 

- Data

   - 이름, 전화번호, Email, …

by cranix 2010. 12. 20. 11:21

C 언어계얼 소스코드를 보다보면 종종 아래와 같은 소스를 볼 수 있다.

#define M do {printf("hello");printf("world");} while(0)

 

처음에 이 코드를 보았을때에는 컴파일러가 무슨 장난을 치는구나 라고 생각했는데..

이유는 의외로 단순했다.

 

먼저 위와 같은 역할을 하도록 매크로를 짜보자.

 

<첫번째>

#define M printf("hello");printf("world")

이것은 아래와 같은 if 조건이 있을대 오류가 난다.

if (condition)
     M;
else
     printf("!!!");


<두번째>

그렇다면 중괄호로 묶으면 안될까?

#define M {printf("hello");printf("world");}

 

이것은 첫번째와 같은 조건식에 넣었을때 세미콜론 때문에 오류가 나겐된다.

 

if (condition)
    M
else
    printf("!!!");

이와 같이 쓴다면 문제 없이 돌아간다.

하지만 대부분의 프로그래머가 줄 맨 끝에 세미콜론을 쓰는것이 익숙하기 때문에 저런 방식은 오류를 유발할 확률이 높다.

 

그래서 결국 위와같이 do while(0) 을 사용하게 되는것이다.

원문 : http://guntn.blog.me/100045877821

 

 

 

 

by cranix 2010. 12. 13. 18:39
싱글톤 인스턴스는 객체의 인스턴스가 오직 하나만 존재하는것을 보장하도록 코딩하는것을 말한다.
자바에서는 private 생성자를 이용해서 만들면 되었지만 ObjectiveC 에서는 그게 불가능하기 때문에 아래와 같은 방법을 쓴다.

#import "TemperatureConverterBO.h"



static TemperatureConverterBO *instance = nil;



@implementation TemperatureConverterBO



+ (TemperatureConverterBO *)getInstance {

@synchronized(self) {

if (instance == nil) {

instance = [[TemperatureConverterBO alloc] init];

}

}

return instance;

}


+(id)allocWithZone:(NSZone *)zone {

@synchronized(self) {

if (instance == nil) {

instance = [super allocWithZone:zone];

return instance;

}

}

return nil;

}


-(id)copyWithZone:(NSZone *)zone {

return self;

}

-(id)retain {

return self;

}

-(unsigned)retainCount {

return UINT_MAX;

}

-(void)release {

}

-(id)autorelease {

return self;

}


@end


이 방법은 alloc 을 불러도 한번 생성되었으면 더이상 생성되지 않는다.
그리고 retainCount 가 맥스값이 나가기때문에 GC 에 의해 해제되지 않는다.
결국 하나의 인스턴스를 보장한다.

by cranix 2010. 11. 30. 18:37

이번 업데이트는 개인적인 사정으로 상당히 오래걸렸습니다.

기다리신분들 있다면 죄송합니다.ㅜㅜ

 

그리고 이번 버젼에는 속도를 최우선으로 신경썻습니다.

속도를 올리기위해 여러가지 시도를 해 보았지만 획기적으로 올리는 방법은 찾지 못했습니다.

그래서 생각한게 검색범위를 줄이는것입니다.

 

이번 버젼에서는 "모두검색" 버튼을 추가해서 처음에는  통화로그에서만 검색하다가 "모두검색" 버튼을 누르면 전체 연락처에서 찾아주도록 하였습니다.

이렇게 함으로서 초기 구동속도와 검색속도를 대폭 향상시켰습니다.

물론 설정에서 꺼 놓으면 이전처럼 모두 검색 가능합니다.

또한 "간단검색" (떨어져있는 글자 매치시키지 않음) 기능과 "이름만검색" (이름만 검색하고 전화번호는 검색하지 않음) 을 추가해서 검색설정을 할 수 있게 하였습니다.

이렇나 기능들로 인해 연락처가 많아서 속도가 느리신분들은 어느정도 커버할 수 있을것이라고 생각합니다.

 

그리고 이전 버젼에서 문제가 되었던 비정상 종료 되던 버그는 현재 버젼에서는 수정했습니다.

 

또한 이번 버젼에는 안드로이드 공식 마켓에도 올려놓았으니 받으실때 좀 더 편할 것입니다.^^

 

 

 

by cranix 2010. 11. 7. 16:47

Spring 을 쓰는이유가 여러가지 있겠지만 나같은 경우는 테스트의 편안함을 가장 큰 이유로 꼽는다.

그래서 테스트를 위한 spring 3.0 의 maven 기본 설정을 알아보도록 하자.

 

1. pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
 <modelVersion>4.0.0</modelVersion>
 <groupId>net.cranix.project.otm</groupId>
 <artifactId>otm</artifactId>
 <packaging>war</packaging>
 <version>0.0.1-SNAPSHOT</version>
 <name>overtimemanagement Maven Webapp</name>
 <url>http://maven.apache.org</url>
 <dependencies>
  <dependency>
   <groupId>junit</groupId>
   <artifactId>junit</artifactId>
   <version>3.8.1</version>
   <scope>test</scope>
  </dependency>
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-webmvc</artifactId>
   <version>3.0.4.RELEASE</version>
  </dependency>
  <dependency>
   <groupId>commons-dbcp</groupId>
   <artifactId>commons-dbcp</artifactId>
   <version>1.4</version>
  </dependency>
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-jdbc</artifactId>
   <version>3.0.4.RELEASE</version>
  </dependency>

  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-test</artifactId>
   <version>3.0.5.RELEASE</version>
  </dependency>
  <dependency>
   <groupId>javax.servlet</groupId>
   <artifactId>servlet-api</artifactId>
   <version>2.5</version>
   <scope>provided</scope>
  </dependency>
  <dependency>
   <groupId>org.mockito</groupId>
   <artifactId>mockito-all</artifactId>
   <version>1.8.5</version>
   <scope>test</scope>
  </dependency>

 </dependencies>
 <build>
  <finalName>overtimemanagement</finalName>
  <plugins>
   <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <configuration>
     <target>1.6</target>
     <source>1.6</source>
     <encoding>UTF-8</encoding>
    </configuration>

   </plugin>
  </plugins>
 </build>
</project>

 

 

 

 

2. web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app 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"
 version="2.4">
 <display-name>otm</display-name>

 <servlet>
  <servlet-name>otm</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  <load-on-startup>1</load-on-startup>
 </servlet>

 <servlet-mapping>
  <servlet-name>otm</servlet-name>
  <url-pattern>/main/*</url-pattern>
 </servlet-mapping>
</web-app>

 

 

 

 

3. otm-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:p="http://www.springframework.org/schema/p"
 xmlns:mvc="http://www.springframework.org/schema/mvc" 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/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
       
    <import resource="classpath:otm-springcontext.xml"/>

 
</beans>

- 테스트를 위해서는 WEB-INF 디렉토리에 설정파일을 두는것 보다는 classpath 상에 두는것이 낳다.

그렇기 때문에 위와같이 WEB-INF 디렉토리의 컨텍스트 파일에는 임포트만 하도록 한다.

 

 

4. otm-springcontext.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:mvc="http://www.springframework.org/schema/mvc" 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/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

 <context:component-scan base-package="net.cranix.project.otm" />
 <bean id="viewResolver"
  class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  <property name="prefix" value="/WEB-INF/jsp/" />
  <property name="suffix" value=".jsp" />
 </bean>

</beans>

 

 

5. 테스트코드

package net.cranix.project.otm.controller;

import static org.junit.Assert.*;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;


@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("/otm-springcontext.xml")
public class MainControllerTest {
 @Autowired
 private MainController mainController = null;
 
 @Test
 public void testIndex() {
  String page = mainController.index();
 
  assertEquals("index",page);
 }

}

- 이와같이 셋팅하면 위와 같은 형태로 어노테이션 기반으로 스프링의 DI 를 쉽게 사용하여 테스트 할 수 있게된다.

 

 

언제나 생각한거지만 Spring 은 예술이다.

 

 

 

 

 

 

 

 

 

 

by cranix 2010. 10. 25. 22:49

1. 테스트를 위한 view 페이지를 만든다.

   - WEB-INF/jsp/dao.jsp 생성

<html>
<body>
<h2>data : ${data }</h2>
</body>
</html>


 

2. DAO 클래스 작성

   - package : net.cranix.web.hellospring3.dao

   - name : TestDAO

 

package net.cranix.web.hellospring3.dao;

public class TestDAO {
 private String data = null;
 public void setData(String data) {
  this.data = data;
 }
 public String getData() {
  return data;
 }
}

   - @Component 를 사용하지 않았기 때문에 bean 설정파일에 등록해 주어야 한다.

 

 

3. Controller 작성

   - package : net.cranix.web.hellospring3

   - name : DaoProcess

package net.cranix.web.hellospring3;

import net.cranix.web.hellospring3.dao.TestDAO;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class DaoProcess {
 public TestDAO testDAO = null;
 

// 스프링 bean 에 등록되어있는 컴포넌트를 자동으로 입력해 준다.

// 이것으로 이 파일에대한 bean 등록을 하지않아도 된다.
 @Autowired
 public void setTestDAO(TestDAO testDAO) {
  this.testDAO = testDAO;
 }
 
 @RequestMapping("dao")
 public String dao(Model model) {
  model.addAttribute("data",testDAO.getData());
  return "dao";
 }
 
}

 

 

4. bean 설정파일 수정

    - WEB-INF/hello-servlet.xml

<beans ...>
...
 <bean id="testDAO" class="net.cranix.web.hellospring3.dao.TestDAO">
  <property name="data" value="daodata!!"/>
 </bean>
</beans>

   - 결국 실제 string 은 이 설정파일에서 넣어준다.

 

 

5. 실행해보기

   - http://localhost:8080/hellospring3/dao.do 접근

 

 

6. 마무리

   - 사실 스프링 내에서 관리되는 모든 bean 들은 어노테이션을 추가하면 xml 설정을 하지않아도 되게 되어있다. 그러나 dao 같이 connection pool 을 가지고 있어야 하는 모듈 들은 위와 같이 해서 connection 정보를 xml 파일에 저장하는것이 효율적인 방법이다.

 

' > Spring' 카테고리의 다른 글

maven Spring3.0 webmvc 기본설정  (63) 2010.10.25
Spring 3.0 webmvc 의 request 를 처리하는 8가지 방법  (844) 2010.09.29
Spring 3.0 webmvc heloworld!!!  (31) 2010.09.29
Spring 에서 JUnit 로 테스트하기  (733) 2007.06.10
이거 이해가 안된다.  (64) 2007.06.09
by cranix 2010. 9. 29. 18:13

1. 결과를 뿌려주기위해 jsp 를 먼저 만든다.

    - WEB-INF/jsp/request/request.jsp 생성

<html>
<body>
<h2>request</h2>
</body>
</html>


   - WEB-INF/jsp/request/request2.jsp 생성

<html>
<body>
<h2>message : ${message }</h2>
</body>
</html>

 


2. RequestProcess 클래스 생성

   - package : net.cranix.web.hellospring3

   - className : RequestProcess

 

package net.cranix.web.hellospring3;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

 

// 클래스에 @RequestMapping 어노테이션을 쓰면 상위 URL 이 추가된다.

// http://localhost:8080/hellospring3/request/... 형태로 접근해야 한다.
@Controller
@RequestMapping("request")
public class RequestProcess {


// return void 이면 request 와 같은 경로의 view 를 자동으로 찾는다.

// http://localhost:8080/hellospring3/request/request.do 로 접근
 @RequestMapping("request")
 public void request1() {
 }
 
 
// return string 이면 해당 값의 view 를 찾는다.

// http://localhost:8080/hellospring3/request/request2.do 로 접근
 @RequestMapping("request2")
 public String request2() {
  return "request/request";
 }
 
 
// parameter 가 있으면 파라미터를 받는다.
// 만약 파라메터를 프리미티브 타입으로 해 놓으면 넘기지 않으면 오류난다.
// 그럼으로 파라메터는 왠만하면 Wrapper 타입으로 써줘야 한다.

// http://localhost:8080/hellospring3/request/request3.do?param1=aa&param2=2 로 접근
 @RequestMapping("request3")
 public String request3(String param1,Integer param2) {
  System.out.println("param1:"+param1+",param2:"+param2);

  return "request/request";
 }
 

// @RequestParam 어노테이션으로 파라메터의 좀 더 세세한 설정이 가능하다.

// http://localhost:8080/hellospring3/request/request4.do?p1=aa&p2=2 로 접근
 @RequestMapping("request4")
 public String request4(
   @RequestParam(value="p1",required=true) String param1,
   @RequestParam(value="p2",required=true) Integer param2
   ) {
  System.out.println("param1:"+param1+",param2:"+param2);

  return "request/request";
 }
 
 
// 파라메터에 Model 객체를 넣어놓으면 해당 객체에 속성을 추가하는것으로 view 에 데이터를 던져 줄 수 있다.

// http://localhost:8080/hellospring3/request/request5.do 로 접근
 @RequestMapping("request5")
 public String request5(Model model) {
  model.addAttribute("message","hello5");
  return "request/request2";
 }
 
// 리턴을 ModelAndView 를 받는것으로 view 에 데이터를 던져 줄 수도 있다.

// http://localhost:8080/hellospring3/request/request6.do? 로 접근
 @RequestMapping("request6")
 public ModelAndView request6() {
  ModelAndView modelAndView = new ModelAndView();
  modelAndView.setViewName("request/request2");
  modelAndView.getModel().put("message","hello6");

  return modelAndView;
 }
 
 
// 파라메터와 model 을 혼용해서 사용할 수 있다.

// http://localhost:8080/hellospring3/request/request7.do?param1=aa&param2=2 로 접근
 @RequestMapping("request7")
 public String request7(String param1,Integer param2,Model model) {
  System.out.println("param1:"+param1+",param2:"+param2);
  model.addAttribute("message","hello7");

  return "request/request2";
 }
 
// 마찬가지로 파라메터와 ModelAndView 를 같이 사용할수 있다.

// http://localhost:8080/hellospring3/request/request8.do?param1=aa&param2=2 로 접근
 @RequestMapping("request8")
 public ModelAndView request8(String param1,Integer param2) {
  System.out.println("param1:"+param1+",param2:"+param2);
  ModelAndView modelAndView = new ModelAndView();
  modelAndView.setViewName("request/request2");
  modelAndView.getModel().put("message","hello8");

  return modelAndView;
 }
}

 

 

3. 마무리

   - 어떤 방식을 쓰던 개발자의 자유다. 역시 스프링답게 상당히 프리하게 풀어놨다.

 

 

 

 

 

by cranix 2010. 9. 29. 17:33

1. eclipse 에서 Maven Project 생성

    - archetype :

        - Group Id : org.apache.maven.archetypes

        - Artifact Id : maven-archetype-webapp

    - group Id : net.cranix.web

    - artifact Id : hellospring3

 

 

2. maven dependency 에 spring-mvc 추가

    - 기본 웹 archetype 을 선택했기때문에 spring-webmvc 라이브러리를 추가해 줘야한다.

    - 그리고 기본적으로 메이븐 플러그인에서 이클립스 버젼을 관리하도록 아래와 같이 버젼셋팅 플러그인을 추가한다.

    - pom.xml 파일에 아래 추가

<dependencies>
...
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-webmvc</artifactId>
   <version>3.0.4.RELEASE</version>
  </dependency>
</dependencies>
<build>
...
  <plugins>
   <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <configuration>
     <target>1.6</target>
     <source>1.6</source>
    </configuration>
   </plugin>
  </plugins>
</build>

    - Maven -> Update Project Configuration 로 프로젝트 설정 업데이트

    - 플러그인 설정을 하지않으면 기본적으로 1.5 이하버젼으로 셋팅되기때문에 어노테이션을 쓸 수가 없음으로 주의하자.

 


3. 프로젝트에 java 소스디렉토리 추가

   - 처음 만들면 java 소스 폴더가 없기때문에 만들어주자.

   - New > Source Folder

       - Folder name : src/main/java

 

 

4. 톰켓 작동 테스트

   - Run As -> Maven build...

      - Goals : tomcat:run

   - http://localhost:8080/hellospring3/ 접속확인

 

 

5. WEB-INF/web.xml 파일수정

   - 톰켓으로 들어오는 요청을 spring-webmvc 로 돌리기 위해서 셋팅을 해야한다.

   - *.do 로 들어오는 모든 요청을 spring 이 처리하도록 한다.

<?xml version="1.0" encoding="UTF-8"?>
<web-app 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"
 version="2.4">
 
 <display-name>Archetype Created Web Application</display-name>
 
 <servlet>
  <servlet-name>hello</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
 </servlet>
 
 <servlet-mapping>
  <servlet-name>hello</servlet-name>
  <url-pattern>*.do</url-pattern>
 </servlet-mapping>
 
</web-app>

    - 기본적인 web.xml 파일은 jsp 버젼을 2.3 을 채택하고 있기때문에 위 처럼 버젼을 2.4 로 바꾸지 않으면 jsp 의 EL 표현식을 사용할 수 없으니 주의하자.

 

 

6. spring bean 설정파일 만들기

    - spring bean 설정파일 이름은 [servlet-name]-servlet.xml 형태로 만들어야 한다.

    - WEB-INF/hello-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:p="http://www.springframework.org/schema/p"
 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">


 <context:component-scan base-package="net.cranix.web.hellospring3" />
 <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  <property name="prefix" value="/WEB-INF/jsp/" />
  <property name="suffix" value=".jsp" />
 </bean>
 
</beans>

    - context:component-scan 태그는 이름그대로 어노테이션 기반의 spring3-mvc 컴포넌트를 검색하도록 하기위한 기본 패키지를 지정한다. 여기에 지정된 패키지는 하위 패키지까지 자동으로 검색해서 컴포넌트를 등록해 준다.

    - spring-webmvc 는 id 가 viewResolver 인 bean 을 가지고 출력할 view 페이지의 경로를 만들어 낸다.

 

7. hello jsp 만들기

   - WEB-INF/jsp/hello.jsp 생성 (jsp 디렉토리도 생성)

<html>
<body>
<h2>hello ${message}</h2>
</body>
</html>


 

8. hello controller 만들기

   - New -> Class

      - Package : net.cranix.web.hellospring3

      - Name : Hello

 

package net.cranix.web.hellospring3;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class Hello {
 @RequestMapping("hello")
 public String hello(Model model) {
  model.addAttribute("message","spring3!!");
  return "hello";
 }
}


9. 실행하기

   - Run As -> Maven build...

      - Goals : tomcat:run

   - http://localhost:8080/hellospring3/hello.do 접속확인

 

 

10. 마무리

  - 스프링3.0 webmvc 모델은 어노테이션 지원을 강화했다. 거의 xml 편집을 하지않아도 될 정도이기 때문에 상당히 편해졌음을 알 수 있다.

 

by cranix 2010. 9. 29. 16:18
| 1 2 3 4 5 6 7 8 ··· 33 |