프로그래밍 2017. 2. 21. 00:59


Request 정보 처리를 위한 설정


사용자가 공지사항 등록화면에서 입력한 정보와 첨부파일 정보를 저장할 테이블을 생성하고 DB연동을 위한 Datasource 설정, Mybatis연동 설정, Transaction설정, 파일처리를 위한 multipartResolver 설정을 차례대로 설명하겠습니다.


1. Database 테이블 생성


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
/*
    공지사항 정보 저장
*/
CREATE TABLE SCOTT.TB_NOTICE(
NOTICE_ID       NUMBER(10),
NOTICE_TITLE    VARCHAR2(200),
NOTICE_CONTENT  VARCHAR2(4000),
DEL_YN          CHAR(1)
)
TABLESPACE USERS
STORAGE
(
    INITIAL 64K
    NEXT 1M
)
NOCOMPRESS;
 
/*
    공지사항 첨부파일 정보 저장
*/
CREATE TABLE SCOTT.TB_ATT_FILE(
NOTICE_ID           NUMBER(10),
FILE_ID             NUMBER(3),
ATT_FILE_SAVE_NM    VARCHAR2(200),
ATT_FILE_NM         VARCHAR2(4000),
ATT_FILE_SIZE       NUMBER(10),
DEL_YN              CHAR(1)
)
TABLESPACE USERS
STORAGE
(
    INITIAL 64K
    NEXT 1M
)
NOCOMPRESS;
 
ALTER TABLE SCOTT.TB_NOTICE
ADD CONSTRAINT PK_TB_NOTICE PRIMARY KEY (NOTICE_ID);
 
ALTER TABLE SCOTT.TB_ATT_FILE
ADD CONSTRAINT PK_TB_ATT_FILE PRIMARY KEY (NOTICE_ID, FILE_ID);
 
ALTER TABLE SCOTT.TB_ATT_FILE
ADD CONSTRAINT FK_TB_ATT_FILE FOREIGN KEY (NOTICE_ID) REFERENCES SCOTT.TB_NOTICE (NOTICE_ID);
cs



2. Datasource 및 Transaction 설정

 - root-context.xml 파일을 참조하여 네임스페이스와 설정 정보를 추가합니다.

 - oracle Driver를 찾지 못하는 error가 발생하면, 오라클 설치 폴더에서 ojdbc를 찾아 JAVA를 설치한 곳으로 복사하면 error가 해결됩니다.

=> 오라클홈 -> jdbc -> lib -> ojdbc6.jar 파일을

=> 자바설치폴더 -> jre -> lib -> ext 폴더로 복사


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
<?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:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
                        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
                        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
                        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">
    
    <!--  
        @Service, @Repository 스트레오타입 어노테이션이 선언된 클래스를 빈으로 등록한다.
    -->
     <context:component-scan base-package="com.devdic.board">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Service"/>
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Repository"/>
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
    
    <context:annotation-config/>
    
    <!-- 
    datasource 설정에 필요한 라이브러리 추가를 위해 아래의 내용을 pom.xml에 추가필요
    <dependency>
        <groupId>commons-dbcp</groupId>
        <artifactId>commons-dbcp</artifactId>
        <version>1.3</version>
    </dependency>
    -->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/>
        <property name="url" value="jdbc:oracle:thin@127.0.0.1:1521:orcl" />
        <property name="username" value="SCOTT"/>
        <property name="password" value="SCOTT"/>
    </bean>
    
    <!-- Transaction 설정 -->
    <!-- 
    Transaction 설정에 필요한 라이브러리 추가를 위해 아래의 내용을 pom.xml에 추가
    <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>${org.springframework-version}</version>
    </dependency>  
     -->
     <!-- dataSource를 활용하는 트랜잭션 매니저를 등록 -->
     <!-- dataSource 빈을 DataSourceTransactionManager 트랜잭션 매니저의 dataSource 속성에 지정  -->
    <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
    
    <!-- AOP advisor 를 활용하여 트랜잭션을 처리함
        아래의 dependency를 pom.xml에 추가 
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.8.9</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
            <version>1.8.9</version>
        </dependency>
    -->
     <tx:advice id="txAdvice" transaction-manager="txManager">
       <tx:attributes>
       <!--
            모든 메소드에 대해서 트랜잭션을 REQUIRED 으로 지정하고
            Exception 발생 시 롤백 지정
        -->
       <tx:method name="*" propagation="REQUIRED" rollback-for="Exception"/>
       </tx:attributes>
    </tx:advice>
    <!-- 
    com.devdic.board 아래의 클래스 명이 ~~~ServiceImpl로 끝나는
    클래스 내의 모든 메소드는 트랜재션 처리가 된다.
     -->
    <aop:config><!-- execution(* *..service.impl.*ServiceImpl.*(..)) -->
        <aop:pointcut id="requiredTx" expression="execution(* com.devdic.board..*ServiceImpl.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="requiredTx" />
    </aop:config>
