영보의 SystemOut.log

[Spring] Spring MVC 구조 자유게시판 만들기 - (1) 본문

Spring

[Spring] Spring MVC 구조 자유게시판 만들기 - (1)

영보로그 2020. 11. 7. 21:29
반응형

 개념 정리

 

 

# request 

구분
일반 MVC 구조

Spring
차이점
  1. 사용자 보내준 데이터를 받을 수 있다
       → getParameter() 
  2. 결과값을 모아서 전송해준 기능  
  3. request안에는 사용자의 정보 (IP,PORT) 존재

  1. 스프링에서 메소드의 매개변수를 이용해서 데이터값을 받는다  
  2. Model 인터페이스를 이용해서 데이터 전송  
  3. 보안에 목적 
예시
 * HttpSession 생성 (
 MVC에서 사용 )

   public String login(HttpServletRequest request) 
  { 
  HttpSession session=request.getSession(); 
  } 
  * Spring  
   public String login(HttpSession session) 
  { 
  } 
 
      → 매개변수는 순서가 없다  

  →   ※ Spring에서는 request를 사용하지 않는다 

 

 

# Spring → 데이터를 받는 경우 
  - 일반 데이터 (String,int...)
       VO단위로 데이터를 받는다 <input type=text name=subject>
                                                                               VO에 변수명이 동일
  - List로 데이터를 받을 수 있다 => <input type=text name=name[0]>                                               
  - 같은 값 여러개  ==> String[]
     <input type=checkbox name=cb>
     <input type=checkbox name=cb>
     <input type=checkbox name=cb>

 

 

 

 

 

 코드


#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
490
491
492
493
494
495
496
497
498
499
<?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>OnLineSpringMVCStudy5</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>com.googlecode.json-simple</groupId>
          <artifactId>json-simple</artifactId>
          <version>1.1.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>2.2.2</version>
      </dependency>
      <dependency>
         <groupId>org.apache.tiles</groupId>
         <artifactId>tiles-jsp</artifactId>
         <version>2.2.2</version>
      </dependency>
      <dependency>
         <groupId>org.apache.tiles</groupId>
         <artifactId>tiles-api</artifactId>
         <version>2.2.2</version>
      </dependency>
      
      <dependency>
         <groupId>org.apache.tiles</groupId>
         <artifactId>tiles-servlet</artifactId>
         <version>2.2.2</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>
      
      <!-- 
         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
<?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

 - 한글 변환을 위해서 이것도 환경설정을 꼭 해줘야합니다.

 

 

 

# BoardVO.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
package com.sist.dao;
import java.util.*;
 
import org.springframework.web.multipart.MultipartFile;
public class BoardVO {
   private int no;
   private String name;
   private String subject;
   private String content;
   private String pwd;
   private Date regdate;
   private int hit;
   private String filename;
   private String filesize;
   private int filecount;
   private List<MultipartFile> files;
   
public String getFilename() {
    return filename;
}
public void setFilename(String filename) {
    this.filename = filename;
}
public String getFilesize() {
    return filesize;
}
public void setFilesize(String filesize) {
    this.filesize = filesize;
}
public int getFilecount() {
    return filecount;
}
public void setFilecount(int filecount) {
    this.filecount = filecount;
}
public List<MultipartFile> getFiles() {
    return files;
}
public void setFiles(List<MultipartFile> files) {
    this.files = files;
}
public int getNo() {
    return no;
}
public void setNo(int no) {
    this.no = no;
}
public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public String getSubject() {
    return subject;
}
public void setSubject(String subject) {
    this.subject = subject;
}
public String getContent() {
    return content;
}
public void setContent(String content) {
    this.content = content;
}
public String getPwd() {
    return pwd;
}
public void setPwd(String pwd) {
    this.pwd = pwd;
}
public Date getRegdate() {
    return regdate;
}
public void setRegdate(Date regdate) {
    this.regdate = regdate;
}
public int getHit() {
    return hit;
}
public void setHit(int hit) {
    this.hit = hit;
}
   
}
cs

 - 미리 Oracle에 생성해놓은 데이터를 VO에서 스프링 프레임워크와 연동하기 위해 getter/setter로 캡슐화 코딩을 해줍니다.

 

 

