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

스프링은 단위 테스트를 편하게 할수있는 클래스를 제공해준다.

어떤 클래스를 단위테스트 하려면 그 클래스와 연관성있는 모든 클래스를 해줘야지만 할수 있었다.

스프링은 빈 들을 모두 관리해줌으로써 간단하게 이 문제를 해결하고 있다.

[code]package dic.dao;

import static org.junit.Assert.*;

import java.util.Calendar;
import java.util.List;

import org.junit.Before;
import org.junit.Test;
import org.springframework.context.support.FileSystemXmlApplicationContext;

import dic.model.Accounting;

public class AccountingDaoTest {
 private AccountingDao ad = null;
 @Before
 public void setUp() throws Exception {
  String[] paths = {
   "D:\\cranix\\workspace\\DICProject\\WebContent\\WEB-INF\\applicationContext.xml",
   "D:\\cranix\\workspace\\DICProject\\WebContent\\WEB-INF\\applicationContext-jdbc.xml"
  };
  FileSystemXmlApplicationContext ctx = new FileSystemXmlApplicationContext(paths);

  ad = (AccountingDao)ctx.getBean("accountingDao");
 }

 @Test
 public void testGetAccountingList() {
  List<Accounting> ll = ad.getAccountingList();
  assertTrue(true);
 }

 @Test
 public void testInsertAccounting() {
  Accounting ac = new Accounting();
  ac.setInPrice(10);
  ac.setRegDate(Calendar.getInstance().getTime());
  assertEquals(ad.insertAccounting(ac),1);
 }
}[/code]


위 소스에서처럼 빈설정 파일을 FileSystemXmlApplicationContext 클래스에 넘겨주기만 하면 알아서 연관 클래스 설정을 해준다.

무지하게 편하다.

by cranix 2007. 6. 10. 01:07
분명 이클립스의 모든것을 UTF-8 로 셋팅했다고 생각했는데..

그래도 글씨가 깨져 나온다.

아래와 같이 해줘야지만 글씨가 깨지지 않는다.

new String(str.getBytes("8859_1"),"UTF-8");

어디에 또 설정이 있는것일까?

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

Spring 3.0 webmvc heloworld!!!  (31) 2010.09.29
Spring 에서 JUnit 로 테스트하기  (733) 2007.06.10
Spring 에서 MultiActionController 사용하기  (29) 2007.06.03
Spring 에서 properties 파일 다루기.  (33) 2007.06.01
Spring jsp 예외처리 전략  (20) 2007.05.30
by cranix 2007. 6. 9. 22:44

Controller 만 상속해서 사용하려니 Controller 가 너무 많아지는 경항이 있다..

이렇게되면 bean 설정도 많아지고 또 복잡해 지게된다.

이런걸 해결하기위해 MultiActionController 가 나왔다.

로직이 비교적간단한 것들을 모두 하나의 Controller 로 만드는건 귀찮은 작업이 아닐수 없다.

이럴땐 하나의 Controller 를 만들어서 MultiActionController 를 상속한다음 메소드별로 기능을 부여할수가 있다.

먼저 Controller 파일은 아래와같이 만든다.

[code]package dic.controllers;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

public abstract class DicSuperMultiActionController extends MultiActionController{
 public ModelAndView others(HttpServletRequest request, HttpServletResponse response) throws Exception {
  String contextPath = request.getContextPath();
  String uri = request.getRequestURI();
  String viewName = uri.substring(contextPath.length()+1,uri.lastIndexOf("."));

  return new ModelAndView(viewName);
 }
}[/code]


MultiActionController 는 abstract 메소드가 없기때문에 구현해야할 메소드가 없다.

대신 bean 설정에서 methodNameResolver 를 셋팅 해줘야 한다.

MultiActionController 의 최상위 클래스로 others 메소드만 구현하고 있다.

이 메소드는 MultiActionController 로 넘어왔는데 해당 메소드가 없으면 이쪽으로 맵핑되도록 한것이다.

다음으로 bean 설정이다.

[code] <bean id="dicSuperMultiActionController" class="dic.controllers.DicSuperMultiActionController" abstract="true"/>
 
 <bean id="adminAuthMultiActionController" class="dic.controllers.AdminAuthMultiActionController" parent="dicSuperMultiActionController">
  <property name="authDao" ref="authDao" />
  <property name="methodNameResolver">
   <ref local="adminAuthMultiActionControllerMethodNameResolver"/>
  </property>
 </bean>
 
 <bean id="adminAuthMultiActionControllerMethodNameResolver" class="org.springframework.web.servlet.mvc.multiaction.PropertiesMethodNameResolver">
  <property name="mappings">
   <props>
    <prop key="/**/*.do">others</prop>
    <prop key="/admin/auth/list.do">list</prop>
    <prop key="/admin/auth/modify.do">view</prop>
    <prop key="/admin/auth/modify_action.do">modify</prop>
    <prop key="/admin/auth/insert_action.do">insert</prop>
    <prop key="/admin/auth/delete_action.do">delete</prop>
   </props>
  </property>
 </bean>
 
 <bean id="urlMapping"
  class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
  <property name="mappings">
   <props>
    <prop key="/**/*.do">defaultController</prop>
    <prop key="/admin/login.do">adminLoginController</prop>
    <prop key="/admin/logout.do">adminLogoutController</prop>
    <prop key="/admin/auth/*.do">adminAuthMultiActionController</prop>
   </props>
  </property>
 </bean>[/code]