cs


3. myBatis 연동

 3.1  root-context.xml에 아래의 myBatis 연동 설정 정보 추가


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<!--  Mybatis 연동
    pom.xml 추가
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.4.1</version>
    </dependency>
    
    마이바티스 스프링 연동 모듈
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis-spring</artifactId>
        <version>1.3.0</version>
    </dependency>
    -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <!-- mybatis config파일 경로 지정 -->
        <property name="configLocation" value="/WEB-INF/config/mybatis-config.xml"/>
        
        <!-- SQL(mapper) 경로 지정 -->
        <property name="mapperLocations" value="classpath:sqlMap/**/*.xml"/>
    </bean>
    
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
          <constructor-arg ref="sqlSessionFactory" />
    </bean>
cs


3.2 WEB-INF -> config(폴더생성) -> mybatis-config.xml(파일 추가)

 - mybatis-config.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.2//EN" "HTTP://mybatis.org/dtd/mybatis-3-config.dtd">
 
<configuration>
    <settings>
        <setting name="cacheEnabled" value="false" />
        <setting name="useGeneratedKeys" value="true" />
        <setting name="defaultExecutorType" value="BATCH" />
        <setting name="jdbcTypeForNull" value="NULL" />
        <setting name="callSettersOnNulls" value="true" />
    </settings>
 
    <typeAliases>
        <typeAlias type="java.util.Map" alias="map"/>
    </typeAliases>
 
    <mappers>
    </mappers>
</configuration>
cs



4. 첨부파일 처리를 위한 multipartResolver 설정
  - root-context.xml 파일에 아래와 같이 추가합니다.
  - dependency 추가를 위한 정보는 주석부분을 참조하세요!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
    <!-- MultipartResolver -->
    <!-- 
        <dependency>
            <groupId>commons-fileupload</groupId>
                <artifactId>commons-fileupload</artifactId>
            <version>1.3.1</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.4</version>
        </dependency>
     -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">   
<property name="maxUploadSize" value="50000000"></property>
    </bean>
 
cs


posted by 생각퍼즐
:
프로그래밍 2017. 2. 15. 00:07

스프링 환경설정


바로 코딩을 시작할 줄 알았는데...

또 환경설정을 해야되냐구요?

지금까지는 개발을 위한 환경구성에 초점이 맞춰졌다면, 이제는 웹과 스프링 프레임워크 사용을 위한 기본 설정파일에 대한 설정과 설명을 하고 개발로 넘어가야 할 것 같아서... 몇 가지 준비했습니다.


web.xml [배포 서술자 : (DD, Deployment Descriptor)]

웹 애플리케이션의 기본적인 설정을 기술하는 파일입니다.

기본적인 설정이라 함은 filter, listener, servlet, session 등을 설정하는 것입니다.


