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 |