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

spring 이나 struts 같은 프레임웍은 jsp 의 처리를 컨트롤러에 위임하게 된다.

그래서 *.do 같은 형태의 url 로 접근 하도록 만들어 놓은건데.

좀 똑똑한 사용자가 jsp 파일의 경로를 알아서 컨트롤러를 거치지 않고

바로 jsp 에 접근하는게 가능하다.

이것을 막기위해 web.xml 에다가 아래 코드를 추가하면 된다.

[code]<security-constraint>
  <display-name>JSP Protection</display-name>
  <web-resource-collection>
   <web-resource-name>SecureJSPPages</web-resource-name>
   <url-pattern>*.jsp</url-pattern>
  </web-resource-collection>
  <auth-constraint>
   <role-name>nobody</role-name>
  </auth-constraint>
 </security-constraint>
 
 <security-role>
  <description>
  Nobody should be in this role so JSP files are protected
  from direct access.
  </description>
  <role-name>nobody</role-name>
 </security-role>[/code]

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

JSP 페이지를 열때마다 자동으로 캐시 지우기  (42) 2007.03.18
TOMCAT5.5 + MYSQL5.0 + JNDI 설정하기  (44) 2006.12.16
스트러츠 2.0  (92) 2006.12.16
by cranix 2007. 12. 12. 10:56

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

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

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

[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

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

예를들어 Bean 클래스를 만들었는데 toString 메소드를 만들어서 출력하게 하고싶다고 치자 어떻게 해야할까?

뭐 가장 쉬운 방법은 get 메소드를 하나하나 호출해서 붙혀서 알맞게 출력하는 방법이겠지만, 그게 답이라면 이글을 쓸필요도 없겠다.

정말 간단한 답이 있었다.
일단 아파치 자카르타 프로젝트의 Commons Lang 에서 제공하는 API 를 이용하여 메소드들을 쉽게 구현할수 있다.
이 라이브러리는 toString 말고도 equals,hashCode 도 쉽게 만드는 방법을 제공한다.

BaseObject 라는 클래스를 아래와같이 만들어서 모든 Bean 클래스에 적용해 주면된다.



- BaseObject.java

[code]package dic.model;

import java.io.Serializable;

import org.apache.commons.lang.builder.*;

@SuppressWarnings("serial")
public class BaseObject implements Serializable {
 public String toString() {
  return ToStringBuilder.reflectionToString(this,ToStringStyle.MULTI_LINE_STYLE);
 }
  public boolean equals(Object o) {
  return EqualsBuilder.reflectionEquals(this, o);
 }
 
 public int hashCode() {
  return HashCodeBuilder.reflectionHashCode(this);
 }
}[/code]

- Member.java

[code]package dic.model;

import java.util.Date;

import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionBindingListener;

import dic.member.MemberManager;

public class Member extends BaseObject implements HttpSessionBindingListener{
 private String id;
 private String password;
 private String name;
 private String auth_id_list;
 private String file_id_list;
 private Date reg_date;

 public String getId() {
  return id;
 }
 public void setId(String s) {
  id = s;
 }
 
 public String getPassword() {
  return password;
 }
 public void setPassword(String s) {
  password = s;
 }
 
 public String getName() {
  return name;
 }
 public void setName(String s) {
  name = s;
 }
 
 public String getAuthIdList() {
  return auth_id_list;
 }
 public void setAuthIdList(String s) {
  auth_id_list = s;
 }
 
 public String getFileIdList() {
  return file_id_list;
 }
 public void setFileIdList(String s) {
  file_id_list = s;
 }
 
 public Date getRegDate() {
  return reg_date;
 }
 public void setRegDate(Date d) {
  reg_date = d;
 }
 
 // 세션에 입력될때
 public void valueBound(HttpSessionBindingEvent event) {
  MemberManager.getInstance().doLogin(this);
 }
 // 세션에서 제거될때
 public void valueUnbound(HttpSessionBindingEvent event) {
  MemberManager.getInstance().doLogout(this);
 }
 
 public static void main(String args[]) {
  Member m = new Member();
  m.setId("cranix");
  m.setPassword("1234");
  m.setName("크래닉스");
  System.out.println(m);
 }
}[/code]


 - 실행결과

dic.model.Member@8813f2[
  id=cranix
  password=1234
  name=크래닉스
  auth_id_list=<null>
  file_id_list=<null>
  reg_date=<null>
]


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

Spring jsp 예외처리 전략  (20) 2007.05.30
Spring 의 exception 처리 전략  (26) 2007.05.29
기본 Controller 지정하기.  (23) 2007.05.24
SPRING  (25) 2007.02.28
JSTL 사용하기  (28) 2007.02.28
by cranix 2007. 5. 26. 01:10
| 1 2 |