web.xml 설정과 설명


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
 
 
    <!-- 웹 애플리케이션 이름 정의 -->
    <display-name>myapp</display-name>
    
    <!-- filter 설정 추가 -->
    <!-- filter : Client와 Servlet Containder 사이에서 HTTP 요청/응답을 변경할 수 있는 재사용 코드 -->
    <filter>
        <filter-name>encodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>utf-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    
    <!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
    <!-- ContextLoaderListener가 사용할 설정파일 위치 변경 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring/root-context.xml</param-value>
    </context-param>
    
    <!-- Creates the Spring Container shared by all Servlets and Filters -->
    <!-- listener 설정 -->
    <!-- listener : 루트 웹 애플리케이션 컨텍스트를 등록할 때 사용
                    웹 애플리케이션의 시작과 종료 시 발생하는 이벤트를 처리하는 listener인
                    ServletContextListener를 구현한 ContextLoaderListener가 웹 애플리케이션이
                    시작될 때 root application context를 생성 및 초기화하고,
                    웹 애플리케이션이 종료될 때 context를 종료하는 기능을 담당한다.  -->
                    
    <!-- 별다른 설정을 하지 않고 아래처럼 listener를 정의하면 /WEB-INF/applicationContext.xml 파일을
         디폴트 설정파일로 사용한다.
         설정파일의 위치는 <context-param> 항목을 이용해 변경할 수 있다.
         위의 <context-param> 항목을 참조!  -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
 
    <!-- Processes application requests -->
    <!-- 서블릿 설정과 서블릿 애플리케이션 컨텍스트 등록 -->
    <!-- DispatcherServlet이 초기화될 때 자신만의 컨텍스트를 생성 및 초기화한다.
         그리고 웹 애플리케이션 레벨에 등록된 루트 웹 애플리케이션 컨텍스트를 찾아서
         자신의 부모 컨텍스트로 사용한다. -->
    <servlet>
        <servlet-name>appServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!-- DispatcherServlet의 컨텍스트에 대한 디폴트 설정을 변경하고 싶다면
             아래와 같이 contextConfigLocation을 정의하여 경로를 설정하면 된다. -->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
        
    <servlet-mapping>
        <servlet-name>appServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
 
</web-app>
 
cs



servelt-context.xml 설정과 설명(child context)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:beans="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc 
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
 
    <!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
    
    <!-- Enables the Spring MVC @Controller programming model -->
     
     <!-- 
     1. RequestMappingHandlerMapping bean등록(기존 DefaultAnnotationHandlerMapping)
     2. RequestMappingHandlerAdapter bean등록(기존 AnnotationMethodHandlerAdapter) : customArgumentResolvers, customReturnValueHandlers 추가 가능
     3. JSR-303의 검증용 어노테이션(@Valid)를 사용할 수 있도록 LocalValidatorFactoryBean bean설정 (JSR-303지원 라이브러리 존재 시)
     4. RequestMappingHandlerAdapter의 messageConverters프로퍼티로 메시지 컨버터들 등록
     주의사항
     <mvc:annotation-driven>을 사용할 때는 직접 RequestMappingHandlerAdapter를 등록해주어서는 안되며 직접 등록이 필요한 경우에는 
     <mvc:annotation-driven>을 설정하지 않고 각각의 필요한 설정을 수동으로 해주어야 한다.
     -->
     <annotation-driven />
    
    <!-- @Controller, @Repository, @Service, @Component 스트레오타입 어노테이션이 선언된 클래스를 빈으로 등록한다. -->
     <context:component-scan base-package="com.devdic.board"/>
 
 
    <!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
    <resources mapping="/resources/**" location="/resources/" />
 
    <!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
    <!-- 
    InternalResourceViewResolver는 웹 어플리케이션 컨텍스트에 존재하는 템플릿에게 랜더링에 대한 책임을 위임하는
    View 객체를 논리적인 View 이름을 사용하여 결정한다.
    View 객체는 기본적으로 InternalResourceViewResolver이며, 이 객체는 실제 랜더링을 수행할 JSP에 단순히 요청을 전달하는 일을 한다.
    만약 JSTL 태그를 사용한다면 viewClass 특성을 설정함으로써 InternalResourceView를 JstlView로 대체하여 JstlView 요청을 JSP에 전달한다.
     -->
    <beans:bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <beans:property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
    
    <!-- JSP파일 경로와 접미어 설정 -->
    <beans:property name="prefix" value="/WEB-INF/views/"/>
    <beans:property name="suffix" value=".jsp" />
    </beans:bean>
    
</beans:beans>
 
cs


root-context.xml 설정과 설명(parent context)

<context~> 항목을 사용하기 위해 네임스페이스를 추가하셔야 합니다.

아래코드에서 굵은 글씨로 된 부분을 추가하시면 됩니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<?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:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
    
    <!--  
        @Service, @Repository 스트레오타입 어노테이션이 선언된 클래스를 빈으로 등록한다.
    -->
     <context:component-scan base-package="com.devdic.board">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Service"/>
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Repository"/>
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
    
    <context:annotation-config/>
    
</beans>
cs


기본적인 설정은 어느정도 된것 같습니다.

DB연결을 위한 datasource, JDBC를 좀 더 쉽게 사용하기 위한 Mybatis연동, 논리적 작업단위의 Transaction 설정 등 몇가지가 남았지만...

잠시 뒤로 미루어두고 공지사항 등록 화면을 만들어보죠~~~

 

posted by 생각퍼즐
: