영보의 SystemOut.log

[Spring] Spring AOP(스프링 AOP) 개념과 예제 본문

Spring

[Spring] Spring AOP(스프링 AOP) 개념과 예제

영보로그 2020. 11. 17. 13:51
반응형

 개념

 

# 개요

스프링
   - 공통 모듈 → 공통 관심사 → SPRING(AOP) - Callback함수 (시스템에 의해 자동 호출)

   - 핵심 모듈 → 핵심 관심사 → 프로그래머가코딩

   - 반복을 제거하는 프로그램 AOP( 트랜잭션, 로그파일, 보안)

프로젝트 순서


   1. 프로젝트 생성 

      프로젝트 명 → 패키지 설정 (3개이상)

   2. 자바 버전 변경

    2-2. pom.xml (라이브러리 추가)

         라이브러리가 없는 경우 : mvnrepository.com 검색 후 추가

   3. web.xml 변경

   4. application-context.xml 설정

   5. 자바(Model, DAO, VO) => html

 

 

 

# AOP(Aspect Oriented Programming)  → 공통 기능 삽입

개념


   - 여러 객체에 공통으로 적용할 수 있는 기능을 분리해서 재사용성을 높여주는 프로그래밍 기법

   - 핵심기능과 공통 기능의 구현을 분리함으로써 핵심 기능을 구현한 코드의 수정 없이 공통 기능을 적용할 수 있게 만들어줌

   

주요 용어  
  - Aspect : 공통기능
  - Advice : Aspect의 기능 자체
  - Joinpoing : Advice를 적용해야 되는 부분(method)
  - Pointcut : Joinpoint의 부분으로 실제로 Advice가 적용된 부분
  - Weaving : Advice를 핵심 기능에 적용하는 행위


구현 방법

    스프링에서는 proxy로 구현함 

 

 

 

# Aspect 실행 시점 지정 어노테이션

@Before(이전)
   Advice 타겟 메소드가 호출되기 전에 Advice기능을 수행 

@After(이후)
   타겟 메소드의 결과에 관계없이 (성공/예외) 타겟 메소드가 완료 되면 어드바이스 기능을 수행

@AfterReturning
(정상적 반환 이후)

  타겟 메소드가 성공적으로 결과값을 반환 후에 Advice 기능을 수행

@AfterThrowing
(예외 발생 이후)

   타겟 메소드가 수행 중 예외를 던지게 되면 Advice 기능을 수행

@Around
(메소드 실행 전후)

    Advice 타겟 메소드를 감싸서 타겟 메소드 호출전과 후에 Advice기능을 수행

 

 

 

 

 # pom.xml 유효성 검사 코드 추가하기

     @AOP 를 사용하기 위해서 반드시 다음과 같은 의존성을 추가시켜야함.

1
2
3
4
5
6
7
8
9
10
11
12
<!--유효성검사-->
<dependency>
    <groupId>javax.validation</groupId>
    <artifactId>validation-api</artifactId>
    <version>2.0.1.Final</version>
</dependency>
 
<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>6.1.6.Final</version>
</dependency>
cs

mvnrepository.com/artifact/org.hibernate/hibernate-validator/6.1.6.Final 

 

Maven Repository: org.hibernate » hibernate-validator » 6.1.6.Final

Hibernate Validator Engine Relocation Artifact Note: There is a new version for this artifact org.hibernate hibernate-validator 6.1.6.Final // https://mvnrepository.com/artifact/org.hibernate/hibernate-validator compile group: 'org.hibernate', name: 'hiber

mvnrepository.com

mvnrepository.com/artifact/javax.validation/validation-api/2.0.1.Final

 

Maven Repository: javax.validation » validation-api » 2.0.1.Final

javax.validation validation-api 2.0.1.Final // https://mvnrepository.com/artifact/javax.validation/validation-api compile group: 'javax.validation', name: 'validation-api', version: '2.0.1.Final' // https://mvnrepository.com/artifact/javax.validation/valid

mvnrepository.com

  - 코드는 위 링크에서 가져왔습니다

 

 

 

 

 

 예제

 