# BoardController.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
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
package com.sist.web;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
 
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.URLEncoder;
import java.util.*;
 
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.sist.dao.*;
 
@Controller
public class BoardController {
  
    @Autowired
    private BoardDAO dao;
    @RequestMapping("board/list.do")
    public String board_list(String page,Model model)
    // request없이 dispatcherservlet사용
    {
        if(page==null)
            page="1";
        int curpage=Integer.parseInt(page);
        // 현재 페이지 데이터값을 읽어 온다
        Map map=new HashMap();
        int rowSize=10;
        int start=(curpage*rowSize)-(rowSize-1);
        int end=curpage*rowSize;
        map.put("start", start);
        map.put("end", end);
        List<BoardVO> list=dao.boardListData(map);
        // 총페이지 
        int totalpage=dao.boardTotalPage();
        model.addAttribute("curpage", curpage);
        model.addAttribute("totalpage", totalpage);
        model.addAttribute("list", list);
        return "board/list";// forward ,sendRedirect => return "redirect:.do";
    }
    @RequestMapping("board/insert.do")
    public String board_insert()
    {
        return "board/insert";
    }
    @RequestMapping("board/insert_ok.do")
    public String board_insert_ok(BoardVO vo) throws Exception
    {
        List<MultipartFile> list=vo.getFiles();
        if(list==null || list.size()<1)
        {
            vo.setFilename("");
            vo.setFilesize("");
            vo.setFilecount(0);
        }
        else
        {
            String fn="";
            String fs="";
            for(MultipartFile mf:list)
            {
                //System.out.println(mf.getOriginalFilename());
                String filename=mf.getOriginalFilename();
                File file=new File("c:\\upload\\"+filename);
                mf.transferTo(file);// 업로드하는 소스 
                fn+=filename+",";
                fs+=file.length()+",";
            }
            fn=fn.substring(0,fn.lastIndexOf(","));
            fs=fs.substring(0,fs.lastIndexOf(","));
            vo.setFilename(fn);
            vo.setFilesize(fs);
            vo.setFilecount(list.size());
        }
        
        dao.boardInsert(vo);
        return "redirect:list.do";
    }
    
    @RequestMapping("board/detail.do")
    public String board_detail(int no,Model model)
    {
        // DB연동 
        BoardVO vo=dao.boardDetailData(no);
        List<String> fList=new ArrayList<String>();
        List<Integer> sList=new ArrayList<Integer>();
        if(vo.getFilecount()>0)
        {
            StringTokenizer st=new StringTokenizer(vo.getFilename(),",");
            while(st.hasMoreTokens())
            {
                fList.add(st.nextToken());
            }
            
            StringTokenizer st1=new StringTokenizer(vo.getFilesize(),",");
            while(st1.hasMoreTokens())
            {
                sList.add(Integer.parseInt(st1.nextToken()));
            }
        }
        model.addAttribute("fList", fList);
        model.addAttribute("sList", sList);
        model.addAttribute("vo", vo);
        return "board/detail";
    }
    
    @RequestMapping("board/update.do")
    public String board_update(int no,Model model)
    {
        BoardVO vo=dao.boardUpdateData(no);
        model.addAttribute("vo", vo);
        return "board/update";
    }
    
    @RequestMapping("board/delete.do")
    public String board_delete(int no,Model model)
    {
        model.addAttribute("no", no);
        return "board/delete";
    }
 
    @RequestMapping("board/download.do")
    public void board_download(String fn,HttpServletResponse response) 
    {
        try
        {
            response.setHeader("Content-Disposition""attachment;filename="
                      +URLEncoder.encode(fn,"UTF-8"));
            File file=new File("c:\\upload\\"+fn);
            response.setContentLength((int)file.length());
            // 파일크기 => long
            
            BufferedInputStream bis=new BufferedInputStream(new FileInputStream(file));
            BufferedOutputStream bos=new BufferedOutputStream(response.getOutputStream());
            
            int i=0;
            // 읽은 바이트수
            byte[] buffer=new byte[1024];
            while((i=bis.read(buffer, 01024))!=-1)
            {
                bos.write(buffer, 0, i);
            }
            
            bis.close();
            bos.close();
        }catch(Exception ex){}
    }
cs

 -  스프링으로부터 필요한 클래스 객체를 받아 둔다 
    스프링에서 생성된 객체 주소를 받을 경우에 → 지역변수는 사용 할 수 없다 

 

 

 

# BoardDAO.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
package com.sist.dao;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import java.util.*;
@Repository
public class BoardDAO {
    @Autowired
    private BoardMapper mapper;
    // 목록 읽기
    public List<BoardVO> boardListData(Map map)
    {
        return mapper.boardListData(map);
    }
    // 총페이지 읽기
    public int boardTotalPage()
    {
        return mapper.boardTotalPage();
    }
    // 상세보기 
    public BoardVO boardDetailData(int no)
    {
        mapper.boardHitIncrement(no);
        return mapper.boardDeteilData(no);
    }
    // 추가 
    public void boardInsert(BoardVO vo)
    {
        mapper.boardInsert(vo);
    }
    // 수정 
    public BoardVO boardUpdateData(int no)
    {
        return mapper.boardDeteilData(no);
    }
    // 실제 수정 
    public boolean boardUpdate(BoardVO vo)
    {
        boolean bCheck=false;
        String db_pwd=mapper.boardGetPassword(vo.getNo());
        if(db_pwd.equals(vo.getPwd()))
        {
            bCheck=true;
            mapper.boardUpdate(vo);
        }
        else
        {
            bCheck=false;
        }
        return bCheck;
    }
    // 삭제
    public boolean boardDelete(int no,String pwd)
    {
        boolean bCheck=false;
        String db_pwd=mapper.boardGetPassword(no);
        if(db_pwd.equals(pwd))
        {
            bCheck=true;
            mapper.boardDelete(no);
        }
        else
        {
            bCheck=false;
        }
        return bCheck;
    }
    public BoardVO boardFileInfoData(int no)
    {
        return mapper.boardFileInfoData(no);
    }
    
}
cs

 

 

 

# BoardMapper.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
package com.sist.dao;
import java.util.*;
 
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.SelectKey;
import org.apache.ibatis.annotations.Update;
public interface BoardMapper {
  // 목록 출력
  // <select> => @Select ==> XML을 대체 어노테이션 
  @Select("SELECT no,subject,name,regdate,hit,num "
         +"FROM (SELECT no,subject,name,regdate,hit, rownum as num "
         +"FROM (SELECT no,subject,name,regdate,hit "
         +"FROM spring_board ORDER BY 1 DESC)) "
         +"WHERE num BETWEEN #{start} AND #{end}")
  public List<BoardVO> boardListData(Map map);
  @Select("SELECT CEIL(COUNT(*)/10.0) FROM spring_board")
  public int boardTotalPage();
  // 데이터 추가 
  @SelectKey(keyProperty="no",resultType=int.class,before=true,
            statement="SELECT NVL(MAX(no)+1,1) as no FROM spring_board")
  @Insert("INSERT INTO spring_board(no,name,subject,content,pwd,filename,filesize,filecount) "
         +"VALUES(#{no},#{name},#{subject},#{content},#{pwd},#{filename},#{filesize},#{filecount})")
  public void boardInsert(BoardVO vo);
  // 상세보기 
  @Update("UPDATE spring_board SET "
         +"hit=hit+1 "
         +"WHERE no=#{no}")
  public void boardHitIncrement(int no);
  @Select("SELECT no,name,subject,content,regdate,hit,filename,filesize,filecount "
         +"FROM spring_board "
         +"WHERE no=#{no}")
  public BoardVO boardDeteilData(int no);
  // 수정 
  @Select("SELECT pwd FROM spring_board "
         +"WHERE no=#{no}")
  public String boardGetPassword(int no);
  
  @Update("UPDATE spring_board SET "
         +"name=#{name},subject=#{subject},content=#{content},"
         +"filename=#{filename},filesize=#{filesize},filecount=#{filecount} "
         +"WHERE no=#{no}")
  public void boardUpdate(BoardVO vo);
  // 삭제  
  @Delete("DELETE FROM spring_board "
         +"WHERE no=#{no}")
  public void boardDelete(int no);
  // 삭제 - 1
  @Select("SELECT filename,filecount,filesize "
         +"FROM spring_board "
         +"WHERE no=#{no}")
  public BoardVO boardFileInfoData(int no);
}
cs

 

 

 

# BoardRestController.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
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
package com.sist.web;
 
import java.io.File;
import java.util.StringTokenizer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.sist.dao.*;
import java.util.*;
 
// 필요한 JavaScript
@RestController
// ajax , react 
// 단점 => IE (실행이 안됨)
public class BoardRestController {
   @Autowired
   private BoardDAO dao;
   
   @RequestMapping("board/update_ok.do")
   public String board_update_ok(BoardVO vo)
   {
       String result="";
       BoardVO pvo=dao.boardFileInfoData(vo.getNo());
       List<MultipartFile> list=vo.getFiles();
       // 파일 업로드가 안된 상태
       if(list==null || list.size()<1)
       {
           if(vo.getFilecount()<1)
           {
               vo.setFilename("");
               vo.setFilesize("");
               vo.setFilecount(0);
           }
           else
           {
               vo.setFilename(pvo.getFilename());
               vo.setFilesize(pvo.getFilesize());
               vo.setFilecount(pvo.getFilecount());
           }
       }
       // 파일 업로드가 된 상태 
       else
       {
           String fn="";
           String fs="";
           for(MultipartFile mf:list)
           {
               String filename=mf.getOriginalFilename();
               File files=new File("c:\\upload\\"+filename);
               try
               {
                    mf.transferTo(files);// 업로드 
               }catch(Exception ex){}
               fn+=filename+",";
               fs+=files.length()+",";
           }
           fn=fn.substring(0,fn.lastIndexOf(","));
           fs=fs.substring(0,fs.lastIndexOf(","));
           
           vo.setFilename(fn);
           vo.setFilesize(fs);
           vo.setFilecount(list.size());
           // 기존에 파일이 있다면 
           if(pvo.getFilecount()>0)
           {
               StringTokenizer st=new StringTokenizer(pvo.getFilename(),",");
               while(st.hasMoreTokens())
               {
                   File file=new File("c:\\upload\\"+st.nextToken());
                   file.delete();
               }
           }
       }
       boolean bCheck=dao.boardUpdate(vo);
       if(bCheck==true)
       {
           
           result="<script>"
                 +"location.href=\"detail.do?no="+vo.getNo()+"\";"
                 +"</script>";
           
       }
       else
       {
           result="<script>"
                 +"alert(\"Password Fail!!\");"
                 +"history.back();"
                 +"</script>";
       }
       return result;
   }
   
   @RequestMapping("board/delete_ok.do")
   public String board_delete_ok(int no,String pwd)
   {
       String result="";
       // 먼저
       BoardVO vo=dao.boardFileInfoData(no);
       // 나중
       boolean bCheck=dao.boardDelete(no, pwd);
       if(bCheck==true)
       {
           // 파일을 삭제하는 부분 
           try
           {
               if(vo.getFilecount()>0)
               {
                   //File dir=new File("c:\\upload");
                   StringTokenizer st=new StringTokenizer(vo.getFilename(),",");
                   while(st.hasMoreTokens())
                   {
                       File file=new File("c:\\upload\\"+st.nextToken());
                       file.delete();
                   }
               }
           }catch(Exception ex){}
           result="<script>"
                 +"location.href=\"list.do\";"
                 +"</script>";
       }
       else
       {
           result="<script>"
                 +"alert(\"비밀번호가 틀립니다!!\");"
                 +"history.back();"
                 +"</script>";
       }
       return result;
   }
}
cs

- 이전    : mvc프로그램에서 JavaScript를 쓸 때 항상 _ok를 써서 jsp에 코딩

- 스프링 : RestController는 자바 내에서 코딩 가능

             주소값을 넘겨주는 것이 아니라 JavaScript, JSON 일반 문자열 넘길 때 쓰이는 위치로 사용

              → JavaScript 자체를 보낼 수 있다

              JavaScript 코드를 RestController에서 처리하기 때문에  jsp파일이 안늘어나고  코드가 가벼워진다

 

반응형