위와같이 Controller 자체에 PropertiesMethodNameResolver 를 셋팅해서 넘어오는 값에따라 메소드로 분기를 시켜줄수 있다.
오버로딩된 others 메소드를 위에서처럼 이용하면 Controller 가 지정되어있지 않은 요청은 알아서 others 로 가게 된다.

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

Spring 에서 JUnit 로 테스트하기  (733) 2007.06.10
이거 이해가 안된다.  (64) 2007.06.09
Spring 에서 properties 파일 다루기.  (33) 2007.06.01
Spring jsp 예외처리 전략  (20) 2007.05.30
Spring 의 exception 처리 전략  (26) 2007.05.29
by cranix 2007. 6. 3. 14:52

스프링에서 properties 파일을 다루기위해서는 두가지 클래스가 필요하다.

먼저 아래 bean 설정을 applicationContext.xml 파일에 넣어둔다.

- applicationContext.xml

[code] <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
  <property name="basename">
   <value>messages</value>
  </property>
 </bean>
 <bean id="messageSourceAccessor" class="org.springframework.context.support.MessageSourceAccessor">
  <constructor-arg>
   <ref local="messageSource"/>
  </constructor-arg>
 </bean>[/code]


이렇게 한후 위에 보이는 messages 부분이 파일명인데 classes 디렉토리에 위치하면 된다.

이제 properties 파일을 사용하고싶은 bean 에다가 messageSourceAccessor bean 을 넘겨주면 된다.

by cranix 2007. 6. 1. 03:25

Spring 의 bean 부분의 예외를 처리했다고 해도.

기본적으로 jsp 페이지 내에서 발생하는 예외는 spring 만으론 잡을수 없다.

그래서 아래와같은 방법을 썻다.

- web.xml

[code] <error-page>
  <exception-type>java.lang.Exception</exception-type>
  <location>/WEB-INF/jsp/error.jsp</location>
 </error-page>[/code]

- 위와같이 error.jsp 파일을 지정한다.

- error.jsp

[code]<%@page contentType="text/html;chraset=utf-8" isErrorPage="true"%>
<%=exception%>[/code]

- 여기서 중요한건 isErrorPage 속성을 true 로 했다는것이다.
- 이렇게 하면 request  에 "javax.servlet.error.exception"  라는 attribute 가 들어있으면 위와같이 그냥 exception 변수를 쓸수있게 된다.


- BaseExceptionResolver.java

[code]package dic.resolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

public class BaseExceptionResolver implements HandlerExceptionResolver {

 private String view = null;
 public void setView(String view) {
  this.view = view;
 }
 
 public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object obj, Exception exception) {
  exception.printStackTrace();
  request.setAttribute("javax.servlet.error.exception",exception);
  return new ModelAndView(view);
 }

}[/code]

- 위 파일은 예전에 bean 예외를 잡기위해 만들었던 파일인데 저기다가 위와같이 request 에 javax.servlet.error.exception 예외를 추가하면 jsp 의 errorpage 를 그대로 사용할수 있다.


자 이것으로 class 와 page 에서 나는 모든 에러를 한 페이지에서 잡을수 있게 되었다.

by cranix 2007. 5. 30. 11:38

Spring 에서 Exception 을 처리하기위해서는 두가지 방법이 있다.

첫번째는 아래와같이 SimpleMappingExceptionResolver 클래스를 사용하는 방법이다.

- springapp-servlet.xml

[code]    <bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
     <property name="exceptionMappings">
      <props>
       <prop key="java.lang.Exception">error</prop>
      </props>
     </property>
    </bean>[/code]


여기서 쓰인 error 는 viewResolver 에 의해 파싱되어서 가게 된다.

두번째 방법으로는 아래와같이 HandlerExceptionResolver  인터페이스를 직접 상속받아서Resolver 를 만들어 내는 방법이있다.

- BaseExceptionResolver.java

[code]package dic.resolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

public class BaseExceptionResolver implements HandlerExceptionResolver {

 private String view = null;
 public void setView(String view) {
  this.view = view;
 }
 
 public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object obj, Exception exception) {
  request.setAttribute("exception",exception);
  return new ModelAndView(view);
 }

}[/code]


위 파일의 bean 설정은 아래처럼 하면 된다.
- springapp-servlet.xml

[code]    <bean id="exceptionResolver" class="dic.resolver.BaseExceptionResolver">
     <property name="view" value="error"/>
    </bean>[/code]


- 이 방법을 쓰는이유는 request 로 exception 을 넘기기 위해서이다.

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

Spring 에서 properties 파일 다루기.  (33) 2007.06.01
Spring jsp 예외처리 전략  (20) 2007.05.30
클래스의 toString 및 equals 메소드 자동으로 만들어주기.  (47) 2007.05.26
기본 Controller 지정하기.  (23) 2007.05.24
SPRING  (25) 2007.02.28
by cranix 2007. 5. 29. 17:28
| 1 2 |