# pom.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
<?xml version="1.0" encoding="UTF-8"?>
<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 https://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.sist</groupId>
    <artifactId>web</artifactId>
    <name>SpringAOPProject1</name>
    <packaging>war</packaging>
    <version>1.0.0-BUILD-SNAPSHOT</version>
    <properties>
        <!-- Spring 5 -->
        <java-version>1.8</java-version>
        <org.springframework-version>5.1.5.RELEASE</org.springframework-version>
        <org.aspectj-version>1.6.10</org.aspectj-version>
        <org.slf4j-version>1.6.6</org.slf4j-version>
    </properties>
    <repositories>
        <repository>
            <id>mesir-repo</id>
            <url>http://mesir.googlecode.com/svn/trunk/mavenrepo</url>
        </repository>
    </repositories>
    <dependencies>
        <!-- Spring -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${org.springframework-version}</version>
            <exclusions>
                <!-- Exclude Commons Logging in favor of SLF4j -->
                <exclusion>
                    <groupId>commons-logging</groupId>
                    <artifactId>commons-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${org.springframework-version}</version>
        </dependency>
        <!-- Jsoup -->
        <dependency>
            <groupId>org.jsoup</groupId>
            <artifactId>jsoup</artifactId>
            <version>1.12.1</version>
        </dependency>
        <!-- JSON -->
        <dependency>
            <groupId>org.jsoup</groupId>
            <artifactId>jsoup</artifactId>
            <version>1.13.1</version>
        </dependency>
        <!-- JAXB -->
        <dependency>
            <groupId>javax.xml.bind</groupId>
            <artifactId>jaxb-api</artifactId>
            <version>2.3.1</version>
        </dependency>
        <!-- AspectJ -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>5.1.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.1.5.RELEASE</version>
        </dependency>
        <!-- lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.8</version>
            <scope>provided</scope>
        </dependency>
        <!-- websocket -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-websocket</artifactId>
            <version>5.1.5.RELEASE</version>
        </dependency>
 
        <!-- <dependency> <groupId>org.springframework</groupId> <artifactId>spring-expression</artifactId> 
            <version>5.1.5.RELEASE</version> </dependency> -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.1.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-instrument</artifactId>
            <version>5.1.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>5.1.5.RELEASE</version>
        </dependency>
        <!-- <dependency> <groupId>com.oracle</groupId> <artifactId>ojdbc14</artifactId> 
            <version>10.2.0.4.0</version> </dependency> -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jms</artifactId>
            <version>5.1.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>5.1.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-oxm</artifactId>
            <version>5.1.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.1.5.RELEASE</version>
        </dependency>
        <!-- <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc-portlet</artifactId> 
            <version>5.1.5.RELEASE</version> </dependency> -->
 
        <dependency>
            <groupId>taglibs</groupId>
            <artifactId>standard</artifactId>
            <version>1.1.2</version>
        </dependency>
 
        <dependency>
            <groupId>org.nuiton.thirdparty</groupId>
            <artifactId>Rserve</artifactId>
            <version>1.7-3</version>
        </dependency>
        <dependency>
            <groupId>org.nuiton.thirdparty</groupId>
            <artifactId>REngine</artifactId>
            <version>1.7-3</version>
        </dependency>
        <!-- @Select("<script>SELECT~~ <if test="">") -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.2.8</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.2.0</version>
        </dependency>
        <dependency>
            <groupId>org.mongodb</groupId>
            <artifactId>mongo-java-driver</artifactId>
            <version>2.13.0-rc1</version>
        </dependency>
        <dependency>
            <groupId>org.nuiton.thirdparty</groupId>
            <artifactId>JRI</artifactId>
            <version>0.9-6</version>
        </dependency>
        <dependency>
            <groupId>com.github.lucarosellini.rJava</groupId>
            <artifactId>JRIEngine</artifactId>
            <version>0.9-7</version>
        </dependency>
        <dependency>
            <groupId>aopalliance</groupId>
            <artifactId>aopalliance</artifactId>
            <version>1.0</version>
        </dependency>
        <dependency>
            <groupId>asm</groupId>
            <artifactId>asm</artifactId>
            <version>3.3.1</version>
        </dependency>
        <dependency>
            <groupId>c3p0</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.1.2</version>
        </dependency>
        <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib</artifactId>
            <version>3.1</version>
        </dependency>
        <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib-nodep</artifactId>
            <version>3.1</version>
        </dependency>
        <dependency>
            <groupId>commons-collections</groupId>
            <artifactId>commons-collections</artifactId>
            <version>3.2.1</version>
        </dependency>
        <dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
            <version>1.4</version>
        </dependency>
        <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>
        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>commons-pool</groupId>
            <artifactId>commons-pool</artifactId>
            <version>1.6</version>
        </dependency>
        <dependency>
            <groupId>org.javassist</groupId>
            <artifactId>javassist</artifactId>
            <version>3.18.2-GA</version>
        </dependency>
 
        <dependency>
            <groupId>org.nuiton.thirdparty</groupId>
            <artifactId>Rserve</artifactId>
            <version>1.7-3</version>
        </dependency>
        <dependency>
            <groupId>org.nuiton.thirdparty</groupId>
            <artifactId>REngine</artifactId>
            <version>1.7-3</version>
        </dependency>
        <dependency>
            <groupId>org.twitter4j</groupId>
            <artifactId>twitter4j-core</artifactId>
            <version>4.0.2</version>
        </dependency>
        <dependency>
            <groupId>org.twitter4j</groupId>
            <artifactId>twitter4j-stream</artifactId>
            <version>4.0.2</version>
        </dependency>
        <dependency>
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
            <version>1.1.0.Final</version>
        </dependency>
        <!-- <dependency> <groupId>com.oracle</groupId> <artifactId>ojdbc14</artifactId> 
            <version>10.2.0.4.0</version> </dependency> -->
 
        <!-- End -->
        <!-- AspectJ -->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
            <version>${org.aspectj-version}</version>
        </dependency>
        <!-- AOP -->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.6.5</version>
        </dependency>
        <!-- AOP -->
        <dependency>
            <groupId>aopalliance</groupId>
            <artifactId>aopalliance</artifactId>
            <version>1.0</version>
        </dependency>
        <!-- AOP -->
        <dependency>
            <groupId>asm</groupId>
            <artifactId>asm</artifactId>
            <version>3.1</version>
        </dependency>
        <!-- tiles -->
        <dependency>
            <groupId>org.apache.tiles</groupId>
            <artifactId>tiles-core</artifactId>
            <version>3.0.8</version>
        </dependency>
        <dependency>
            <groupId>org.apache.tiles</groupId>
            <artifactId>tiles-jsp</artifactId>
            <version>3.0.8</version>
        </dependency>
        <dependency>
            <groupId>org.apache.tiles</groupId>
            <artifactId>tiles-api</artifactId>
            <version>3.0.8</version>
        </dependency>
 
        <dependency>
            <groupId>org.apache.tiles</groupId>
            <artifactId>tiles-servlet</artifactId>
            <version>3.0.8</version>
        </dependency>
 
        <dependency>
            <groupId>commons-beanutils</groupId>
            <artifactId>commons-beanutils</artifactId>
            <version>1.9.2</version>
        </dependency>
 
        <dependency>
            <groupId>commons-digester</groupId>
            <artifactId>commons-digester</artifactId>
            <version>2.1</version>
        </dependency>
 
        <dependency>
            <groupId>org.antlr</groupId>
            <artifactId>antlr-runtime</artifactId>
            <version>3.5.2</version>
        </dependency>
        <!-- XML -->
        <dependency>
            <groupId>com.sun.xml.bind</groupId>
            <artifactId>jaxb-core</artifactId>
            <version>2.2.11</version>
        </dependency>
        <dependency>
            <groupId>com.sun.xml.bind</groupId>
            <artifactId>jaxb-impl</artifactId>
            <version>2.2.11</version>
        </dependency>
 
        <dependency>
            <groupId>javax.xml.bind</groupId>
            <artifactId>jaxb-api</artifactId>
            <version>2.2.11</version>
        </dependency>
 
        <!--유효성검사 -->
        <dependency>
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
            <version>2.0.1.Final</version>
        </dependency>
 
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>6.1.6.Final</version>
        </dependency>
 
        <!-- jaxb-core jaxb-impl jaxb-api json-simple commons-lang ezmorph -->
        <!-- JSON -->
        <dependency>
            <groupId>com.googlecode.json-simple</groupId>
            <artifactId>json-simple</artifactId>
            <version>1.1.1</version>
        </dependency>
        <dependency>
            <groupId>commons-lang</groupId>
            <artifactId>commons-lang</artifactId>
            <version>2.6</version>
        </dependency>
        <dependency>
            <groupId>net.sf.ezmorph</groupId>
            <artifactId>ezmorph</artifactId>
            <version>1.0.6</version>
        </dependency>
 
        <!-- Logging -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>${org.slf4j-version}</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>jcl-over-slf4j</artifactId>
            <version>${org.slf4j-version}</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>${org.slf4j-version}</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.15</version>
            <exclusions>
                <exclusion>
                    <groupId>javax.mail</groupId>
                    <artifactId>mail</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>javax.jms</groupId>
                    <artifactId>jms</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>com.sun.jdmk</groupId>
                    <artifactId>jmxtools</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>com.sun.jmx</groupId>
                    <artifactId>jmxri</artifactId>
                </exclusion>
            </exclusions>
            <scope>runtime</scope>
        </dependency>
 
        <!-- @Inject -->
        <dependency>
            <groupId>javax.inject</groupId>
            <artifactId>javax.inject</artifactId>
            <version>1</version>
        </dependency>
 
        <!-- Servlet -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.1</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
 
        <!-- Test -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.7</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
 
    <build>
        <plugins>
            <plugin>
                <artifactId>maven-eclipse-plugin</artifactId>
                <version>2.9</version>
                <configuration>
                    <additionalProjectnatures>
                        <projectnature>org.springframework.ide.eclipse.core.springnature</projectnature>
                    </additionalProjectnatures>
                    <additionalBuildcommands>
                        <buildcommand>org.springframework.ide.eclipse.core.springbuilder</buildcommand>
                    </additionalBuildcommands>
                    <downloadSources>true</downloadSources>
                    <downloadJavadocs>true</downloadJavadocs>
                </configuration>
            </plugin>
            <plugin>
                <!-- Spring 5 -->
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.7.0</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <compilerArgument>-Xlint:all</compilerArgument>
                    <showWarnings>true</showWarnings>
                    <showDeprecation>true</showDeprecation>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>exec-maven-plugin</artifactId>
                <version>1.2.1</version>
                <configuration>
                    <mainClass>org.test.int1.Main</mainClass>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>
cs

  - 위의 유효성 검사 코드를 추가했습니다.

 

 

 

# 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
<?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 https://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
 
     <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <!-- XML파일이 여러개를 사용할 때 -->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/config/application-*.xml</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>
    <!-- 한글 변환 ( request를 사용하지 않는다 ) -->
    <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>
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
 
    <!-- /의 형식으로 시작하는 url에 대하여 UTF-8로 인코딩 -->
    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>
cs

 

 

 

# EmpVO.java

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
package com.sist.dao;
import java.util.*;
public class EmpVO {
    private int empno;
    private String ename;
    private String job;
    private Date hiredate;
    private int sal;
    private String dname;
    private String loc;
    public int getEmpno() {
        return empno;
    }
    public void setEmpno(int empno) {
        this.empno = empno;
    }
    public String getEname() {
        return ename;
    }
    public void setEname(String ename) {
        this.ename = ename;
    }
    public String getJob() {
        return job;
    }
    public void setJob(String job) {
        this.job = job;
    }
    public Date getHiredate() {
        return hiredate;
    }
    public void setHiredate(Date hiredate) {
        this.hiredate = hiredate;
    }
    public int getSal() {
        return sal;
    }
    public void setSal(int sal) {
        this.sal = sal;
    }
    public String getDname() {
        return dname;
    }
    public void setDname(String dname) {
        this.dname = dname;
    }
    public String getLoc() {
        return loc;
    }
    public void setLoc(String loc) {
        this.loc = loc;
    }
       
}
 
cs

 

 

 

# EmpDAO.java

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
83
84
85
86
87
88
89
90
91
92
93
package com.sist.dao;
 
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
 
@Repository
public class EmpDAO {
    @Autowired
    private DBConnection dbConn;
    private Connection conn;
    private PreparedStatement ps;
    public EmpDAO()
    {
        
    }
    public List<EmpVO> empListData()
       {
           //conn=dbConn.getConn();
           List<EmpVO> list=new ArrayList<EmpVO>();
           // @Before
           try
           {
               // @Around => 실행 전 => setAutoCommit(false)
               // 핵심 코딩(DML)
               // 실행 후 => commit
               
               String sql="SELECT empno,ename,job,hiredate,sal,"
                         +"(SELECT dname FROM dept d WHERE d.deptno=e.deptno) as dname,"
                         +"(SELECT loc FROM dept d WHERE d.deptno=e.deptno) as loc "
                         +"FROM emp e";
               ps=dbConn.getConn().prepareStatement(sql);
               ResultSet rs=ps.executeQuery();
               while(rs.next())
               {
                   EmpVO vo=new EmpVO();
                   vo.setEmpno(rs.getInt(1));
                   vo.setEname(rs.getString(2));
                   vo.setJob(rs.getString(3));
                   vo.setHiredate(rs.getDate(4));
                   vo.setSal(rs.getInt(5));
                   vo.setDname(rs.getString(6));
                   vo.setLoc(rs.getString(7));
                   list.add(vo);
               }
               rs.close();
           }catch(Exception ex)
           {
               // @After-Throwing => rollback
               System.out.println(ex.getMessage());
           }
           
           return list; // @After-Returning
       }
       // 상세보기 
       public EmpVO empDetailData(int empno)
       {
           EmpVO vo=new EmpVO();
           
           try
           {
               
               String sql="SELECT empno,ename,job,hiredate,sal,"
                         +"(SELECT dname FROM dept d WHERE d.deptno=e.deptno) as dname,"
                         +"(SELECT loc FROM dept d WHERE d.deptno=e.deptno) as loc "
                         +"FROM emp e "
                         +"WHERE empno=?";
               ps=dbConn.getConn().prepareStatement(sql);
               ps.setInt(1, empno);
               ResultSet rs=ps.executeQuery();
               rs.next();
               vo.setEmpno(rs.getInt(1));
               vo.setEname(rs.getString(2));
               vo.setJob(rs.getString(3));
               vo.setHiredate(rs.getDate(4));
               vo.setSal(rs.getInt(5));
               vo.setDname(rs.getString(6));
               vo.setLoc(rs.getString(7));
               rs.close();
           }catch(Exception ex)
           {
               System.out.println(ex.getMessage());
           }
           
           return vo;
       }
}
 
