스프링 >>> 스트럿츠2

Spring 2009. 1. 22. 01:44

오늘도 또 봤지요... 스프링 인 액션2 책을 구해서 봤는데 약간 이해가 되다가도 예제가 그지같군요..(예제가 단적이지 않고 통합되어 있어서 소스를 분석해야함)

그래도 오기로.. 신상철박사님의 사이트에서 예제를 다운받아 실행이라도 되게끔 세팅해 보았습니다. 중간에 오류도 많았구여.
SimpleFormController로 컨트롤러를 구현한 예제였습니다.
차분히 컨트롤러 파일부터 한줄한줄 분석해 보았습니다.
아주 조금씩 이해가 되갈라 카네여..
작년에 스트럿츠2로 만들던 웹게임소스가 있어서 봤는데... 헐.. 로직이 쉽고 설정파일의 가독성이 이렇게나 아름다울수가!!!
스트럿츠2에 새삼 감사했지만, 강력함은 스프링에 못 미칩니다. 스트럿츠2는 단조롭죠.. 물론 더 알아봐야 겠지만요./

컨트롤러
package springexample.controller;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
import springexample.commands.AccountDetail;
import springexample.commands.LoginCommand;
import springexample.services.AccountServices;
import springexample.services.AuthenticationService;
/**
 * SimpleFormController is a concrete FormController implementation that
 * provides configurable form and success views, and an onSubmit chain for
 * convenient overriding. Automatically resubmits to the form view in case
 * of validation errors, and renders the success view in case of a valid
 * submission.
 */
public class LoginBankController extends SimpleFormController {
    public LoginBankController() {
    }
    // The submit behavior can be customized by overriding one of the onSubmit methods. 오버라이딩 필수
    protected ModelAndView onSubmit(Object command) throws Exception {
        LoginCommand loginCommand = (LoginCommand) command; //오브젝트의 커맨드객체를 형변환시킨다.커맨드에는 폼에서 전달한 아뒤와 패스워드 정보가 담겨있다.
        authenticationService.authenticate(loginCommand); //로그인인증.. 아작스처리가 낫지 않을까?
        AccountDetail accountdetail = accountServices.getAccountSummary(loginCommand.getUserId());//커맨드를통해정보를담자..머이리 복잡한것인가!!
        return new ModelAndView(getSuccessView(), "accountdetail", accountdetail);
    }
   
    //어디서 많이 본듯한 장면아닌가..스트럿츠2의 액션인가?? 겟셋..
    private AuthenticationService authenticationService;
    private AccountServices accountServices;
    public AccountServices getAccountServices() {
        return accountServices;
    }
    //sampleBankingServlet-servlet.xml에서  <property name="accountServices">로 설정해 객체를 넘겼다.
    //해당객체를 주입하여 인자로 넘겨줌으로써 위에서 선언한 객체변수들을 쓸 수 있는 것이다.
    public void setAccountServices(AccountServices accountServices) {
        this.accountServices = accountServices;
    }
    public AuthenticationService getAuthenticationService() {
        return authenticationService;
    }
    public void setAuthenticationService(
            AuthenticationService authenticationService) {
        this.authenticationService = authenticationService;
    }
}

패키지는 controller , services , commands로 나뉜다..
controller : 말그대로 컨트롤러 클래스 위치
commands : User ,  Account , Login 등 빈즈 위치
services : 비즈니스 로직이 구현된 클래스 위치.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
   
    <bean id="simpleUrlMapping"
          class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
        <property name="mappings">
            <props>
                <prop key="/login.html">loginBankController</prop>
            </props>
        </property>
    </bean>
   
    <bean id="logonValidator" class="springexample.commands.LogonValidator"/>
   
    <!-- LoginBankController is a SimpleFormController -->
    <bean id="loginBankController"
          class="springexample.controller.LoginBankController">
 <!--AbstractFormController에 sessionForm()가 정의되어있어 사용가능하다        -->
        <property name="sessionForm">
            <value>true</value>
        </property>
       
        <!-- This is Command object.  The command object can be
             accessed in a view through <spring:bind path="loginCommand"> -->
 <!--커맨드명설정 BaseCommandController클래스에 commandName()메소드가 정의되어있다            -->
        <property name="commandName">
            <value>loginCommand</value>
        </property>
 <!--커맨드클래스로 LoginCommand클래스 사용. 파라미터타입은 class타입 -->
        <property name="commandClass">
            <value>springexample.commands.LoginCommand</value>
        </property>
 <!-- BaseCommandController에 setValidator()메소드가 정의되어있다.        -->
        <property name="validator">
            <ref bean="logonValidator"/>
        </property>
       
        <!-- Indicates what view to use when the user asks for a new form
             or when validation errors have occurred on form submission. -->
 <!--SimpleFormController클래스에 setFormView()메소드 정의되어있다. 인자로넘긴 login은 login.jsp로 연결 
      결국 onSubmit()에서 에러가 나면 폼입력화면..또는 처음요청은 GET방식이니까 폼입력으로..  -->
        <property name="formView">
            <value>login</value>
        </property>
       
        <!-- Indicates what view to use when successful form submissions
             have occurred. Such a success view could e.g. display a submission
             summary. More sophisticated actions can be implemented by
             overriding one of the onSubmit() methods.-->
 <!-- onSubmit()이 성공하면 getSuccessView()를 리턴하는데 여기서 setSuccessView를 세팅해준다.
   accountdetail.jsp로 가는거다.        -->
        <property name="successView">
            <value>accountdetail</value>
        </property>
       
        <property name="authenticationService">
            <ref bean="authenticationService" />
        </property>
        <property name="accountServices">
            <ref bean="accountServices" />
        </property>
       
    </bean>
 <!--뷰리졸버 세팅    -->
    <bean id="viewResolver"
          class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass">
            <value>org.springframework.web.servlet.view.JstlView</value>
        </property>
        <property name="prefix">
            <value>/WEB-INF/jsp/</value>
        </property>
        <property name="suffix">
            <value>.jsp</value>
        </property>
    </bean>
   
</beans>


AND