cs

 

 

 

# DBConnection.java

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
package com.sist.dao;
 
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
 
public class DBConnection {
    private Connection conn;
    private PreparedStatement ps;
    private String driver,url,username,password;
    public DBConnection(String driver,String url,String username,String password)
    {
        this.driver=driver;
        this.url=url;
        this.username=username;
        this.password=password;
        
        try
        {
            Class.forName(driver);
        }catch(Exception ex){}
    }
    public void getConnection()
    {
        try
        {
            conn=DriverManager.getConnection(url,username,password);
        }catch(Exception ex){}
    }
    public void disConnection()
    {
        try
        {
            if(ps!=null) ps.close();
            if(conn!=null) conn.close();
        }catch(Exception ex){}
    }
    public Connection getConn() {
        return conn;
    }
    public void setConn(Connection conn) {
        this.conn = conn;
    }
    public PreparedStatement getPs() {
        return ps;
    }
    public void setPs(PreparedStatement ps) {
        this.ps = ps;
    }
   
}
cs

 

 

 

# DBAsepect.java

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
package com.sist.aspect;
 
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.sist.dao.*;
 
@Aspect
@Component
public class DBAspect {
   @Autowired
   private DBConnection dbConn;
   
   @Before("execution(* com.sist.dao.EmpDAO.emp*(..))")
   public void before()
   {
       dbConn.getConnection();
   }
   @After("execution(* com.sist.dao.EmpDAO.emp*(..))")
   public void after()
   {
       dbConn.disConnection();
   }
}
cs

   - @Aspect  : 공통모듈 => DAO에서 공통사용 내용을 모아 준다(메모리 할당은 하지 않는다)
   - @Component : 메모리 할당

   - @Aspect 어노테이션을 붙여 이 클래스가 Aspect를 나타내는 클래스라는 것을 명시하고 @Component를 붙여 스프링 빈으로 등록한다.

 

 

 

# EmpController

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
package com.sist.web;
 
import java.util.*;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
 
import com.sist.dao.*;
@Controller
public class EmpController {
   @Autowired
   private EmpDAO dao;
   @GetMapping("emp/list.do")
   public String emp_list(Model model)
   {
       List<EmpVO> list=dao.empListData();
       model.addAttribute("list", list);
       return "emp/list";
   }
   @GetMapping("emp/detail.do")
   public String emp_detail(int empno,Model model)
   {
       EmpVO vo=dao.empDetailData(empno);
       model.addAttribute("vo", vo);
       return "emp/detail";
   }
}
cs

 

 

 

# application-context.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
<?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:aop="http://www.springframework.org/schema/aop"
    xmlns:c="http://www.springframework.org/schema/c"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:p="http://www.springframework.org/schema/p"
    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-4.3.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd">
    <!-- AOP적용 -->
    <aop:aspectj-autoproxy/>
    <!-- 사용자 클래스 메모리 할당 -->
    <context:component-scan base-package="com.sist.*"/>
    <!-- 
         1. 메모리 할당 => 어노테이션 사용
         2. 메모리 할당 => 값 주입 (XML)
     -->
    <bean id="dbconn"
       class="com.sist.dao.DBConnection"
       c:driver="oracle.jdbc.driver.OracleDriver"
       c:url="jdbc:oracle:thin:@211.238.142.181:1521:XE"
       c:password="happy"
       c:username="hr"
    />
    <bean id="viewResolver"
       class="org.springframework.web.servlet.view.InternalResourceViewResolver"
       p:prefix="/"
       p:suffix=".jsp"
     />
</beans>
 
cs

 

 

 

# list.jsp

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
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<style type="text/css">
.row {
  margin: 0px auto;
  width:800px;
}
</style>
</head>
<body>
  <div class="container">
    <div class="row">
      <h1 class="text-center">사원목록</h1>
      <table class="table table-striped">
        <tr class="success">
          <th>사번</th>
          <th>이름</th>
          <th>직위</th>
          <th>입사일</th>
          <th>급여</th>
          <th>부서명</th>
          <th>근무지</th>
        </tr>
        <c:forEach var="vo" items="${list }">
          <tr>
              <td>${vo.empno }</td>
              <td><a href="detail.do?empno=${vo.empno }">${vo.ename }</a></td>
              <%--
                  @GetMapping : 메소드방식(데이터 전송) : GET <a> sendRedirect(), location.href
                  @PostMapping : POST => form , ajax
                  @RequestMapping (@GetMapping+@PostMapping)
               --%>
              <td>${vo.job }</td>
              <td><fmt:formatDate value="${vo.hiredate }" pattern="yyyy-MM-dd"/></td>
              <td>${vo.sal }</td>
              <td>${vo.dname }</td>
              <td>${vo.loc }</td>
         </tr>
        </c:forEach>
      </table>
    </div>
  </div>
</body>
</html>
 
cs

 

 

 

# detail.jsp

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
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<style type="text/css">
.row {
  margin: 0px auto;
  width:350px;
}
</style>
</head>
<body>
   <div class="container">
     <div class="row">
       <h1 class="text-center">&lt;${vo.ename}&gt;사원 정보</h1>
       <table class="table">
         <tr>
          <td width=25% class="text-right">사번</td>
          <td width=75%>${vo.empno }</td>
         </tr>
         <tr>
          <td width=25% class="text-right">이름</td>
          <td width=75%>${vo.ename }</td>
         </tr>
         <tr>
          <td width=25% class="text-right">직위</td>
          <td width=75%>${vo.job }</td>
         </tr>
         <tr>
          <td width=25% class="text-right">입사일</td>
          <td width=75%><fmt:formatDate value="${vo.hiredate }" pattern="yyyy-MM-dd"/></td>
         </tr>
         <tr>
          <td width=25% class="text-right">급여</td>
          <td width=75%>${vo.sal }</td>
         </tr>
         <tr>
          <td width=25% class="text-right">부서명</td>
          <td width=75%>${vo.dname }</td>
         </tr>
         <tr>
          <td width=25% class="text-right">근무지</td>
          <td width=75%>${vo.loc }</td>
         </tr>
       </table>
     </div>
   </div>
</body>
</html>
 
cs

 

반응형