세미프로젝트발표




A조

간트차트 집어넣을것

폰트부분이 너무화려함( 깨져서 잘못뜬 폰트)


UI 웹부분 어떤 UI인지 인지하기힘듬 타이틀이 나와야함


시스템 구성도

웹서버가 웹클라이언트로 빠져야함


비동기식에 대한 언급이 없음

기술이 들어간 것에 대한 주요 언급이 없음

물리ERD만 들어갈 것


UML때는 VO는 제외할 것

시연때는 기술적인 내용을 발표 할 것(타이틀로)


시연중 오류시 감점



B조

간트차트 누가 무엇을 했는지 

PPT발표자는 처음부터 끝까지 내용숙지후 발표 할 것


C조

간트차트 잘되어있음

웹구현 소스설명 UI와 접목이 안됨

시연영상(자막을 추가하는 것이 좋음)


D조

지적없음




메인프로젝트

1차(회로)은 개인제출

2차(백엔드)도 개인제출

'학원수업 > Spring' 카테고리의 다른 글

학원 33~35일차 복습(4/27,5/2,5/3)  (0) 2018.04.27
학원 32일차 복습(4/26)  (0) 2018.04.27
학원 26일차 복습(4/18)  (0) 2018.04.18
학원 24일차 복습(4/16)  (0) 2018.04.16
학원 23일차 복습(4/13)  (0) 2018.04.13


세미프로젝트


안드로이드(리스트뷰,인탠트,쓰레드,소켓통신,HTTP통신,I/O파일 저장 및 읽기)

자바(소켓,IO,쓰레드),AJAX

스프링MVC,래스트풀 제이슨처리,마이바티스(다이나믹쿼리,리졸트맵,기타)

오라클(조인,서브쿼리,그룹함수)


중요파트 소켓,스프링MVC,래스트풀,마이바티스


발사믹목업,(UI)

1.(요구사항) 페르소나 ->기능추출

2.클래스설계

3.DB설계


워터풀방식

개발팀분장


작업플랜: 간트차트


조장님은 종이에 테스크보드(start, doing , end)



안드실행시 검은화면뜨면 IP주소확인할것!!

'학원수업 > Spring' 카테고리의 다른 글

학원 36일차 복습(5/4)  (0) 2018.05.08
학원 32일차 복습(4/26)  (0) 2018.04.27
학원 26일차 복습(4/18)  (0) 2018.04.18
학원 24일차 복습(4/16)  (0) 2018.04.16
학원 23일차 복습(4/13)  (0) 2018.04.13

이론



테스트시 

http://localhost/spring0426_jquery/exam?cmd= jsp이름 

입력하여 확인


id는 #

tag는 그냥

class는 . 


JQuery

$(document).ready(function(){});

축약형 : $(function(){});

 dom구조이다. dom만 로드 될때까지 기다린다.(이미지,동영상,리소스 X)


1. css의 가장 기본적인 선택자는 와일드 카드 선택자 이다.

    HTML문서 내의 모든 요소에 스타일이 적용된다. 

2. tag 선택자를 사용해서 특정 태그를 선택 할 수 있다.


JQuery 함수 필터 선택자

● 요소:contains(문자열) : 특정 문자열을 포함하는 문서 객체를 선택

● 요소:eq(n) : n번째 위치하는 문서 객체를 선택

● 요소:gt(n) : n번째 초과 위치하는 문서 객체를 선택

● 요소:has(h1) : h1태그를 가지고 있는 문서 객체를 선택

● 요소:lt(n) : n번째 미만에 위치하는 문서 객체를 선택

● 요소:not(선택자) : 선택자와 일치하지 않는 문서 객체를 선택

● 요소:nth-child(3n+1) : 3n+1번째 위치하는 문서 객체를 선택한다 (1,4,7,,,,)


each()는 jQuery를 사용해서 배열을 관리하려고 할 때 사용하는 메서드이다.

 1. $.each(배열객체,function(index,item){});

 2. $.(selector).each(function(index,item){});


filter() : 문서 객체를 탐색 및 필터링을 한다.

● $(selector).filter(selector);

● $(selector).filter(function(){ });


$.ajax({옵션속성:값}); // jQuery.ajax();

 url:문자열 - 요청url 설정

 type:문자열 - GET/POST설정

 data:객체,문자열 - 요청 매개변수 설정 

 success:함수 - 성공시 호출할 함수 설정

 async:불리언 - 동기/비동기 설정

 error:함수 - 실패시 호출할 함수 설정



실습


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
  <modelVersion>4.0.0</modelVersion>
  <groupId>spring0426_jquery</groupId>
  <artifactId>spring0426_jquery</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  <build>
    <sourceDirectory>src</sourceDirectory>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.7.0</version>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>
      <plugin>
        <artifactId>maven-war-plugin</artifactId>
        <version>3.0.0</version>
        <configuration>
          <warSourceDirectory>WebContent</warSourceDirectory>
        </configuration>
      </plugin>
    </plugins>
  </build>
  <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.3.6.RELEASE</version>
        </dependency>
        <!-- spring-jdbc for MyBatis -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>4.3.6.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.2</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.1</version>
        </dependency>
        <!-- Web MVC -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>4.3.6.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>4.3.6.RELEASE</version>
        </dependency>
        <!-- Aop관련 -->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.8.10</version>
        </dependency>
        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.8.6</version>
        </dependency>
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.3</version>
        </dependency>
    </dependencies>
</project>

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
<?xml version="1.0" encoding="UTF-8"?>
  <display-name>spring0426_jquery</display-name>
   <!-- Filter -->
  <filter>
    <filter-name>CharacterEncodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>EUC-KR</param-value>
    </init-param>
    <init-param>
      <param-name>forceEncoding</param-name>
      <param-value>true</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>CharacterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  <servlet>
   <servlet-name>kosta</servlet-name>
   <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  </servlet>
  <servlet-mapping>
   <servlet-name>kosta</servlet-name>
   <url-pattern>/</url-pattern>
  </servlet-mapping>
   
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
 
</web-app>

kosta-servlet.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
<?xml version="1.0" encoding="UTF-8"?>
    xmlns:mybatis-spring="http://mybatis.org/schema/mybatis-spring"
 
    <context:component-scan base-package="or.kosta.mvc"/>
    <mvc:annotation-driven/>
    <mvc:resources location="/resources/" mapping="/resources/**"/>
     
    <!-- dataSource settting -->
    <bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
    <property name="jndiName" value="java:comp/env/jdbc/myoracle"></property>
    </bean>
    <!-- MyBatis config,mapper setting -->
    <bean id="factoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="configLocation"
            value="classpath:or/kosta/config/config.xml"/>
        <property name="mapperLocations"
            value="classpath*:or/kosta/mapper/*.xml"/>
         
    </bean>  
    <!-- Mybatis Template configure -->
    <bean id="ss" class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg ref="factoryBean"/>
    </bean>
    <!-- MyBatis MapperFactoryBean :  Mybatis어노테이션 사용하기 위한 설정-->
    <bean class="org.mybatis.spring.mapper.MapperFactoryBean">
        <property name="mapperInterface" value="or.kosta.mvc.map.MemoMapper"/>
        <property name="sqlSessionFactory" ref="factoryBean"/>
    </bean>
     
    <!-- mutipartresolver 추가 : 파일 업로드를 하기 위해서 꼭 필요한 객체 -->
    <bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver"></bean>
    <!--  /WEB-INF/jsp/hello.jsp -->
    <bean id="viewResolver"
    class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>

or.kosta.mvc.controller/JQueryExamController.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
package or.kosta.mvc.controller;
 
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
 
@Controller
public class JQueryExamController {
 
    @GetMapping("/exam")
    public String ex1(String cmd, Model m) {
        if (cmd.equals("eachExam")) {
//          String[] colr = { "red", "orange", "aqua", "blueviolet", "palevioletred", "purple", "pink", "royalblue",
//                  "brown", "burlywood" };
//          m.addAttribute("colr", colr);
        } else if (cmd.equals("ex2_load_test")) {
            StringBuffer sb = new StringBuffer();
            sb.append("<h1>Hello World!</h1>");
            sb.append("<p> load될 영역 </p>");
            sb.append("<span>여기는?</span>");
            sb.append("<span>잠시만 .. <p>여기는2?<p></span>");
            m.addAttribute("html", sb.toString());
        }
        return cmd;
    }
    @GetMapping("/exam2")
    public String ex1(String cmd,String name,String orderName,Model m) {
        String status;
        if(cmd.equals("ex3_ajax")) {
            if(name.equals("김길동") && orderName.equals("A001")){
                status="주문하신 금괴가 지금 발송중입니다.";
            }else if(name.equals("김길동") && orderName.equals("A002")){
                status="주문하신 자동차는 공장에서 주문생산 완료 되었습니다.";
            }else{
                 status="이미 발송된 완료된 제품입니다.";
            }
            m.addAttribute("status", status);
             
        }
        return cmd;
    }
}

ex2.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html>
 
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>ex2.jsp</title>
<script>
    $(document).ready(function(){
        // 1. css의 가장 기본적인 선택자는 와일드 카드 선택자 이다.
        //    HTML문서 내의 모든 요소에 스타일이 적용된다.
        $('*').css('color','red');
        // 2. tag 선택자를 사용해서 특정 태그를 선택 할 수 있다.
        $('p').css('color','orange');
    });
</script>
</head>
 
        <h1>Hello World!</h1>
        <p>나의 첫번째 jQuery Page 입니다.</p>
        <h2>jQuery를 사용하면 브라우저의 차이를 최소화 할 수 있다.</h2>
        <p>jQuery가 편하다.^^</p>

ex3.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
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html>
 
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>ex3.jsp</title>
<script
<style>
#wrap {  width: 450px;  margin: auto; }
</style>
<script>
         $(function(){
             $('#wrap').css('backgroundColor','red');
             $('#wrap').css('text-align','center');
             $('#wrap h1').css('color','white');
             // 5초 후에 다음 스타일을 적용 시켜보자.
             setTimeout(function(){
                 $('#wrap').css('backgroundColor','pink');
                 $('#wrap h1').css('color','yellow');
             },5000);
         });
 
</script>
</head>
 
    <div id="wrap">
        <h1>test1</h1>
    </div>

ex4_class.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
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html>
 
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>Insert title here</title>
<style>
#wrap {  width: 450px;  margin: auto; }
</style>
<script>
    $(document).ready(function(){
            $('.item').css('color','orange');
            $('div h1 .item').css('background','red');
            $('div .item.select').css('background','blue');
    });
</script>
</head>
 
        <div>
        <h1 class="item">Hello World!</h1>
        <h1 class="item select">Hello World!</h1>
        <h1><p class="item">Hello World!</p></h1>
        </div>

ex5.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
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html>
 
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>Insert title here</title>
<script>
    $(document).ready(function(){
         // 속성 선택자
        $('input[type=text]:first').val('My JQuery!');
        $('input[type=text]:last').val('My JQuery!');
        $('input[type=text]:eq(2)').val('My JQuery!!');
        $('input[type=password]').val('test');
    });
</script>
</head>
 
        <div>
            <input type="text"/>
            <input type="text"/>
            <input type="text"/>
            <input type="text"/>
            <input type="text"/>
            <input type="password"/>
        </div>

ex6.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
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>  
<!DOCTYPE html>
 
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>ex5.jsp</title>
<script
<style>
table {width: 200px;}
</style>
<script>
    $(document).ready(function() {
         $('tr:first').css("background", "olive");
         $('tr:odd').css("background", "pink");
         $('tr:even').css("background", "yellow");
    });
</script>
</head>
 
    <table>
        <c:forEach var="i" begin="0" end="9" step="1">
        <tr>
            <td>${i }</td>
        </tr>
        </c:forEach>
    </table>

ex7.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
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html>
 
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>Insert title here</title>
<%--
JQuery 함수 필터 선택자
● 요소:contains(문자열) : 특정 문자열을 포함하는 문서 객체를 선택
● 요소:eq(n) : n번째 위치하는 문서 객체를 선택
● 요소:gt(n) : n번째 초과 위치하는 문서 객체를 선택
● 요소:has(h1) : h1태그를 가지고 있는 문서 객체를 선택
● 요소:lt(n) : n번째 미만에 위치하는 문서 객체를 선택
● 요소:not(선택자) : 선택자와 일치하지 않는 문서 객체를 선택
● 요소:nth-child(3n+1) : 3n+1번째 위치하는 문서 객체를 선택한다 (1,4,7,,,,)
 --%>
<script>
    $(document).ready(function(){
           //$('div p:contains("Test")').css("background", "pink");
           //연습문제 div안에 있는 모든 요소에서 Test 문자열을 포함할 때
            
           //$('div p:gt(0)').css('background','red');
            
           //$('div:has("h1")').css({'background':'yellow','border':'1px solid red'});
           //$('p:nth-child(2n+1)').css('background','green');
    });
</script>
</head>
 
        <div>
            <p>Test 1</p>
            <p>이것은  Test 입니다.</p>
            <p>오늘은 목요일!</p>
            <p>내일은 금요일!</p>
            <p>내일은 금요일!</p>
            <p>내일은 금요일!</p>
            <p>내일은 금요일!</p>
            <p>내일은 금요일!</p>
            <h1>jQuery Test 입니다.</h1>
            <div>
                <h1>jQuery Test2 입니다.</h1>
            </div>
        </div>

ex8_each.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
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html>
 
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>Insert title here</title>
<style>
    .h{ background: orange;}
    .t{ background: pink;}
</style>
<script>
    $(document).ready(function(){
/* each()는 jQuery를 사용해서 배열을 관리하려고 할 때 사용하는 메서드이다.
 1. $.each(배열객체,function(index,item){});
 2. $.(selector).each(function(index,item){});*/
 
         var array=[
             {name:'김길동', addr:'서울 신촌'},
             {name:'김승아', addr:'서울 신촌'},
             {name:'이지현', addr:'서울 구로'}
         ];
         $(function(){
             $.each(array, function(idx,item){
//                   var print ='';
//                   print +="<h1> ["+item.addr+"]"+" "+item.name+"</h1>";
//                   document.getElementById("res").innerHTML +=print; 
                 $('#res').append("<h1> ["+item.addr+"]"+" "+item.name+"</h1>");
                 $('#res h1').addClass("h");
             });
             $('p').each(function(index,item){
                   $(item).addClass('t');
                   $(this).append(":"+array[index].name);
             });
         });
    });
</script></head>
 
            <div id="res"></div>
            <h1>Hello World!</h1>
            <p>test1</p>
            <p>test2</p>
            <p>test3</p>

ex9_filter.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
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html>
 
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>ex9_filter</title>
<script
<script>
    $(document).ready(function() {
        /*filter() : 문서 객체를 탐색 및 필터링을 한다.
         ● $(selector).filter(selector);
         ● $(selector).filter(function(){ });*/
        // 1. 예전에 했던 홀수요소만 찾아서 문서 객체의 색상을 변경 해보자
        //$('tr:odd').css({backgroundColor:'orange',color:'red'});
        // 2. filter()메서드의 인자값에 even을 사용할 수 있다.
        $('tr').filter(':even').css({backgroundColor:'yellow',color:'blue'});
        // -> 3의 배수값을 리턴 받아서 문서객체로 선택한다.
//      $('tr').filter(function(index) {
//          return index % 3 == 0;
//      }).css({
//          backgroundColor : 'pink',
//          color : 'blue'
//      });
    });
</script>
</head>
<div id="wrap">
        <table><%for (int i = 0; i < 10; i++) {%>
            <tr>
                <td>Value : <%=i%></td>
            </tr>
            <%
                }
            %>
        </table>
    </div>

ex10.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
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html>
 
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>ex10</title>
<script
<style>
#res {
    width: 200px;
    background: pink;
    height: 35px;
}
</style>
<script>
//attr() : 속성과 관련된 모든 기능을 수행한다.
$(function(){
  //  $('img').attr('width', 150);
//     $('img').attr('width',function(index){
//        return (index +1) * 100;
//     });
   // 연습문제 : 이미지의 크기를 100, 250, 500 으로 맞추시오.
    $('img').attr('width',function(index){
        if(index == 0){       
            return 100;
        }else if(index == 1){
            return 250;
        }else {
            return 500;
        }   
     });
});
</script>
</head>
 
    <div id="res"></div>
    <img src="resources/img/m1.png" />
    <img src="resources/img/m2.png" />
    <img src="resources/img/m3.png" />

ex11.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
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html>
 
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>Insert title here</title>
<script
<script>
    $(document).ready(function() {
        /*
         * attr()
         ● $(selector).attr(name,value);
         ● $(selector).attr(name,function(index,attr){});
         ● $(selector).attr({object});
         */$('img').attr({
            border : '1px soild red',
            height : function(index) {
                if (index == 0) {
                    return 100;
                } else if (index == 1) {
                    return 200;
                } else {
                    return 500;
                }
            }
        });
    });
</script>
</head>
 
    <div id="res"></div>
    <img src="resources/img/m1.png" />
    <img src="resources/img/m2.png" />
    <img src="resources/img/m3.png" />

ex12.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
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html>
 
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>Insert title here</title>
<script
<script>
    $(document).ready(function() {
 
                //innerHTML같다.
                //$('div').html('<h1>Test 1 </h1>');
//              $('div').html(function(index) {
//                  return '<p> test' + index + "</p>";
//              });
                //위의 예제에서 <h1> ~ <h3> 으로 <div>안의 내용을 채우시오.
                $('div').html(
                        function(index) {
                            return '<h' + parseInt(index + 1,10) + '> Test  '
                                    + '</h' + parseInt(index + 1,10) + '>';
                        });
                $('div').css({
                    border : '1px solid red',
                    width : 300,
                    height : 120
                });
            });
</script>
</head>
 
    <div></div>
    <div></div>
    <div></div>

ex13.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
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html>
 
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>Insert title here</title>
<script
<script>
//  $(document).ready(function() {
//       //h1의 내용을 읽어와서 html 인자로 전달
//         $('h1').html(function(index,html){
//          console.log(index+":"+html);
//             return '♡'+html+'♡';
//         });
//         //연습문제) css선택자를 사용해서 h1의 0부터 2까지의 색상을 지정해서 출력하시오.
//  });
    $(function(){
        //색상이 굵은 부분을 추가해서 작성한 후 설명 한다.(연습문제 답)
        $('h1').css('color', function(index){
            if(index == 0){
                return 'red';
            }else if(index == 1){
                return 'blue';
            }else{
                return 'orange';
            }
        });
        $('h1').html(function(index,html){
            return '♡'+html+'♡';
        });
        $('<h2></h2>').html('하이 안뇽!').appendTo('body');
        $('<p></p>').html('하이 안뇽!zz').prependTo('span');
    });
</script>
</head>
 
    <span>Tag Test</span>
     
    <h1>Hello World!</h1>
    <h1>Hello World!</h1>
    <h1>Hello World!</h1>
     
     
    

ex14.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
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html>
 
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>Insert title here</title>
<script
<style>
#res {width: 300px;background: pink}
.cng {background: orange;color: red;}
p {color: pink}
</style>
<script>
    $(function() {
        // 한번에 여러 이벤트를 감지하고 처리하고 할 때 사용되는 함수
        $('h1').bind({
            click : function() {
                $(this).html(function(index, html) {
                    return "<p>러브러브 ♥</p>";
                });
            },
            mouseenter : function() {
                $(this).addClass('cng')
            },
            mouseleave : function() {
                $(this).removeClass('cng')
            }
        });
    });
</script>
</head>
 
 
    <h1>Hello World!</h1>
    <h1>Hello World!</h1>
    <h1>Hello World!</h1>
    <div id="res"></div>

ex15_load.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
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html>
 
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>Insert title here</title>
<script>
    $(document).ready(function(){
        /*
         *  ex2_load_test.jsp의
         *  p 요소만을 가져와서 현제 페이지
         *  div 요소안에 넣기 위해서 아래와
         *  같이 문법을 적용할 수 있다.
         *  p이외에도 , 를 사용해서 span 요소도 가져 올 수 있다.
         */
        $('div').load('exam?cmd=ex2_load_test p,span p');
    });
</script>
</head>
 
        <div></div>
        

ex16_ajax.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
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html>
 
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>Insert title here</title>
<script>
    $(document).ready(function(){
/*$.ajax({옵션속성:값}); // jQuery.ajax();
 *
 url:문자열 - 요청url 설정
 type:문자열 - GET/POST설정
 data:객체,문자열 - 요청 매개변수 설정
 success:함수 - 성공시 호출할 함수 설정
 async:불리언 - 동기/비동기 설정
 error:함수 - 실패시 호출할 함수 설정
  
 */
  
         $('#btn1').click(function(){
             var n = $('#name').val();
             var on = $('#orderNum').val();
             console.log("Name"+n);
             console.log("Num"+on);
             $.ajax({
                 url: "exam2?cmd=ex3_ajax&name="+n+"&orderName="+on,
                 success: function (data,status) {
                     alert(data+","+status);
                     $('#res').html(data);
                 },
                 error:function(e){
                     alert(e);
                 }
             });
         });
    });
</script>
</head>
 
       <h1>주문확인!</h1>
        <input  type="text" name="name" id="name"><br/>
        <input type="text" name="orderNum" id="orderNum"><br/>
        <input type="button" value="확인" id="btn1"><br />
        <div id="res">Status : </div>

ex2_load_test.jsp

1
2
3
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
${html}

ex3_ajax.jsp

1
2
3
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
${status}

exam.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
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html>
 
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>exam.jsp</title>
<script
<style>
#wrap {
    width: 450px;
    margin: auto;
}
</style>
 
<script>
    $(document).ready(function() {
          $('div p').css('width',200);
          $('div p').css('backgroundColor','pink');
    });
</script>
</head>
<%--다음 div 안에 p 태그의 요소에 스타일을 width :200px 에 background-color를
pink 로 변경 하시오. --%>
    <div id="wrap">
        <p>test1</p>
    </div>

exam2.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
56
57
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html>
 
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>Insert title here</title>
<script
<style>
#wrap {
    width: 650px;
    margin: auto;
}
</style>
<script>
    var num = false;
    $(function() {
        $('.item').css('background', 'yellow');
        $('.item.select').css('background', 'orange');
        setTimeout(test, 500);
 
    });
    function test() {
        $('.item').css('background', 'red');
        $('.item.select').css('background', 'blue');
        setTimeout(test2, 500);
    }
    function test2() {
        $('.item').css('background', 'blue');
        $('.item.select').css('background', 'red');
        setTimeout(test, 500);
    }
</script>
</head>
 
    <div id="wrap">
        <table style="width:100%">
            <tbody>
                <tr>
                    <td class="item">Test내용 입니다.</td>
                </tr>
                <tr>
                    <td class="item select">Test내용 입니다.</td>
                </tr>
                <tr>
                    <td class="item">Test내용 입니다.</td>
                </tr>
                <tr>
                    <td class="item select">Test내용 입니다.</td>
                </tr>
                <tr>
                    <td class="item">Test내용 입니다.</td>
                </tr>
            </tbody>
        </table>
    </div>

exam3.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
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
 
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>ex5.jsp</title>
<script
<style>
table {
    width: 200px;
}
</style>
<script>
var flag = false;
    $(document).ready(function() {
            $('thead tr:first').css("background", "olive");
            $('tbody tr:odd').css("background", "pink");
            $('tbody tr:even').css("background", "yellow");
             
            setInterval(function() {
                if(flag){
                        $('tbody tr:odd').css("background", "yellow");
                        $('tbody tr:even').css("background", "pink");
                        flag=false;
                }else{
                        $('tbody tr:odd').css("background", "pink");
                        $('tbody tr:even').css("background", "yellow");
                        flag=true;
                }
                 
            }, 500);
        });
 
</script>
</head>
 
    <table>
        <c:forEach var="i" begin="0" end="9" step="1">
            <tr>
                <td>${i }</td>
            </tr>
        </c:forEach>
    </table>

examBind.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html>
 
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>examBind</title>
<script
    <style>
            #target,#imgCnt{width: 600px; margin: auto; }
            #target img{width: 550px; height: 350px; margin: 30px;}
            ul li {list-style: none; float: left; margin-left: 5px}
            ul li img{width: 100px; cursor: pointer; }
 
            #dialog-background {
                display: none;
                position: fixed;
                top: 0; left: 0;
                width: 100%; height: 100%;
                background: rgba(0,0,0,.3);
                z-index: 10;
            }
            #my-dialog {
                display: none;
                position: fixed;
                left: calc( 50% - 160px ); top: calc( 50% - 70px );
                background: #fff;
                z-index: 11;
                padding: 10px;
            }
</style>
<script>
    $(document).ready(function() {
         $('img').bind({
             mouseenter:function(){
                 $('#target  img').attr('src',$(this).attr('src').valueOf())
             },click:function(){
                 $('#my-dialog,#my-dialogImg').css({'width':400,'height':300})
                 $("#my-dialog,#dialog-background").show();
                 $('#my-dialogImg').attr('src',$(this).attr('src').valueOf());
             }
         });
         $('#btn-close-dialog').click(function(){
             $("#my-dialog,#dialog-background").hide();
         });
    });
</script>
</head>
 
    <div id="target">
        <img src="resources/img/m1.png"/>
    </div>
    <div id="imgCnt">
        <ul>
            <%
                for (int i = 1; i <= 5; i++) {
            %>
            <li><img src="resources/img/m<%=i%>.png"/></li>
            <%
                }
            %>
        </ul>
    </div>
    <!-- 모달창  -->
    <div id="my-dialog">
    <img src="" id="my-dialogImg">
    <button id="btn-close-dialog">창 닫기</button>
    </div>
    <div id="dialog-background"></div>


'학원수업 > Spring' 카테고리의 다른 글

학원 36일차 복습(5/4)  (0) 2018.05.08
학원 33~35일차 복습(4/27,5/2,5/3)  (0) 2018.04.27
학원 26일차 복습(4/18)  (0) 2018.04.18
학원 24일차 복습(4/16)  (0) 2018.04.16
학원 23일차 복습(4/13)  (0) 2018.04.13

이론


동기식: HTTPRequest 모든 코드 전송



비동기식: XML_HTTPRequest 필요한 코드만 전송,callback***

자바스크립트 이벤트가 트리거


Ajax를 이용한 웹 접근 방법

 - 요청 / 응답 방식 동일

 - 응답은 자바스크립트의 HttpRequest객체가 받음

 - 사용자는 하나의 페이지에서 다른일을 계속 수행할 수 있음

 - 응답이 오면 자바스크립트의 함수를 통해 일을 수행

 - 하나의 페이지에서 여러 가지 데이터를 서버로부터 실시간으로 갱신 가능

 - 페이지리로딩없이 계속 서버와 통신 가능


■ Ajax의 장점

 - 서버 처리를 기다리지 않고, 비동기 요청이 가능

 - 수신하는 데이터의 양을 줄일 수 있음

 - 서버의 부하를 줄이고, 성능좋은 클라이언트를 사용함


■ Ajax의 단점

 - 페이지 이동없는 통신으로 인한 보안상의 문제

 - 클라이언스크립트로 작성되므로 Debugging이 용이하지 않음

 (WISWIG를 지원하는 통합개발툴(IDE)이 없음)


html에서 name 과 id

name: action에 해당하는 페이지로 전달하는 파라미터

id: javascript에서 다룰려고 지정


브라우저별 XMLHttpRequest 객체를 저장할 전역변수

서버로부터 결과가 도착할 때 수행하는 함수 지정 (콜백함수)


실습


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
  <modelVersion>4.0.0</modelVersion>
  <groupId>spring0418_js</groupId>
  <artifactId>spring0418_js</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  <build>
    <sourceDirectory>src</sourceDirectory>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.7.0</version>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>
      <plugin>
        <artifactId>maven-war-plugin</artifactId>
        <version>3.0.0</version>
        <configuration>
          <warSourceDirectory>WebContent</warSourceDirectory>
        </configuration>
      </plugin>
    </plugins>
   </build>
   <dependencies>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-context</artifactId>
                <version>4.3.6.RELEASE</version>
            </dependency>
            <!-- spring-jdbc for MyBatis -->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-jdbc</artifactId>
                <version>4.3.6.RELEASE</version>
            </dependency>
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis</artifactId>
                <version>3.4.2</version>
            </dependency>
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis-spring</artifactId>
                <version>1.3.1</version>
            </dependency>
            <!-- Web MVC -->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-web</artifactId>
                <version>4.3.6.RELEASE</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-webmvc</artifactId>
                <version>4.3.6.RELEASE</version>
            </dependency>
            <dependency>
                <groupId>commons-fileupload</groupId>
                <artifactId>commons-fileupload</artifactId>
                <version>1.3.3</version>
            </dependency>
            <!-- Aop관련 -->
            <dependency>
                <groupId>org.aspectj</groupId>
                <artifactId>aspectjweaver</artifactId>
                <version>1.8.10</version>
            </dependency>
            <dependency>
                <groupId>jstl</groupId>
                <artifactId>jstl</artifactId>
                <version>1.2</version>
            </dependency>
            <dependency>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-databind</artifactId>
                <version>2.8.6</version>
            </dependency>
        </dependencies>
</project>

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
<?xml version="1.0" encoding="UTF-8"?>
  <display-name>spring0418_js</display-name>
   <!-- Filter -->
  <filter>
    <filter-name>CharacterEncodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>EUC-KR</param-value>
    </init-param>
    <init-param>
      <param-name>forceEncoding</param-name>
      <param-value>true</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>CharacterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  <servlet>
   <servlet-name>kosta</servlet-name>
   <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  </servlet>
  <servlet-mapping>
   <servlet-name>kosta</servlet-name>
   <url-pattern>/</url-pattern>
  </servlet-mapping>
   
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
 
</web-app>

kosta-servlet.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
<?xml version="1.0" encoding="UTF-8"?>
 
 
    <context:component-scan base-package="or.kosta.mvc"/>
    <mvc:annotation-driven/>
    <mvc:resources location="/resources/" mapping="/resources/**"/>
     
    <!-- dataSource setting -->
    <bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
    <property name="jndiName" value="java:comp/env/jdbc/myoracle"></property>
    </bean>
    <!-- MyBatis config,mapper setting -->
    <bean id="factoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="configLocation" value="classpath:or/kosta/config/config.xml"/>
        <property name="mapperLocations" value="classpath*:or/kosta/mapper/*.xml"/>
    </bean>
    <!-- MyBatis Template configure -->
    <bean id="ss" class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg ref="factoryBean"/>
    </bean>
     
    <!-- multipartResolver 추가 : 파일 업로드를 하기 위해서 꼭 필요한 객체  -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"></bean>
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
 
</beans>

or.kosta.config/config.xml

1
2
3
4
5
6
7
8
9
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
<configuration>
    <typeAliases>
        <typeAlias type="or.kosta.vo.MemberVO" alias="mvo" />
    </typeAliases>
</configuration>

or.kosta.mapper/member.xml

1
2
3
4
5
6
7
8
9
10
11
12
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  <mapper namespace="member">
    <insert id="add" parameterType="mvo">
    insert into member2 values(member2_seq.nextVal,#{id},#{pwd},#{name},sysdate)
    </insert>
    <select id="check" resultType="int" parameterType="String">
    select count(*) cnt from member2 where id=#{id}
    </select>
  </mapper>

or.kosta.Controller/DefaultController.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package or.kosta.mvc.controller;
 
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
 
@Controller
public class DefaultController {
 
    //기본 페이지 설정
    @RequestMapping(value= {"/index","/"})
    public String defaultPage() {
        System.out.println("test");
        return "index";
    }
    @RequestMapping(value="/myindex")
    public String myDefaultView() {
        return "index";
    }
}

or.kosta.Controller/javaScript01Controller.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
package or.kosta.mvc.controller;
 
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 org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
 
import or.kosta.mvc.dao.MemberDao;
import or.kosta.vo.MemberVO;
 
@Controller
public class JavaScript01Controller {
    @Autowired
    private MemberDao memberDao;
     
    @RequestMapping(value = "/form")
    public String form() {
        return "form";
    }
     
    @RequestMapping(value="/memberProcess")
    public String memberProcess(String id, Model m) {
        StringBuffer out = new StringBuffer();
        System.out.println(id);
        int num= memberDao.getCheck(id);
        System.out.println(num);
        if(num==0) {
            out.append("사용가능한아이디입니다.");
        }else {
            out.append("중복된 아이디입니다.");
        }
        m.addAttribute("msg",out.toString());
        return "ex8_ajaxData";
    }
     
    @GetMapping("/ex8_ajax")
    public String ajax() {
        return "ex8_ajax";
    }
     
    @RequestMapping(value="/ajaxData1")
    public String ajaxData(String subject,Model m) {
        System.out.println("subject :"+subject);
        StringBuffer out = new StringBuffer();
        if(subject.equals("자바")) {
            out.append("SCJP,SCJD");
        }else if(subject.toUpperCase().equals("C")) {
            out.append("정보처리");
        }else if(subject.equals("오라클")) {
            out.append("OCP");
        }else {
            out.append("준비중입니다.");
        }
        m.addAttribute("msg",out.toString());
        return "ex8_ajaxData";
    }
 
}

or.kosta.dao/MemberDao.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package or.kosta.mvc.dao;
 
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
 
import or.kosta.vo.MemberVO;
//
@Repository
public class MemberDao {
    @Autowired
    private SqlSessionTemplate ss;
     
    public void add(MemberVO mvo) {
        ss.insert("member.add",mvo);
    }
    public int getCheck(String id) {
        return ss.selectOne("member.check",id);
    }
     
}

or.kosta.vo/MemberVO.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
package or.kosta.vo;
 
public class MemberVO {
    private int num;
    private String id,pwd,name,mdate;
     
    public int getNum() {
        return num;
    }
    public void setNum(int num) {
        this.num = num;
    }
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getPwd() {
        return pwd;
    }
    public void setPwd(String pwd) {
        this.pwd = pwd;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getMdate() {
        return mdate;
    }
    public void setMdate(String mdate) {
        this.mdate = mdate;
    }
     
}

ex8_ajax.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=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html>
 
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>Insert title here</title>
<script type="text/javascript">
    var xhr; //브라우저별 XMLHttpRequest 객체를 저장할 전역변수
    function test(){
        var param = document.getElementById("subject").value;
//      var s = subject.value;
//      s = "subject="+s;
//      var param = "subject="+encodeURIComponent(s);
        //현재 브라우져에 따라 XMLHttpRequest,또는 XMLHTTP를 구별하여 생성한다.
        if(window.ActiveXObject){
            xhr = new ActiveXObject("Microsoft.XMLHTTP");
        }else{
            xhr = new XMLHttpRequest();
        }
        //서버로부터 결과가 도착할 때 수행하는 함수 지정 (콜백함수)
        xhr.onreadystatechange = res;
         
        //서버에게 호출하기 위한 준비
        xhr.open("GET","ajaxData1?subject="+param, true);//전송방식,주소,비동기식(true),동기식(false)
//      xhr.open("post","test1.jsp");
//      xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
        //서버에게 요청보내기
        xhr.send(null); //우린 get방식으로 보내기로 했기 때문에 인자는 반드시 null을 이어야한다.
        //post라면 null이 아니라, 보내고자 하는 파라미터를 문자열로 넣어야 한다.
//      xhr.send(s);
         
    }
    //서버로부터 전달되는 결과가 도착하는 메서드
    function res(){
        if(xhr.readyState==4){//서버로부터 데이터 처리가 완료된 경우
            if(xhr.status==200){//정상적인 처리인 경우
                document.getElementById("txt");
                txt.innerHTML = xhr.responseText;
                //alert(xhr.responseText);
            }else{
                alert("실패" + xhr.status);
            }
        }
    }
     
</script>
</head>
 
    <div style="width: 300px; height: 300px; margin: auto;">
    과목 : <input type="text" name="subject" id="subject"/>
    <input type="button" value="Ajax테스트" onclick="test()"/>
    <p>관련시험 :
    <div id="txt"></div>
    </div>

ex8_ajaxData.jsp

1
2
3
4
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%-- ex8_ajaxData.jsp --%>
${msg}


'학원수업 > Spring' 카테고리의 다른 글

학원 33~35일차 복습(4/27,5/2,5/3)  (0) 2018.04.27
학원 32일차 복습(4/26)  (0) 2018.04.27
학원 24일차 복습(4/16)  (0) 2018.04.16
학원 23일차 복습(4/13)  (0) 2018.04.13
학원 22일차 복습(4/12)  (0) 2018.04.12

이론


서브쿼리 (단일행,다중행)

-하나이상의 테이블에서 검색한 결과를 다른 테이블에 전달하여 새로운 결과를 검색하는 경우에 사용한다.


1.단일행 서브쿼리 : 하나의 행만 검색해서 메인쿼리에 보내는 것을 말한다.


2.다중행 서브쿼리

서브쿼리에서 반환되는 결과가 하나 이상의 행일때 사용.

반드시 다중행 연산자(Multiple Row Operator)와 함께 사용.

<다중행 연산자>

IN: 메인쿼리의 비교조건이 서브쿼리의 결과중에서 하나라도 일치하면 참.

ANY,SOME: 메인쿼리의 비교조건이 서브쿼리의 검색결과와 하나 이상이 일치하면 참

ALL: 메인쿼리의 비교조건이 서브쿼리의 검색 결과와 모든 값이 일치하면 참

EXIST: 메인쿼리의 비교조건이 서브쿼리의 결과중에서 만족하는 값이 하나라도 존재하면 참


ALL연산자: 메인조건의 비교조건이 서브쿼리에서 검색한 결과값과 모두 일치하면 참이 된다.

찾아진 값에 대해서 AND연산을 해서 모두 참이면 참이되는 셈이다.


ANY연산자

메인쿼리의 비교조건이 서브쿼리의 검색결과와 하나 이상이 일치하면 참이된다.

ANY하면 "비교값 중 하나보다 크냐"하고 묻는 것이 된다.

즉 그값들 중 어느하나보다 더 크면, 그 값들중 최소값보다 더 크면 참이된다.


사진불러올때 경로설정 주의하기!

자바스크립트 호이스팅 : Hoisting은 선언을 맨 위로 이동시키는 JavaScript의 기본 동작

선언시 var 대신 let으로 선언하면  Hoisting 일어나지 않음




실습


ex2.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html>
 
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>Insert title here</title>
<script src="resources/js/myfunc.js"></script>
<script>
//  function changeImg(imgSrc){
//      console.log(imgSrc);
//      document.getElementById('myImage').src="resources/img/"+imgSrc;
//  }
</script>
</head>
 
<button onclick="changeImg('pic_bulbon.gif')">Turn on the light</button>
 
<img id="myImage" src="resources/img/pic_bulboff.gif" style="width:100px">
 
<button onclick="changeImg('pic_bulboff.gif')">Turn off the light</button>

ex3.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html>
 
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>Insert title here</title>
<script>
function sumNum(){
var x, y, z; 
x = document.getElementById('x').value;
y = document.getElementById('y').value;
//parseInt(문자열정수,10)
z = parseInt(x,10) + parseInt(y,10);
document.getElementById('res').innerHTML=z;
}
</script>
</head>
 
<input type="number" name="x" id="x" step="1" max="10">
<input type="number" name="y" id="y" step="1" max="10">
<p id="res"></p>
<input  type="button" value="연산" onclick="sumNum()">

ex4.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
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html>
 
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>Insert title here</title>
<style>
    #demo{width: 300px; background: orange; color: #ffffff;}
</style>
<script>
var x = 0; //전역변수
function sum(){
    x += 5;
    document.getElementById('res').innerHTML=x;
    document.getElementById('res2').value=x;
    }
</script>
</head>
 
<h2>The += Operator</h2>
<input  type="button" value="연산" onclick="sum()">
<p id="res"></p>
<input type="number" value="0" id="res2">

ex5.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
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html>
 
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>Insert title here</title>
<!-- 브라우저가 DOM객체를 포함한 리소스 모두 읽어 올때까지 자바스크립트 객체를 대기 시키는 함수를 사용해서 해결
    이벤트: onload     -->
<script>
    window.onload=function(){
        let car = {
                type : "Fiat",
                model : "500",
                color : "white",
                printCar : function() {
                    let printCarMsg = "Type : " + car.type;
                    printCarMsg += "model : " + car.model;
                    printCarMsg += "color : " + car.color;
                    console.log("printCarMsg:" + printCarMsg);
                    document.getElementById('res').innerHTML = printCarMsg;
                }
            };
            console.log("Type : " + car.type);
            car.printCar();
         
    }
</script>
</head>
 
    <p id="res"></p>

ex6_array.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
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html>
 
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>Insert title here</title>
<style>
    #res {width: 300px; height: 300px; margin: auto;
    background-color: pink;
    border: 1px solid blue;
    }
</style>
<script>
    var color = ["red", "green", "blue","pink","orange"];
    var i=0;
window.onload=function(){
    var inter = setInterval(function(){
            document.getElementById("res").style.backgroundColor=color[i];
            console.log(i+":"+color[i]+":"+color.length);
            if(i<(color.length-1)){
                i++;
            }else{
                i=0;
                //clearInterval(inter); //interval을 삭제
            }
    },1000);   
};
</script>
</head>
 
<div id="res"></div>


'학원수업 > Spring' 카테고리의 다른 글

학원 32일차 복습(4/26)  (0) 2018.04.27
학원 26일차 복습(4/18)  (0) 2018.04.18
학원 23일차 복습(4/13)  (0) 2018.04.13
학원 22일차 복습(4/12)  (0) 2018.04.12
학원 21일차 복습(4/11)  (0) 2018.04.11

이론


조건 함수

DECODE 함수: 오라클에서만 제공하는 유용한 SQL함수

DECODE(기준값,조건1,결과1,조건2,결과2,...,그외의 결과)"컬럼명"


CASE함수 : DECADE기능을 확장한 함수,

CASE [기준값] WHEN 조건1 THEN 결과1

             WHEN 조건2 THEN 결과2

             ...

             ELSE 그 외의 결과

             END "컬럼명"


DECODE 함수는 표현식, 컬럼값이 "=" 비교를 통해 조건과 일치하는 경우에만 다른 값으로 대처할 수 있다.

그러나 CASE 함수는 산술연산, 관계연산, 논리연산과 같은 다양한 비교가 가능하다.

WHEN 절에서 표현식을 다양하게 정의할 수 있다.


변환함수

TO_CHAR(날짜|숫자, '형식') : 날짜 또는 숫자를 지정한 형식의 문자열로 변환

TO_DATE(날짜형식의 문자열, '형식') : 날짜형식의 문자열을 지정한 형식의 날짜로 변환,시간까지 표현***

TO_DATE('09.10.12 12:30:00','YY.MM.DD HH:MI:SS')

TO_NUMBER(숫자형식의 문자열) : 숫자형식의 문자열이 숫자로 변환

TO_NUMBER('100') => 100


날짜 형식

scc , cc : 세기 표현

year : 년도를 영어로 표현

yyyy, yyy, yy, y : 년도를 자릿수로 자른다

bc, ad : 서기 등으로 표시

q : 분기 표시

mm : 두자리로 월표시

month: 영어로 표시

mon: 영어로 3자리로 월표시

rm: 로마자로 표시 i, ii. xi

ww: 1년기준 몇째주 표시

w:한달기준 몇째주 표시

ddd: 365(1년기준 ) 의 몇째 일

dd: 날짜를 두자리로 표시

d: 요일을 숫자로 표시

dy : 요일 한자리로 표시

day: 요일 표시

am, pm, a.m. , p.m. : 오전오후 표시

hh, hh12 : 12시 기준으로 표시

hh24 : 24시 기준으로 표시

/, "of" : 날짜의 중간에 문자 표시 -> to_char(to_date('19951201', 'yyyymmdd'),'yyyy "of" mm/dd')

spth : 날짜를 영문 서수로 표시

sp : 날짜를 영문 숫자로 표시


날짜에 연산되는 ROUND/TRUNC 함수


특정 날짜와 연산되는 함수

TO_YMINTERVAL, TO_DSINTERVAL


 ***다중행함수 ***

계산함수,집계함수,그룹함수

SUM,AVG,COUNT,MAX,MIN 함수

GROUP BY 칼럼명,... --정렬작업포함



NVL : null값을 다른 것으로 바꿔줌, 컬럼하나 단독적용 함수

AVG: COUNT 영향 널포함 꼭넣어야함

COUNT : 널을 포함하지 않음('*'를 사용하면 NULL도 카운트)


***Join(조인)***

사용하는 컬럼이 두 개 이상의 테이블에 존재하는 경우 사용되는 고급 쿼리 명령

32개까지 가능


종류

1.eque(inner) join : 조인되는 테이블 간의 조건에 만족하는 행만을 추출

2.outer join(left & right) : 조인되는 테이블 간의 조건에 만족하는 행과 마스터 테이블의 모든 데이터가 추출

3.cross join : 조인되는 테이블간의 어떤 관계도 없는 경우(table*table)->카디션 프로덕트

4.self join : 자기 자신의 테이블과 조인되는 경우


문법

1.T-SQL 문법: where조건절, 테이블명을 나열하여 표현

-select~ : 원하는 컬럼 나열

-from~ : 사용한 컬럼을 가진 테이블 나열

-where~ : 사용된 테이블간의 관계 또는 조건을 표현

2.Ansi 문법 : on조건절, 서술형태의 표현

조인되는 테이블간의 관계컬럼명이 같은 경우! -ansi


OUTER JOIN

1) LEFT OUTER JOIN

먼저 표기된 좌측 테이블에 해당하는 데이터를 먼저 읽은 후, 나중 표기된 우측 테이블에서 JOIN 대상 데이터를 읽어 온다.

Table A와 B가 있을 때 (Table 'A'가 기준이 됨),

A와 B를 비교해서 B의 JOIN 칼럼에서 같은 값이 있을 때 그 해당 데이터를 가져오고,

B의 JOIN 칼럼에서 같은 값이 없는 경우에는 B테이블에서 가져오는 칼럼들은 NULL값으로 채운다.


2) RIGHT OUTER JOIN

LEFT JOIN과 반대로 우측테이블이 기죽이 되어 결과를 생성한다.

TABLE A와 B가 있을때 (TABLE 'B'가 기준이 됨)



실습


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
  <modelVersion>4.0.0</modelVersion>
  <groupId>spring0413_resultMap</groupId>
  <artifactId>spring0413_resultMap</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  <build>
    <sourceDirectory>src</sourceDirectory>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.7.0</version>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>
      <plugin>
        <artifactId>maven-war-plugin</artifactId>
        <version>3.0.0</version>
        <configuration>
          <warSourceDirectory>WebContent</warSourceDirectory>
        </configuration>
      </plugin>
    </plugins>
  </build>
   <dependencies>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-context</artifactId>
                <version>4.3.6.RELEASE</version>
            </dependency>
            <!-- spring-jdbc for MyBatis -->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-jdbc</artifactId>
                <version>4.3.6.RELEASE</version>
            </dependency>
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis</artifactId>
                <version>3.4.2</version>
            </dependency>
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis-spring</artifactId>
                <version>1.3.1</version>
            </dependency>
            <!-- Web MVC -->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-web</artifactId>
                <version>4.3.6.RELEASE</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-webmvc</artifactId>
                <version>4.3.6.RELEASE</version>
            </dependency>
            <dependency>
                <groupId>commons-fileupload</groupId>
                <artifactId>commons-fileupload</artifactId>
                <version>1.3.3</version>
            </dependency>
            <!-- Aop관련 -->
            <dependency>
                <groupId>org.aspectj</groupId>
                <artifactId>aspectjweaver</artifactId>
                <version>1.8.10</version>
            </dependency>
            <dependency>
                <groupId>jstl</groupId>
                <artifactId>jstl</artifactId>
                <version>1.2</version>
            </dependency>
            <dependency>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-databind</artifactId>
                <version>2.8.6</version>
            </dependency>
        </dependencies>
</project>

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
<?xml version="1.0" encoding="UTF-8"?>
  <display-name>spring0413_resultMap</display-name>
   <!-- Filter -->
  <filter>
    <filter-name>CharacterEncodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>EUC-KR</param-value>
    </init-param>
    <init-param>
      <param-name>forceEncoding</param-name>
      <param-value>true</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>CharacterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  <servlet>
   <servlet-name>kosta</servlet-name>
   <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  </servlet>
  <servlet-mapping>
   <servlet-name>kosta</servlet-name>
   <url-pattern>/</url-pattern>
  </servlet-mapping>
   
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
 
</web-app>

kosta-servlet.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
<?xml version="1.0" encoding="UTF-8"?>
 
 
    <context:component-scan base-package="or.kosta.mvc"/>
    <mvc:annotation-driven/>
    <mvc:resources location="/resources/" mapping="/resources/**"/>
     
    <!-- dataSource setting -->
    <bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
    <property name="jndiName" value="java:comp/env/jdbc/myoracle"></property>
    </bean>
    <!-- MyBatis config,mapper setting -->
    <bean id="factoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="configLocation" value="classpath:or/kosta/config/config.xml"/>
        <property name="mapperLocations" value="classpath*:or/kosta/mapper/*.xml"/>
    </bean>
    <!-- MyBatis Template configure -->
    <bean id="ss" class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg ref="factoryBean"/>
    </bean>
     
    <!-- multipartResolver 추가 : 파일 업로드를 하기 위해서 꼭 필요한 객체  -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"></bean>
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
 
</beans>

src/or.kosta.config/config.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
<configuration>
    <typeAliases>
        <typeAlias type="or.kosta.vo.GogekDTO" alias="gvo" />
        <typeAlias type="or.kosta.vo.SearchVO" alias="svo" />
        <typeAlias type="or.kosta.vo.SawonVO" alias="savo" />
        <typeAlias type="or.kosta.vo.DeptVO" alias="deptvo" />
        <typeAlias type="or.kosta.vo.SawonPhoneVO" alias="sphonevo" />
    </typeAliases>
</configuration>

src/or.kosta.mapper/gogek.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  <mapper namespace="gogek">
    <select id="list" resultType="gvo">
    select gobun,goname,gotel,rpad(substr(gojumin,1,7),14,'*') gojumin,godam from gogek
    </select>
    <select id="search" resultType="gvo" parameterType="svo">
    select gobun,goname,gotel,rpad(substr(gojumin,1,7),14,'*') gojumin,godam from gogek
    <if test="searchValue != null">
        <where>
            <choose>
                <when test="searchType == 1">goname like '%'|| #{searchValue} || '%'</when>
                <when test="searchType == 2">gotel like '%'|| #{searchValue} || '%'</when>
                <when test="searchType == 3">gojumin like '%'|| #{searchValue} || '%'</when>
            </choose>
        </where>     
    </if>
    order by 1 desc
    </select>
  </mapper>

src/or.kosta.mapper/sawon.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
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  <mapper namespace="sawon">
    <resultMap type="deptvo" id="deptResultMap">
        <constructor>
            <idArg column="deptno" javaType="java.lang.Integer"/>
            <arg column="dname" javaType="java.lang.String"/>
        </constructor>
        <result property="loc" column="location"/>
    </resultMap>
    <select id="showDept" resultMap="deptResultMap">
        select deptno, dname, loc location from dept order by 1 desc
    </select>
   
   
    <select id="list" resultType="savo">
    select sabun,saname,deptno,sajob,sapay,to_char(sahire,'YYYY-MM-DD') sahire ,sasex,samgr from sawon
    </select>
     
    <!-- resultMap예제 2/Association 예제 1 hasone: 사원한명당 phone을 가지는 관계
        SawonVO에서 SawonPhoneVO를 가지는 관계  private SawonPhoneVO sphonel resultMap의 타입을
        sawonvo로 지정한다.
     -->
     <resultMap type="savo" id="sawonphoneResult">
     <id property="sabun" column="sabun"/>
     <association property="sphone" column="sabun" javaType="sphonevo" select="sawonPhone">
     </association>
     </resultMap>
    <!-- 외부에서 사원이 가지고 있는 폰의 정보를 출력하기 위한 쿼리문을 각각 만든다.
        resultMap에서 select속성으로 아래의 sawonPhone을 읽어와서 sphonevo에 넣어준다.
     -->
     <select id="sawondetail" resultMap="sawonphoneResult" parameterType="int">
        select sabun,saname,sajob from sawon where sabun=#{sabun}
     </select>
     <select id="sawonPhone" resultType="sphonevo">
        select pnum,pmodel,phnum,pdate from sawon_phone where pnum=#{pnum}
     </select>
     
  </mapper>

src/or.kosta.mvc.controller/DefaultController.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package or.kosta.mvc.controller;
 
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
 
@Controller
public class DefaultController {
 
    //기본 페이지 설정
    @RequestMapping(value= {"/index","/"})
    public String defaultPage() {
        System.out.println("test");
        return "index";
    }
    @RequestMapping(value="/myindex")
    public String myDefaultView() {
        return "index";
    }
}

src/or.kosta.mvc.controller/GogekController.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
package or.kosta.mvc.controller;
 
import java.util.List;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
 
import or.kosta.mvc.dao.GvoDao;
import or.kosta.vo.GogekDTO;
import or.kosta.vo.SearchVO;
 
@Controller
public class GogekController {
    @Autowired
    private GvoDao gvoDao;
 
 
    @RequestMapping(value = "/gogekList", method = RequestMethod.GET)
    public String gogekList(Model m) {
        List<GogekDTO> list = gvoDao.getGogekList();
        m.addAttribute("list", list);
        return "gogekList";
    }
     
    @RequestMapping(value="/search")
    public String gogekList(SearchVO vo, Model m) {
        List<GogekDTO> list = gvoDao.getGogekList(vo);
        m.addAttribute("list", list);
        return "gogekList";
    }
 
}

src/or.kosta.mvc.controller/SawonController.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
package or.kosta.mvc.controller;
 
import java.util.List;
 
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 org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
 
import or.kosta.mvc.dao.SawonDao;
import or.kosta.vo.DeptVO;
import or.kosta.vo.SawonVO;
 
@Controller
public class SawonController {
    @Autowired
    private SawonDao sawonDao;
 
 
    @RequestMapping(value = "/sawonList", method = RequestMethod.GET)
    public String sawonList(Model m) {
        List<SawonVO> list = sawonDao.getSawonList();
        m.addAttribute("list", list);
        return "sawonList";
    }
    //1번째 예제 ResultMap
    @GetMapping("/deptList")
    public String deptList(Model m) {
        List<DeptVO> list = sawonDao.getDeptList();
        m.addAttribute("dlist",list);
        return "deptList";
    }
    // 2번째 예제 ResultMap
    @GetMapping("/sphoneForm")
    public String sawonphoneForm() {
        return "sphForm";
    }
    @PostMapping("/sPhone")
    public String sawonPhone(int sabun,Model m) {
        SawonVO v = sawonDao.getSawonPhone(sabun);
        m.addAttribute("sawon",v);
        return "sawonPhone";
    }
 
}

src/or.kosta.mvc.dao/GvoDao.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
package or.kosta.mvc.dao;
 
import java.util.List;
 
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
 
import or.kosta.vo.GogekDTO;
import or.kosta.vo.SearchVO;
//
@Repository
public class GvoDao {
    @Autowired
    private SqlSessionTemplate ss;
     
    public List<GogekDTO> getGogekList(){
        return ss.selectList("gogek.list");
    }
    public List<GogekDTO> getGogekList(SearchVO svo){
        return ss.selectList("gogek.search",svo);
    }
     
}

src/or.kosta.mvc.dao/SawonDao.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
package or.kosta.mvc.dao;
 
import java.util.List;
 
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
 
import or.kosta.vo.DeptVO;
import or.kosta.vo.SawonPhoneVO;
import or.kosta.vo.SawonVO;
//
@Repository
public class SawonDao {
    @Autowired
    private SqlSessionTemplate ss;
     
    public List<SawonVO> getSawonList(){
        return ss.selectList("sawon.list");
    }
    //1번째 ResultMap예제
    public List<DeptVO> getDeptList(){
        return ss.selectList("sawon.showDept");
    }
    public SawonVO getSawonPhone(int sabun) {
        return ss.selectOne("sawon.sawondetail", sabun);
    }
 
}

src/or.kosta.vo/DeptVo.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
package or.kosta.vo;
 
import java.util.List;
 
public class DeptVO {
    private int deptno;
    private String dname,loc;
    private List<SawonVO> sawon;
    public DeptVO() {
    }
    public DeptVO(Integer deptno, String dname) {
        this.deptno = deptno;
        this.dname = dname;
    }
    public int getDeptno() {
        return deptno;
    }
    public void setDeptno(int deptno) {
        this.deptno = deptno;
    }
    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;
    }
    public List<SawonVO> getSawon() {
        return sawon;
    }
    public void setSawon(List<SawonVO> sawon) {
        this.sawon = sawon;
    }
     
     
}

src/or.kosta.vo/GogekVo.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
package or.kosta.vo;
 
public class GogekDTO {
    private int gobun,godam;
    private String goname,gotel,gojumin;
    public int getGobun() {
        return gobun;
    }
    public void setGobun(int gobun) {
        this.gobun = gobun;
    }
    public int getGodam() {
        return godam;
    }
    public void setGodam(int godam) {
        this.godam = godam;
    }
     
    public String getGoname() {
        return goname;
    }
    public void setGoname(String goname) {
        this.goname = goname;
    }
    public String getGotel() {
        return gotel;
    }
    public void setGotel(String gotel) {
        this.gotel = gotel;
    }
    public String getGojumin() {
        return gojumin;
    }
    public void setGojumin(String gojumin) {
        this.gojumin = gojumin;
    }
     
     
     
     
}

src/or.kosta.vo/SawonPhoneVo.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
package or.kosta.vo;
 
public class SawonPhoneVO {
    private int pnum;
    private String pmodel,phnum,pdate;
    public int getPnum() {
        return pnum;
    }
    public void setPnum(int pnum) {
        this.pnum = pnum;
    }
    public String getPmodel() {
        return pmodel;
    }
    public void setPmodel(String pmodel) {
        this.pmodel = pmodel;
    }
    public String getPhnum() {
        return phnum;
    }
    public void setPhnum(String phnum) {
        this.phnum = phnum;
    }
    public String getPdate() {
        return pdate;
    }
    public void setPdate(String pdate) {
        this.pdate = pdate;
    }
     
}

src/or.kosta.vo/SawonVo.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
package or.kosta.vo;
 
public class SawonVO {
    private int sabun,deptno,sapay,samgr;
    private String saname,sajob,sahire,sasex;
    //ResultMap2 Association 예제
    private SawonPhoneVO sphone;
     
    public SawonPhoneVO getSphone() {
        return sphone;
    }
    public void setSphone(SawonPhoneVO sphone) {
        this.sphone = sphone;
    }
    public int getSabun() {
        return sabun;
    }
    public void setSabun(int sabun) {
        this.sabun = sabun;
    }
    public int getDeptno() {
        return deptno;
    }
    public void setDeptno(int deptno) {
        this.deptno = deptno;
    }
    public int getSapay() {
        return sapay;
    }
    public void setSapay(int sapay) {
        this.sapay = sapay;
    }
    public int getSamgr() {
        return samgr;
    }
    public void setSamgr(int samgr) {
        this.samgr = samgr;
    }
    public String getSaname() {
        return saname;
    }
    public void setSaname(String saname) {
        this.saname = saname;
    }
    public String getSajob() {
        return sajob;
    }
    public void setSajob(String sajob) {
        this.sajob = sajob;
    }
    public String getSahire() {
        return sahire;
    }
    public void setSahire(String sahire) {
        this.sahire = sahire;
    }
    public String getSasex() {
        return sasex;
    }
    public void setSasex(String sasex) {
        this.sasex = sasex;
    }
     
}

jsp/sawonList.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=EUC-KR"
    pageEncoding="EUC-KR"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
 
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>list.jsp</title>
<style>
#wrap {
    width: 1000px;
    margin: auto;
}
 
#wrap table {
    width: 100%
}
 
#wrap img {
    width: 110px;
}
</style>
</head>
 
    <div id="wrap">
        <table>
            <tr>
                <td colspan="8">사원리스트</td>
            </tr>
            <tr>
                <td>사원번호</td>
                <td>사원이름</td>
                <td>부서번호</td>
                <td>직책</td>
                <td>급여</td>
                <td>입사일</td>
                <td>성별</td>
                <td>상급자</td>
            </tr>
            <c:forEach var="listv" items="${list}">
                <tr>
                    <td>${listv.sabun}</td>
                    <td>${listv.saname}</td>
                    <td>${listv.deptno}</td>
                    <td>${listv.sajob}</td>
                    <td>${listv.sapay}</td>
                    <td>${listv.sahire}</td>
                    <td>${listv.sasex}</td>
                    <td>${listv.samgr}</td>
                </tr>
            </c:forEach>
        </table>
    </div>

jsp/deptList.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
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
 
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>list.jsp</title>
<style>
#wrap {
    width: 1000px;
    margin: auto;
}
 
#wrap table {
    width: 100%
}
 
#wrap img {
    width: 110px;
}
</style>
</head>
 
    <div id="wrap">
        <table>
            <tr>
                <td colspan="3">부서리스트</td>
            </tr>
            <tr>
                <td>부서번호</td>
                <td>부서이름</td>
                <td>위치번호</td>
            </tr>
            <c:forEach var="e" items="${dlist}">
                <tr>
                    <td>${e.deptno}</td>
                    <td>${e.dname}</td>
                    <td>${e.loc}</td>
                </tr>
            </c:forEach>
        </table>
    </div>

jsp/sphForm.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html>
 
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>Insert title here</title>
<style>
    #wrap{width: 400px; margin: auto;}
</style>
</head>
 
    <div id="wrap">
        <form method="post" action="sPhone">
            사원번호 입력 : <input type="text" name="sabun">
            <input type="submit" value="send">
        </form>
    </div>

jsp/sawonPhone.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html>
 
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>Insert title here</title>
<style>
    #wrap{width: 500px; margin: auto; border: 1px dotted;}
</style>
</head>
 
    <div id="wrap">
        <ul>
            <li>사원번호 : ${sawon.sabun}</li>
            <li>사원직책 : ${sawon.sajob}</li>
            <li>사원이름 : ${sawon.saname}</li>
            <li>폰번호 : ${sawon.sphone.phnum}</li>
            <li>폰모델 : ${sawon.sphone.pmodel}</li>
        </ul>
    </div>


'학원수업 > Spring' 카테고리의 다른 글

학원 26일차 복습(4/18)  (0) 2018.04.18
학원 24일차 복습(4/16)  (0) 2018.04.16
학원 22일차 복습(4/12)  (0) 2018.04.12
학원 21일차 복습(4/11)  (0) 2018.04.11
학원 20일차 복습(4/10)  (0) 2018.04.10

이론



제약조건주는이유: 데이터의 무결성보장, 

컬럼단위 제약조건

낫널은 컬럼단위

DDL에는 TCL이 포함


트랜잭션이란?

■ 트랜잭션이란 단어의 본래 뜻은 '거래'라는 의미

■ 예를 들어 돈을 주었는데 물건을 받지 못한다면, 그 거래는 이루어 지지

못하고 원상태로 복구되어야 함

이와 같이 쪼갤 수 없는 하나의 처리 행위를 원자적 행위라고 함

■ 여기서 쪼갤 수 없다는 말의 의미는 실제로 쪼갤 수 없다기 보다는 만일

쪼개질 경우 시스템에 심각한 오류를 초래할 수 있다는 것


eXERD설치하여 ERD작성


오라클에서 sql문 작성

--cascade: 상위테이블로부터 행을 삭제하고 하나의 삭제 명령어로 그에 대응되는 하위테이블의 해당행을 삭제할 수 있다.


-- 조건절 : where 컬럼명 조건 >> 제한된 행을 출력(데이터 제한)

-- 산술연산자 : +,-,*,/,mod(10,3) =>1

-- 관계연산자 : >,<,>=,<=,=,!=(<>)

-- 논리연산자 : not , and , or

-- 문자열연산자 : like

--between A and B : 범위연산자

--or,in 연산자

--연결 연산자(||)


-- 문자열 연산자) 주로 검색에서 많이 사용이 된다.

-- like (% : 모든 문자열, _ : 한문자


--수학 관련 함수

--power(n2,n1) : 제곱값을 구하기 위한 함수 n2에 대한 n1승의 값을 구함.

--dual => 실험하고 싶을때 // 가상테이블

--SIGN: 인자가 음수인지 양수인지 판단하는 함수

--n<0 : -1 ,n=0 : 0 , n>0 :1 을 리턴함

--mod(n2,n1) : n2나누기 n1의 나머지 값구하기 자바에서 % 동일

--반올림 함수 : ROUND

--자리수를 지정한 버림 : TRUNC

--정수형태 출력 : CEIL(천장,상한값), FLOOR(바닥,하한값)


--문자함수

--lower : 문자열 전체를 소문자로 변환

--upper : 문자열 전체를 대문자로 변환

--initcap : 문자열의 첫번째 문자만 대문자로 변환


--문자 조작 함수

--trim: 좌우측 공백을 제거

--ltrim: 좌측, rtrim: 우측


--INSTR 함수 : 문자열중에서 지정한 특정문자가 포함된 위치를 반환하는 함수

--instr(대상문자열, 찾을문자열, 방향, 검색된결과의 순번)

--방향 : 1이면 왼쪽->오른쪽  // -1이면 오른쪽->왼쪽


--SUBSTR 함수: 문자열의 일부를 추출하는 함수

--substr(문자열,N번째부터,N개);



실습


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
  <modelVersion>4.0.0</modelVersion>
  <groupId>spring0411</groupId>
  <artifactId>spring0412_dynamic</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  <build>
    <sourceDirectory>src</sourceDirectory>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.7.0</version>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>
      <plugin>
        <artifactId>maven-war-plugin</artifactId>
        <version>3.0.0</version>
        <configuration>
          <warSourceDirectory>WebContent</warSourceDirectory>
        </configuration>
      </plugin>
    </plugins>
  </build>
  <dependencies>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-context</artifactId>
                <version>4.3.6.RELEASE</version>
            </dependency>
            <!-- spring-jdbc for MyBatis -->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-jdbc</artifactId>
                <version>4.3.6.RELEASE</version>
            </dependency>
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis</artifactId>
                <version>3.4.2</version>
            </dependency>
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis-spring</artifactId>
                <version>1.3.1</version>
            </dependency>
            <!-- Web MVC -->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-web</artifactId>
                <version>4.3.6.RELEASE</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-webmvc</artifactId>
                <version>4.3.6.RELEASE</version>
            </dependency>
            <dependency>
                <groupId>commons-fileupload</groupId>
                <artifactId>commons-fileupload</artifactId>
                <version>1.3.3</version>
            </dependency>
            <!-- Aop관련 -->
            <dependency>
                <groupId>org.aspectj</groupId>
                <artifactId>aspectjweaver</artifactId>
                <version>1.8.10</version>
            </dependency>
            <dependency>
                <groupId>jstl</groupId>
                <artifactId>jstl</artifactId>
                <version>1.2</version>
            </dependency>
            <dependency>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-databind</artifactId>
                <version>2.8.6</version>
            </dependency>
        </dependencies>
</project>

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
<?xml version="1.0" encoding="UTF-8"?>
  <display-name>spring0411</display-name>
 <!-- Filter -->
  <filter>
    <filter-name>CharacterEncodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>EUC-KR</param-value>
    </init-param>
    <init-param>
      <param-name>forceEncoding</param-name>
      <param-value>true</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>CharacterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  <servlet>
   <servlet-name>kosta</servlet-name>
   <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  </servlet>
  <servlet-mapping>
   <servlet-name>kosta</servlet-name>
   <url-pattern>/</url-pattern>
  </servlet-mapping>
   
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
 
</web-app>

kosta-servlet.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
<?xml version="1.0" encoding="UTF-8"?>
 
 
    <context:component-scan base-package="or.kosta.mvc"/>
    <mvc:annotation-driven/>
    <mvc:resources location="/resources/" mapping="/resources/**"/>
     
    <!-- dataSource setting -->
    <bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
    <property name="jndiName" value="java:comp/env/jdbc/myoracle"></property>
    </bean>
    <!-- MyBatis config,mapper setting -->
    <bean id="factoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="configLocation" value="classpath:or/kosta/config/config.xml"/>
        <property name="mapperLocations" value="classpath*:or/kosta/mapper/*.xml"/>
    </bean>
    <!-- MyBatis Template configure -->
    <bean id="ss" class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg ref="factoryBean"/>
    </bean>
     
    <!-- multipartResolver 추가 : 파일 업로드를 하기 위해서 꼭 필요한 객체  -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"></bean>
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
 
</beans>

src/or.kosta.config/config.xml

1
2
3
4
5
6
7
8
9
10
11
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
<configuration>
    <typeAliases>
        <typeAlias type="or.kosta.vo.gogekDTO" alias="gvo" />
        <typeAlias type="or.kosta.vo.SearchVO" alias="svo" />
    </typeAliases>
  
</configuration>

src/or.kosta.mapper/gogek.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  <mapper namespace="gogek">
    <select id="list" resultType="gvo">
    select gobun,goname,gotel,rpad(substr(gojumin,1,7),14,'*') gojumin,godam from gogek
    </select>
    <select id="search" resultType="gvo" parameterType="svo">
    select gobun,goname,gotel,rpad(substr(gojumin,1,7),14,'*') gojumin,godam from gogek
    <if test="searchValue != null">
        <where>
            <choose>
                <when test="searchType == 1">goname like '%'|| #{searchValue} || '%'</when>
                <when test="searchType == 2">gotel like '%'|| #{searchValue} || '%'</when>
                <when test="searchType == 3">gojumin like '%'|| #{searchValue} || '%'</when>
            </choose>
        </where>     
    </if>
    order by 1 desc
    </select>
  </mapper>

src/or.kosta.mvc.controller/DefaultController.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package or.kosta.mvc.controller;
 
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
 
@Controller
public class DefaultController {
 
    //기본 페이지 설정
    @RequestMapping(value= {"/index","/"})
    public String defaultPage() {
        System.out.println("test");
        return "index";
    }
    @RequestMapping(value="/myindex")
    public String myDefaultView() {
        return "index";
    }
}

src/or.kosta.mvc.controller/GogekController.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
package or.kosta.mvc.controller;
 
import java.util.List;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
 
import or.kosta.mvc.dao.GvoDao;
import or.kosta.vo.SearchVO;
import or.kosta.vo.gogekDTO;
 
@Controller
public class GogekController {
    @Autowired
    private GvoDao gvoDao;
 
 
    @RequestMapping(value = "/gogekList", method = RequestMethod.GET)
    public String gogekList(Model m) {
        List<gogekDTO> list = gvoDao.getGogekList();
        m.addAttribute("list", list);
        return "gogekList";
    }
     
    @RequestMapping(value="/search")
    public String gogekList(SearchVO vo, Model m) {
        List<gogekDTO> list = gvoDao.getGogekList(vo);
        m.addAttribute("list", list);
        return "gogekList";
    }
 
}

src/or.kosta.mvc.dao/GvoDao.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
package or.kosta.mvc.dao;
 
import java.util.List;
 
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
 
import or.kosta.vo.SearchVO;
import or.kosta.vo.gogekDTO;
//
@Repository
public class GvoDao {
    @Autowired
    private SqlSessionTemplate ss;
     
    public List<gogekDTO> getGogekList(){
        return ss.selectList("gogek.list");
    }
    public List<gogekDTO> getGogekList(SearchVO svo){
        return ss.selectList("gogek.search",svo);
    }
     
}

src/or.kosta.vo/gogekDTO.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
package or.kosta.vo;
 
public class gogekDTO {
    private int gobun,godam;
    private String goname,gotel,gojumin;
    public int getGobun() {
        return gobun;
    }
    public void setGobun(int gobun) {
        this.gobun = gobun;
    }
    public int getGodam() {
        return godam;
    }
    public void setGodam(int godam) {
        this.godam = godam;
    }
     
    public String getGoname() {
        return goname;
    }
    public void setGoname(String goname) {
        this.goname = goname;
    }
    public String getGotel() {
        return gotel;
    }
    public void setGotel(String gotel) {
        this.gotel = gotel;
    }
    public String getGojumin() {
        return gojumin;
    }
    public void setGojumin(String gojumin) {
        this.gojumin = gojumin;
    }
     
     
     
     
}

src/or.kosta.vo/searchVO.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package or.kosta.vo;
 
public class SearchVO {
    private String searchType, searchValue;
 
    public String getSearchType() {
        return searchType;
    }
 
    public void setSearchType(String searchType) {
        this.searchType = searchType;
    }
 
    public String getSearchValue() {
        return searchValue;
    }
 
    public void setSearchValue(String searchValue) {
        this.searchValue = searchValue;
    }
     
     
}

gogekList.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
56
57
58
59
60
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
 
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>list.jsp</title>
<style>
#wrap {
    width: 500px;
    margin: auto;
}
 
#wrap table {
    width: 100%
}
 
#wrap img {
    width: 110px;
}
</style>
</head>
 
    <div id="wrap">
        <table>
            <tr>
                <td colspan="5">고객리스트</td>
            </tr>
            <tr>
                <td>고객번호</td>
                <td>고객이름</td>
                <td>전화번호</td>
                <td>주민번호</td>
                <td>담당자번호</td>
            </tr>
            <c:forEach var="listv" items="${list}">
                <tr>
                    <td>${listv.gobun}</td>
                    <td>${listv.goname}</td>
                    <td>${listv.gotel}</td>
                    <td>${listv.gojumin}</td>
                    <td>${listv.godam}</td>
                </tr>
            </c:forEach>
            <tr>
                <td colspan="5">
                    <form method="post" action="search">
                    <select name="searchType">
                        <option value="1">고객이름</option>
                        <option value="2">전화번호</option>
                        <option value="3">주민번호</option>
                    </select> 
                    <input type="text" name="searchValue">
                    <input type="submit" value="검색">
                    </form>
                </td>
            </tr>
        </table>
    </div>


'학원수업 > Spring' 카테고리의 다른 글

학원 24일차 복습(4/16)  (0) 2018.04.16
학원 23일차 복습(4/13)  (0) 2018.04.13
학원 21일차 복습(4/11)  (0) 2018.04.11
학원 20일차 복습(4/10)  (0) 2018.04.10
학원 19일차 복습(4/9)  (0) 2018.04.09

이론


pom.xml에 dependency 하기 -> web.xml에 필터설정하기, servlet설정하기 ->context.xml에 연결할 DB설정하기

->build path에서 톰캣에 ojdbc6.jar 추가하기*****  -> servlet.xml 생성하고 dataSource setting, MyBatis config,mapper setting , MyBatis Template configure, multipartResolver 추가하기 

vo생성하기 -> dao생성하기 ->config.xml생성하기 -> mapper.xml 생성하기-> Controller생성하기 -> jsp생성하기


파일 다운로드 방법(Controller 에서 사용)

파일의 버퍼 설정

다운로드 요청에 대한 HandlerMapping

이미 업로드된 경로에서 파일 다운로드를 할 것이기 때문에 리스트나 뷰에서 해당 파일의 이름을 받아와야 한다.

fileDown.kosta?fileName=파일이름

-> @RequestParam("fileName") String fileName

ServletContext와 파일의 절대경로를 얻어내기위해서

-> HttpSession session, HttpServletRequest request

다운로드란 브라우저와 Stream으로 연결되어서 통신되어야 하기 때문에..

-> HttpServletResponse response

applicationContext 객체를 request로 부터 얻어냄

업로드된 경로 얻음

그 경로로 파일객체를 생성

FileInputStream 스트림으로 읽어옴

요청객체로부터 연결될 브라우저의 마임타입을 얻어냄

만약 마임타입값이 없으면 그냥 디폴트로 스트림으로 연결

지정된 마임타입 세팅

다운로드될 파일의 길이 세팅

다운로드 Type을 설정함

위의 다운로드 타입의 정보를 해더로 설정

브라우저로부터 스트림을 연결

버퍼를 끼워서 빠르게 전달 목적

이제 브라우저로 보내고, 자원 닫으면 끝





실습


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
  <modelVersion>4.0.0</modelVersion>
  <groupId>spring0411</groupId>
  <artifactId>spring0411</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  <build>
    <sourceDirectory>src</sourceDirectory>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.7.0</version>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>
      <plugin>
        <artifactId>maven-war-plugin</artifactId>
        <version>3.0.0</version>
        <configuration>
          <warSourceDirectory>WebContent</warSourceDirectory>
        </configuration>
      </plugin>
    </plugins>
  </build>
  <dependencies>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-context</artifactId>
                <version>4.3.6.RELEASE</version>
            </dependency>
            <!-- spring-jdbc for MyBatis -->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-jdbc</artifactId>
                <version>4.3.6.RELEASE</version>
            </dependency>
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis</artifactId>
                <version>3.4.2</version>
            </dependency>
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis-spring</artifactId>
                <version>1.3.1</version>
            </dependency>
            <!-- Web MVC -->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-web</artifactId>
                <version>4.3.6.RELEASE</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-webmvc</artifactId>
                <version>4.3.6.RELEASE</version>
            </dependency>
            <dependency>
                <groupId>commons-fileupload</groupId>
                <artifactId>commons-fileupload</artifactId>
                <version>1.3.3</version>
            </dependency>
            <!-- Aop관련 -->
            <dependency>
                <groupId>org.aspectj</groupId>
                <artifactId>aspectjweaver</artifactId>
                <version>1.8.10</version>
            </dependency>
            <dependency>
                <groupId>jstl</groupId>
                <artifactId>jstl</artifactId>
                <version>1.2</version>
            </dependency>
            <dependency>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-databind</artifactId>
                <version>2.8.6</version>
            </dependency>
        </dependencies>
</project>

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
<?xml version="1.0" encoding="UTF-8"?>
  <display-name>spring0411</display-name>
 <!-- Filter -->
  <filter>
    <filter-name>CharacterEncodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>EUC-KR</param-value>
    </init-param>
    <init-param>
      <param-name>forceEncoding</param-name>
      <param-value>true</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>CharacterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  <servlet>
   <servlet-name>kosta</servlet-name>
   <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  </servlet>
  <servlet-mapping>
   <servlet-name>kosta</servlet-name>
   <url-pattern>/</url-pattern>
  </servlet-mapping>
   
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
 
</web-app>

kosta-servlet.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
<?xml version="1.0" encoding="UTF-8"?>
 
 
    <context:component-scan base-package="or.kosta.mvc"/>
    <mvc:annotation-driven/>
    <mvc:resources location="/resources/" mapping="/resources/**"/>
     
    <!-- dataSource setting -->
    <bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
    <property name="jndiName" value="java:comp/env/jdbc/myoracle"></property>
    </bean>
    <!-- MyBatis config,mapper setting -->
    <bean id="factoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="configLocation" value="classpath:or/kosta/config/config.xml"/>
        <property name="mapperLocations" value="classpath*:or/kosta/mapper/*.xml"/>
    </bean>
    <!-- MyBatis Template configure -->
    <bean id="ss" class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg ref="factoryBean"/>
    </bean>
     
    <!-- multipartResolver 추가 : 파일 업로드를 하기 위해서 꼭 필요한 객체  -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"></bean>
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
 
</beans>

src/or.kosta.config/config.xml

1
2
3
4
5
6
7
8
9
10
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
<configuration>
    <typeAliases>
        <typeAlias type="or.kosta.vo.TBoardDTO" alias="tvo" />
    </typeAliases>
  
</configuration>

src/or.kosta.mapper/tboardMap.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  <mapper namespace="tboardMap">
    <insert id="add" parameterType="tvo">
    insert into tvo values(tvo_seq.nextVal,#{title},#{writer},#{content},#{pwd},#{mfile})
    </insert>
    <select id="list" resultType="tvo">
    select num,title,writer,mfile from tvo order by 1 desc
    </select>
    <select id="detail" parameterType="int" resultType="tvo">
    select num,title,writer,content,mfile,pwd from tvo where num=#{num}
    </select>
    <update id="up" parameterType="tvo">
    update tvo set title=#{title},writer=#{writer},content=#{content},mfile=#{mfile},pwd=#{pwd} where num=#{num}
    </update>
    <delete id="del" parameterType="int">
        delete from tvo where num=#{num}
    </delete>
  </mapper>

src/or.kosta.mvc.controller/DefaultController.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package or.kosta.mvc.controller;
 
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
 
@Controller
public class DefaultController {
 
    //기본 페이지 설정
    @RequestMapping(value= {"/index","/"})
    public String defaultPage() {
        System.out.println("test");
        return "index";
    }
    @RequestMapping(value="/myindex")
    public String myDefaultView() {
        return "index";
    }
}

src/or.kosta.mvc.controller/TboardController.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
158
159
160
161
162
163
164
165
166
167
168
169
170
171
package or.kosta.mvc.controller;
 
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
 
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
 
import or.kosta.mvc.dao.TvoDao;
import or.kosta.vo.TBoardDTO;
 
@Controller
public class TBoardController {
    @Autowired
    private TvoDao tvoDao;
 
    @RequestMapping(value = "/form")
    public String form() {
        return "form";
    }
 
    @RequestMapping(value = "/tBoardProcess", method = RequestMethod.POST)
    public ModelAndView save(TBoardDTO tvo, HttpServletRequest request) {
        HttpSession session = request.getSession();
        String r_path = session.getServletContext().getRealPath("/");
        System.out.println(r_path);
        String img_path = "resources\\img\\";
        System.out.println(img_path);
        StringBuffer path = new StringBuffer();
        path.append(r_path).append(img_path);
        String oriFn = tvo.getMfile1().getOriginalFilename();
        path.append(oriFn);
        System.out.println(path);
        // 파일 업로드
        File f = new File(path.toString());
        try {
            tvo.getMfile1().transferTo(f);
        } catch (IllegalStateException | IOException e) {
            e.printStackTrace();
        }
        tvo.setMfile(oriFn);
        tvoDao.add(tvo);
        ModelAndView mav = new ModelAndView("redirect:/list");
        return mav;
    }
 
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public ModelAndView list() {
        ModelAndView mav = new ModelAndView();
        mav.setViewName("list");
        List<TBoardDTO> listvo = tvoDao.getList();
        mav.addObject("list", listvo);
        return mav;
    }
 
    // 파일의 버퍼 설정
    private static final int BUFFER_SIZE = 4096;
 
    // 다운로드 요청에 대한 HandlerMapping
    // 이미 업로드된 경로에서 파일 다운로드를 할 것이기 때문에
    // 리스트나 뷰에서 해당 파일의 이름을 받아와야 한다.
    // fileDown.kosta?fileName=파일이름
    // -> @RequestParam("fileName") String fileName
    // ServletContext와 파일의 절대경로를 얻어내기위해서
    // -> HttpSession session, HttpServletRequest request
    // 다운로드란 브라우저와 Stream으로 연결되어서 통신되어야 하기 때문에..
    // -> HttpServletResponse response
    @RequestMapping(value = "/fileDown")
    public void fileDown(@RequestParam("fileName") String fileName, HttpSession session, HttpServletRequest request,
            HttpServletResponse response) throws IOException {
        // applicationContext 객체를 request로 부터 얻어냄
        ServletContext context = request.getServletContext();
        // 업로드된 경로 얻음
        String img_path = "resource\\img\\";
        String path = session.getServletContext().getRealPath("resources/img/") + fileName;
        System.out.println("FileDown:" + path);
        // 그 경로로 파일객체를 생성
        File downloadFile = new File(path);
        // FileInputStream 스트림으로 읽어옴
        FileInputStream fi = new FileInputStream(downloadFile);
        // 요청객체로부터 연결될 브라우저의 마임타입을 얻어냄
        String mimeType = context.getMimeType(path);
        // 만약 마임타입값이 없으면 그냥 디폴트로 스트림으로 연결
        if (mimeType == null) {
            // text/html, text/json, text/image
            mimeType = "application/octet-stream";
        }
        // 지정된 마임타입 세팅
        response.setContentType(mimeType);
        // 다운로드될 파일의 길이 세팅
        response.setContentLength((int) downloadFile.length());
        // 다운로드 Type을 설정함
        String headerKey = "Content-Disposition";
        String headerValue = String.format("attachment; filename=\"%s\"", downloadFile.getName());
        // 위의 다운로드 타입의 정보를 해더로 설정
        response.setHeader(headerKey, headerValue);
        // 브라우저로부터 스트림을 연결
        OutputStream outStream = response.getOutputStream();
        // 버퍼를 끼워서 빠르게 전달 목적
        byte[] buffer = new byte[BUFFER_SIZE];
        // 이제 브라우저로 보내고, 자원 닫으면 끝
        int bytesRead = -1;
        while ((bytesRead = fi.read(buffer)) != -1) {
            outStream.write(buffer, 0, bytesRead);
        }
        fi.close();
        outStream.close();
 
    }
 
    @RequestMapping(value = "/detail")
    public String detail(int num, Model m) {
        TBoardDTO vo = tvoDao.getDetail(num);
        m.addAttribute("vo", vo);
        return "detail";
    }
 
    @RequestMapping(value = "/update")
    public String updateForm(int num, Model m) {
        TBoardDTO vo = tvoDao.getDetail(num);
        m.addAttribute("vo", vo);
        return "updateForm";
    }
 
    @RequestMapping(value = "/updateProcess", method = RequestMethod.POST)
    public ModelAndView updateProcess(TBoardDTO tvo, HttpServletRequest request) {
        if (tvo.getMfile1().isEmpty() == false) {
            HttpSession session = request.getSession();
            String r_path = session.getServletContext().getRealPath("/");
            System.out.println(r_path);
            String img_path = "resources\\img\\";
            System.out.println(img_path);
            StringBuffer path = new StringBuffer();
            path.append(r_path).append(img_path);
            String oriFn = tvo.getMfile1().getOriginalFilename();
            path.append(oriFn);
            System.out.println(path);
            // 파일 업로드
            File f = new File(path.toString());
            try {
                tvo.getMfile1().transferTo(f);
            } catch (IllegalStateException | IOException e) {
                e.printStackTrace();
            }
            tvo.setMfile(oriFn);
        }else {
            tvo.setMfile(tvo.getMfile());
        }
        tvoDao.update(tvo);
        ModelAndView mav = new ModelAndView("redirect:/list");
        return mav;
    }
    @RequestMapping(value = "/delete")
    public String delete(int num) {
        tvoDao.delete(num);
        return "redirect:/list";
    }
}

src/or.kosta.mvc.dao/TvoDao.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
package or.kosta.mvc.dao;
 
import java.util.List;
 
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
 
import or.kosta.vo.TBoardDTO;
//
@Repository
public class TvoDao {
    @Autowired
    private SqlSessionTemplate ss;
     
    public void add(TBoardDTO tvo) {
        ss.insert("tboardMap.add",tvo);
    }
    public List<TBoardDTO> getList(){
        return ss.selectList("tboardMap.list");
    }
    public TBoardDTO getDetail(int num) {
        return ss.selectOne("tboardMap.detail",num);
    }
    public void update(TBoardDTO tvo) {
        ss.update("tboardMap.up", tvo);
    }
    public void delete(int num) {
        ss.delete("tboardMap.del",num);
    }
     
}

src/or.kosta.vo/TBoardDTO.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
package or.kosta.vo;
 
import org.springframework.web.multipart.MultipartFile;
 
public class TBoardDTO {
    private int num;
    private String title,writer,content,pwd,mfile;
    private MultipartFile mfile1;
     
    public String getMfile() {
        return mfile;
    }
 
    public void setMfile(String mfile) {
        this.mfile = mfile;
    }
 
    public MultipartFile getMfile1() {
        return mfile1;
    }
 
    public void setMfile1(MultipartFile mfile1) {
        this.mfile1 = mfile1;
    }
 
    public int getNum() {
        return num;
    }
 
    public void setNum(int num) {
        this.num = num;
    }
 
    public String getPwd() {
        return pwd;
    }
 
    public void setPwd(String pwd) {
        this.pwd = pwd;
    }
 
    public String getTitle() {
        return title;
    }
 
    public void setTitle(String title) {
        this.title = title;
    }
 
    public String getWriter() {
        return writer;
    }
 
    public void setWriter(String writer) {
        this.writer = writer;
    }
 
    public String getContent() {
        return content;
    }
 
    public void setContent(String content) {
        this.content = content;
    }
     
     
}

JSP코드 블로그에 버튼,파일등록창 같이떠서 제외


'학원수업 > Spring' 카테고리의 다른 글

학원 24일차 복습(4/16)  (0) 2018.04.16
학원 23일차 복습(4/13)  (0) 2018.04.13
학원 22일차 복습(4/12)  (0) 2018.04.12
학원 20일차 복습(4/10)  (0) 2018.04.10
학원 19일차 복습(4/9)  (0) 2018.04.09

이론


JSON (JavaScript Object Notation)은 경량의 DATA-교환 형식이다. 

json   뷰


ServletConfig -> pageContext와 Scope가 동일

하나의 서블릿 안에서만 사용될 수 있다.

init-param으로 초기화


ServletContext -> applicationContext와 Scope가 동일

context-param으로 초기화


context는 모든 빈들에게 어노테이션을 제공

어노테이션: 실행가능한 주석


@Controller(DispatcherServlet) -> Model을 수행

or.kosta.mvc 안에 있는 모든 빈중에 어노테이션으로 설정한 객체는 스프링컨테이너에 빈으로 등록!

@Controller 어노테이션은 HandlerMapping에 의해서 요청을 분석이 될 때 선택되는 Model객체이다.

요청을 매핑해서 비지니스 로직이 수행이 된다.(http://XXXXXX/hello)


ModelAndView는 View, RequestScope에 저장, forward/redirect결정


@ModelAttribute을 사용해서 View로 값을 전달한다.



servlet.xml에 multipartResolver 추가 : 파일 업로드를 하기 위해서 꼭 필요한 객체  

form에서 이미지나 동영상, 음악 파일등을 서버로 전송할 때는 enctype="multipart/form-data"속성을 지정해야하며, 

이때 전송방식은 대용량 압축방식인 post여야 한다. 

이미지가 저장될 절대경로를 지정 -> 세션을 생성 ->시스템에 맞는 documentroot(최상위경로) 경로를 가져온다.

->조합해서 이미지가 저장될 경로값을 구현 -> upload된 파일 이름은 path에 설정 -> 파일 업로드





실습


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
    <modelVersion>4.0.0</modelVersion>
    <groupId>spring0410_mvc</groupId>
    <artifactId>spring0410_mvc</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>
    <build>
        <sourceDirectory>src</sourceDirectory>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.7.0</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-war-plugin</artifactId>
                <version>3.0.0</version>
                <configuration>
                    <warSourceDirectory>WebContent</warSourceDirectory>
                </configuration>
            </plugin>
        </plugins>
    </build>
    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.3.6.RELEASE</version>
        </dependency>
        <!-- spring-jdbc for MyBatis -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>4.3.6.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.2</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.1</version>
        </dependency>
        <!-- Web MVC -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>4.3.6.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>4.3.6.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.3</version>
        </dependency>
        <!-- Aop관련 -->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.8.10</version>
        </dependency>
        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.8.6</version>
        </dependency>
    </dependencies>
</project>

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
<?xml version="1.0" encoding="UTF-8"?>
  <display-name>spring0410_mvc</display-name>
 <!-- Filter -->
  <filter>
    <filter-name>CharacterEncodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>EUC-KR</param-value>
    </init-param>
    <init-param>
      <param-name>forceEncoding</param-name>
      <param-value>true</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>CharacterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  <servlet>
   <servlet-name>kosta</servlet-name>
   <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  </servlet>
  <servlet-mapping>
   <servlet-name>kosta</servlet-name>
   <url-pattern>/</url-pattern>
  </servlet-mapping>
   
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
 
</web-app>

kosta-servlet.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<?xml version="1.0" encoding="UTF-8"?>
 
 
    <context:component-scan base-package="or.kosta.mvc"/>
    <mvc:annotation-driven/>
    <mvc:resources location="/resources/" mapping="/resources/**"/>
    <!-- multipartResolver 추가 : 파일 업로드를 하기 위해서 꼭 필요한 객체  -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"></bean>
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
 
</beans>

index.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>jsp/index.jsp</title>
<style>
    body {background: orange;}
</style>
</head>
 
    <a href="hello">첫번째 예제</a>
    <a href="simpleForm">두번째 예제</a>
    <a href="simpleForm2">세번째 예제</a>
    <a href="upform">네번째 예제</a>

or.kosta.mvc.controller/HelloController.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
package or.kosta.mvc.controller;
 
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
//@Controller(DispatcherServlet) -> Model을 수행
//or.kosta.mvc 안에 있는 모든 빈중에 어노테이션으로 설정한 객체는 스프링컨테이너에 빈으로 등록!
//@Controller 어노테이션은 HandlerMapping에 의해서 요청을 분석이 될 때 선택되는 Model객체이다.
@Controller
public class HelloController {
    //요청을 매핑해서 비지니스 로직이 수행이 된다.
    @RequestMapping(value="/hello",method=RequestMethod.GET)
    public ModelAndView sayhello() {
        //ModelAndView는 View,RequestScope에 저장, forward/redirect결정
        ModelAndView mav = new ModelAndView();
        //View의 이름을 지정
        mav.setViewName("sayhello");
        //값을 지정
        mav.addObject("msg","안녕하세요~^^");
        return mav;
    }
}

or.kosta.mvc.controller/DefaultController.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package or.kosta.mvc.controller;
 
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
 
@Controller
public class DefaultController {
 
    //기본 페이지 설정
    @RequestMapping(value= {"/index","/"})
    public String defaultPage() {
        System.out.println("test");
        return "index";
    }
    @RequestMapping(value="/myindex")
    public String myDefaultView() {
        return "index";
    }
}

sayhello.jsp

1
2
3
4
5
6
7
8
9
10
11
12
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>sayhello.jsp</title>
</head>
 
    <div>
        sayhello : ${msg}
    </div>

or.kosta.mvc.controller/SimpleController.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
package or.kosta.mvc.controller;
 
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
 
@Controller
public class SimpleController {
     
    @RequestMapping(value="/simpleForm")
    public String simpleForm() {
        return "simpleForm";
    }
     
    @RequestMapping(value="/simpleProcess")
    public ModelAndView simpleProcess(int num, String msg) {
        ModelAndView mav= new ModelAndView("simpleResult");
        num = num * 2;
        msg= "hi"+msg;
        mav.addObject("num", num);
        mav.addObject("msg", msg);
        return mav;
    }
}

simpleForm.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html>
 
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>simpleForm.jsp</title>
</head>
<!-- simpleForm 요청이 오면 SimpleController에서 매핑해서 화면에 출력 -->
    <div>
        <form method="post" action="simpleProcess">
            <input type="hidden" name="num" value="100">
            msg : <input type="text" name="msg">
            <input type="submit" value="send">
        </form>
    </div>

simpleResult.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html>
 
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>simpleResult.jsp</title>
</head>
 
    <ul>
        <li>num : ${num}</li>
        <li>msg : ${msg}</li>
    </ul>

or.kosta.mvc.controller/SimpleController2.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
package or.kosta.mvc.controller;
 
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
 
import or.kosta.vo.SimpleDTO;
 
@Controller
public class Simple2Controller {
 
    @RequestMapping(value="/simpleForm2")
    public String simpleForm() {
        return "simpleForm2";
    }
    //@ModelAttribute을 사용해서 View로 값을 전달한다.
    @RequestMapping(value="/simpleProcess2",method=RequestMethod.POST)
    public String simpleProcess(@ModelAttribute("vo") SimpleDTO vo) {
//      ModelAndView mav= new ModelAndView("simpleResult2");
//      mav.addObject("vo",vo);
        return "simpleResult2";
    }
}

or.kosta.vo/simpleDTO.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
package or.kosta.vo;
 
public class SimpleDTO {
    private int num;
    private String msg,writer,pwd;
    public int getNum() {
        return num;
    }
    public void setNum(int num) {
        this.num = num;
    }
    public String getMsg() {
        return msg;
    }
    public void setMsg(String msg) {
        this.msg = msg;
    }
    public String getWriter() {
        return writer;
    }
    public void setWriter(String writer) {
        this.writer = writer;
    }
    public String getPwd() {
        return pwd;
    }
    public void setPwd(String pwd) {
        this.pwd = pwd;
    }
 
}

simpleForm2.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html>
 
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>simpleForm2.jsp</title>
</head>
<!-- simpleForm 요청이 오면 SimpleController에서 매핑해서 화면에 출력 -->
    <div>
        <form method="post" action="simpleProcess2">
            <input type="hidden" name="num" value="100">
            msg : <input type="text" name="msg">
            writer : <input type="text" name="writer">
            password : <input type="password" name="pwd">
            <input type="submit" value="send">
        </form>
    </div>

simpleResult2.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html>
 
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>simpleResult2.jsp</title>
</head>
 
    <ul>
        <li>num : ${vo.num}</li>
        <li>msg : ${vo.msg}</li>
        <li>writer : ${vo.writer}</li>
        <li>pwd : ${vo.pwd}</li>
    </ul>

or.kosta.mvc.controller/UpsaveController.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 or.kosta.mvc.controller;
 
import java.io.File;
import java.io.IOException;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
 
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
 
@Controller
public class UpSaveController {
    @RequestMapping(value="/upform")
    public String upform() {
        return "upform";
    }
     
    @RequestMapping(value="/upsave", method = RequestMethod.POST)
    public ModelAndView save(@RequestParam("mfile") MultipartFile mfile, HttpServletRequest request) {
        //이미지가 저장될 절대경로를 지정
        ModelAndView mav = new ModelAndView("success");
        HttpSession session = request.getSession();    //세션을 생성
        String r_path = session.getServletContext().getRealPath("/");
        System.out.println(r_path);
        //시스템에 맞는 documentroot(최상위경로) 경로를 가져온다.
        String img_path = "resources\\img\\";
        System.out.println(img_path);
        //조합해서 이미지가 저장될 경로값을 구현
        StringBuffer path = new StringBuffer();
        path.append(r_path).append(img_path);
        //upload된 파일 이름은 path에 설정
        String oriFn = mfile.getOriginalFilename();
        path.append(oriFn);
        System.out.println(path);
        //파일 업로드
        File f = new File(path.toString());
        try {
            mfile.transferTo(f);
        } catch (IllegalStateException | IOException e) {
            e.printStackTrace();
        }
        mav.addObject("imgName", oriFn);
        return mav;
    }
     
}

upform.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html>
 
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>upform.jsp</title>
<style>
#wrap{width: 300px; margin: auto;}
</style>
</head>
 
    <div id="wrap">
    <%-- form에서 이미지나 동영상, 음악 파일등을 서버로 전송할 때는 enctype="multipart/form-data"속성을 지정해야
    하며, 이때 전송방식은 대용량 압축방식인 post여야 한다. --%>
        <form method="post" action="upsave" enctype="multipart/form-data">
            <input type="file" id="mfile" name="mfile"><br/>
            <input type="submit" value="send">
        </form>
    </div>

success.jsp

1
2
3
4
5
6
7
8
9
10
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html>
 
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>success.jsp</title>
</head>
 
    <img src="${pageContext.request.contextPath}/resources/img/${imgName}">


'학원수업 > Spring' 카테고리의 다른 글

학원 24일차 복습(4/16)  (0) 2018.04.16
학원 23일차 복습(4/13)  (0) 2018.04.13
학원 22일차 복습(4/12)  (0) 2018.04.12
학원 21일차 복습(4/11)  (0) 2018.04.11
학원 19일차 복습(4/9)  (0) 2018.04.09

이론


톰캣 컨테이너로부터 요청이 왔을때 스프링은 DI하여 한번에 수행


포트번호 오류시 

Servers -> server.xml에서 63번 라인 port="80" URIEncoding ="EUC-KR" 으로 수정


액션팩토리-오브잭트팩토리패턴적용 요청에따른 모델생성관리 컨트롤러에게 보고



DI (Dependency Injection)

● DI는 스프링 컨테이너가 지원하는 핵심 개념 중의 하나다.

DI는 객체 사이의 의존 관계를 객체 자신이 아닌 외부의 조립기가 수행한다는 개념이다.

● 스프링은 설정 파일이나 어노테이션을 이용하여 객체 간의 의존 관계를 손쉽게 설정할 수 있다.

■ 의존성(Dependency)

∎ 비즈니스 로직을 수행하기 위해서는 둘 이상의 클래스가 사용되는데, 각 객체는 협업할 객체의 참조를 취득해야할 책임이 있는데, 이것이 의존성이다. 

∎ 객체간의 결합도가 높으면 테스트하기 어려운 코드가 만들어진다.

■ 의존성 주입 : 객체들은 객체의 생성 시점에 spring container로부터 의존성을 부여 받게 된다. 즉, 의존하는 객체를 주입받게 된다.


■ 빈 묶기(Bean Wiring)

스프링 컨테이너에서 각 객체간의 의존관계는 xml 파일을 통해서명시할 수 있다. 객체간의 의존 관계는 생성자와 setter 메소드 방식의 두가지 방식으로 지정할 수 있다. 

값을 추가 시킬수 있는 방법은 기본 2가지 setter,생성자


제어역행(IoC : Inversion of Control)

각 객체는 협업할 객체의 참조를 취득해야하는 책임이 있는데, 제어역행은 의존하는 객체를 역행적으로 취득하는 것이다. IoC는 한 객체가 의존성을 가지는 다른 객체의 참조를 취득하는 방법에 대한 책임의 역행이라는 의미를 가지고 있다. IoC를 적용하면 객체들은 어떤 존재에 의해 객체를 생성할 때 의존성을 가지는 객체를 주입받게 된다.



spring 컨테이너 : 스프링은 객체를 관리하는 컨테이너를 제공한다.(스프링 컨테이너는 객체를 생성, 저장, 관리한다.)

spring은 BeanFactory와 ApplicationContext 인터페이스를 구현한 컨테이너를 제공한다.


■ applicationContext.xml

∎ 스프링에서는 컨테이너에 저장될 Bean객체와 각 Bean객체간의 연관관계를 xml 파일을 통해서 설정한다. 

∎ <bean> 태그는 스프링 컨테이너 안에서 생성해야 하는 자바 빈을 정의한다.

 빈 추가: 빈을 위한 기본 설정에는 빈의 id와 클래스 전체 경로를 설정한다.

id 속성은 생성된 객체를 구분하는 식별값으로 사용되면, id 속성 대신 name 속성을 사용할 수도 있다.


∎ 프로토타입과 싱글톤

스프링의 모든 빈은 기본적으로 싱글톤이다. 컨테이너가 배포하는 빈은 항상 동일한 인스턴스를 반환한다. 컨테이너로부터 매번 새로운 인스턴스를 제공받으려면 <bean>태그의 singleton속성을 false로 혹은 scope속성을 prototype로 정의한다.



proprerty ==> setter호출

Spring은 외부조립기 역할, 객체들 관계를 맞추어 주는 역할...

스프링컨테이너는 싱글톤 레지스터리가 있어서 빈으로 등록하는 모든 객체를 싱글톤레지스터리에 등록 해놓고 사용한다.

di 시킬 대상을 적용해서 주입시킬때 ref= 속성을 을 사용한다.

생성자의 특징 : Spring에서는 생성자 오버로딩 문제일때 기본 빈의 주입 형식이 String이다.

 생성자 오버로딩일 경우 생성자의 자료형을 명시 해줘야 한다.



@Autowired 어노테이션을 이용한 자동 설정

◦ @Autowired 어노테이션은 의존 관계를 자동으로 설정할 때 사용되며 생성자, 필드, 메서드 세 곳에 적용가능하다.

◦ @Autowired 어노테이션은 해당 타입의 빈 객체가 존재하지 않거나 2개 이상 존재하는 경우 예외를 발생한다.


byName : property와 같은 이름의 빈을 찾아서 묶어준다.

byType : property와 같은 타입의 빈을 찾아서 묶어준다.

1.모든 빈을 검색한다.

2.같은 타입의 빈이 오면 혼돈을 일으키기 때문에 수식어 지정!


@Qualifier 어노테이션을 이용한 자동 설정 제한

◦ @Qualifier 어노테이션을 이용하여 동일한 빈 객체들 중에서 특정 빈을 사용하도록 설정할 수 있다.

◦ @Qualifier 어노테이션은 자동 연결할 빈 객체의 수식어 값을 가진다.

빈 객체들 중에서 <qualifier> 태그의 값이 @Qualifier 어노테이션의 수식어 값과 일치하는 빈을 자동 설정한다. 



빈의 초기화와 소멸

∙ 스프링은 빈의 구성과 해제를 위한 생명주기 메소드를 제공

∙ init-method는 빈이 객체화되는 즉시 호출될 메소드 정의

∙ destroy-method는 빈이 컨테이너로부터 제거되기 직전에 호출될 메소드를 정의


생성자 호출

 init 호출 

------------------------ 

printMsg 호출

빈의 라이프 사이클 테스트(str)

destroy 호출




실습


src.ex1.Ex1_MessageApp.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package ex1;
 
public class Ex1_MessageApp {
    private String msg;
    //proprerty ==> setter호출
    //Spring은 외부조립기 역할, 객체들 관계를 맞추어 주는 역할...
    //스프링컨테이너는 싱글톤 레지스터리가 있어서 빈으로 등록하는 모든 객체를 싱글톤레지스터리에 등록 해놓고 사용한다.
 
    public void setMsg(String msg) {
        this.msg = msg;
    }
    public String printMsg() {
        StringBuffer sb = new StringBuffer();
        sb.append("당신이 입력한 메세지:").append(msg);
        sb.append("입니다.");
        return sb.toString();
    }
     
}

src.ex1.Exam_Todate.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package ex1;
 
import java.text.SimpleDateFormat;
import java.util.Date;
//Exam_DI.java   exam_di.xml로 적절하게 di받을 수 있도록 코드를 수정해서 실행해봅시다.
public class Exam_Todate {
    private String todate, name;
    public void setName(String name) {//value값을 주입
        this.name = name;
    }
    public Exam_Todate() {
        //<bean id="f" class="알아서">
        SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
        todate = f.format(new Date());
    }
    public String printDate() {
        return todate+"/"+name;
    }
}

src.ex1.Myprofile.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package ex1;
 
public class MyProfile {
    private String name;
    private int age;
    public void setName(String name) {
        this.name = name;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public String printPro() {
        return name+"/"+age;
    }
     
}

src.ex1.ex1.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
<?xml version="1.0" encoding="UTF-8"?>
    <!-- 스프링에 의해서 문자열 값을 주입시켜 보자. -->
    <bean id="msg" class="ex1.Ex1_MessageApp" scope="prototype">
        <property name="msg" value="안녕하세요~!"/>
    </bean>
    <bean id="today" class="ex1.Exam_Todate">
        <property name="name" value="코스타"/>
    </bean>
 
</beans>

src.ex1.mypro.xml

1
2
3
4
5
6
7
8
9
10
11
<?xml version="1.0" encoding="UTF-8"?>
 
    <bean id="pro" class="ex1.MyProfile">
        <property name="name" value="코스타"/>
        <property name="age" value="182"/>
    </bean>
 
</beans>

ex1_di.jsp

원소스가 제대로 안올라가서 올리지 않음.

ex1_di2.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
<%@page import="ex1.Exam_Todate"%>
<%@page import="ex1.Ex1_MessageApp"%>
<%@page import="org.springframework.context.support.GenericXmlApplicationContext"%>
<%@page import="org.springframework.context.ApplicationContext"%>
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>ex1_di2.jsp</title>
</head>
 
<%
    //1.SpringContainer에 등록되어서 생성될때 객체가 싱글톤으로 생성이 된다.
    ApplicationContext ctx = new GenericXmlApplicationContext("ex1/ex1.xml");
    //2.싱글톤 레지스터리에서 등록된 객체의 주소를 얻어온다.
    Ex1_MessageApp em1 = ctx.getBean("msg", Ex1_MessageApp.class);
    Ex1_MessageApp em2 = ctx.getBean("msg", Ex1_MessageApp.class);
    // scope="prototype" 은 싱글톤이 아니기 때문에 false 즉 주소값이 다름
    System.out.println("em1== em2"+(em1==em2));
    Exam_Todate todate = ctx.getBean("today", Exam_Todate.class);
     
     
%><%=todate.printDate() %>

myprofile.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<%@page import="ex1.MyProfile"%>
<%@page import="org.springframework.context.support.GenericXmlApplicationContext"%>
<%@page import="org.springframework.context.ApplicationContext"%>
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>myprofile.jsp</title>
</head>
 
<%
    ApplicationContext ctx = new GenericXmlApplicationContext("ex1/mypro.xml");
    MyProfile pr = ctx.getBean("pro", MyProfile.class);
     
%><%=pr.printPro() %>

src.exam.Exam_DI.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package exam;
 
import java.text.SimpleDateFormat;
import java.util.Date;
 
public class Exam_DI {
    private SimpleDateFormat sdf;
    private Date date;
    public String printDate() {
        String todate= sdf.format(date);
        return todate;
    }
    //new SimpleDateFormat("yyyy-MM-dd");
    public void setSdf(SimpleDateFormat sdf) {
        this.sdf = sdf;
    }
    public void setDate(Date date) {
        this.date = date;
    }
 
}

src.exam.exam_di.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?xml version="1.0" encoding="UTF-8"?>
    <bean id="sdf" class="java.text.SimpleDateFormat">
        <constructor-arg>
            <value>yyyy-MM-dd</value>
        </constructor-arg>
    </bean>
    <bean id="date" class="java.util.Date"/>
    <bean id="edi" class="exam.Exam_DI" p:sdf-ref="sdf" p:date-ref="date"/>
 
</beans>

exam_di.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<%@page import="exam.Exam_DI"%>
<%@page import="org.springframework.context.support.GenericXmlApplicationContext"%>
<%@page import="org.springframework.context.ApplicationContext"%>
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>Insert title here</title>
</head>
 
<%
    ApplicationContext ctx = new GenericXmlApplicationContext("exam.exam_di.xml");
 
    Exam_DI di = ctx.getBean("edi", Exam_DI.class);
     
%>

src.ex2.Ex2_Resource.java

1
2
3
4
5
6
7
8
9
10
11
12
13
package ex2;
 
public class Ex2_Resource {
    private String name;
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
}

src.ex2.Ex2_Message.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package ex2;
//값을 추가 시킬수 있는 방법은 기본 2가지 setter,생성자
public class Ex2_Message {
    private Ex2_Resource resource;
 
    public Ex2_Message() {
    }
 
    public Ex2_Message(Ex2_Resource resource) {
        this.resource = resource;
    }
 
    public void setResource(Ex2_Resource resource) {
        this.resource = resource;
    }
 
    public String msgPrint() {
        String name = resource.getName();
        return name + "님 안녕하세요!";
    }
 
}

src.ex2.ex2_di.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
<?xml version="1.0" encoding="UTF-8"?>
 
    <bean id="res" class="ex2.Ex2_Resource" p:name="코스타"/>
    <!-- di 시킬 대상을 적용해서 주입시킬때 ref= 속성을 을 사용한다. -->
    <bean id="msg" class="ex2.Ex2_Message">
    <constructor-arg ref="res"/>
    <property name="resource" ref="res"/>
    </bean>
</beans>

ex2_di.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<%@page import="ex2.Ex2_Message"%>
<%@page import="org.springframework.context.support.GenericXmlApplicationContext"%>
<%@page import="org.springframework.context.ApplicationContext"%>
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>ex2_di.jsp</title>
</head>
 
<%
    ApplicationContext ctx = new GenericXmlApplicationContext("ex2/ex2_di.xml");
 
    Ex2_Message msg =ctx.getBean("msg", Ex2_Message.class);
%><p style="background: yellow"><%=msg.msgPrint() %></p>

src.ex3.Ex3_Service.java

1
2
3
4
5
6
7
package ex3;
//생성자의 특징 : Spring에서는 생성자 오버로딩 문제일때 기본 빈의 주입 형식이 String이다.
public interface Ex3_Service {
    public String print();
    public String call();
    public String moniter();
}

src.ex3.Ex3_ServiceImple.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
package ex3;
 
public class Ex3_ServiceImple implements Ex3_Service {
    private int num;
    private String name, str;
    //생성자로 주입을 받을 때는 기본적으로 String이 기본값
    //"1000" 1000
     
    public Ex3_ServiceImple(int num) {
        this.num = num;
        System.out.println("Int 호출");
    }
    public Ex3_ServiceImple(String str) {
        this.str = str;
        System.out.println("String 호출");
    }
 
    public Ex3_ServiceImple(int num, String name) {
        this.num = num;
        this.name = name;
    }
    @Override
    public String print() {
        StringBuffer s = new StringBuffer();
        int res = num * 10;
        s.append("RES :").append(res);
        return s.toString();
    }
    @Override
    public String call() {
        StringBuffer s = new StringBuffer();
        s.append(str).append("★");
        return s.toString();
    }
    @Override
    public String moniter() {
        StringBuffer s = new StringBuffer();
        int res = num + 10;
        s.append("RES :").append(res);
        s.append("Name :").append(name);
        return s.toString();
    }
     
}

src.ex3.ex3_const.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<?xml version="1.0" encoding="UTF-8"?>
 
    <bean id="cont1" class="ex3.Ex3_ServiceImple">
        <constructor-arg value="10000" type="int" />
    </bean>
    <!-- 생성자 오버로딩일 경우 생성자의 자료형을 명시 해줘야 한다. cont2라 이름으로 생성자의 인자가 2개인 빈을 만들어서
        moniter()를 호출하시오. -->
    <bean id="cont2" class="ex3.Ex3_ServiceImple">
        <constructor-arg value="10000" />
        <constructor-arg value="김길동" />
    </bean>
 
</beans>

ex3_const.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<%@page import="ex3.Ex3_Service"%>
<%@page import="org.springframework.context.support.GenericXmlApplicationContext"%>
<%@page import="org.springframework.context.ApplicationContext"%>
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>ex3_const.jsp</title>
</head>
 
<%
    ApplicationContext ctx = new GenericXmlApplicationContext("ex3/ex3_const.xml");
    Ex3_Service es = ctx.getBean("cont1", Ex3_Service.class);
%>Str : <%=es.call() %>/ Num : <%=es.print() %> <br/>
<!--  cont2로 요청하면 Ex3_ServiceImple(int num, String name)를 호출 하도록 bean을 정의하세요. -->
<%
    Ex3_Service es2= ctx.getBean("cont2", Ex3_Service.class);
%><%=es2.moniter() %>

src.ex5.ChinaOrder.java

1
2
3
4
5
6
7
8
9
10
11
package ex5;
 
public class ChinaOrder implements MenuInter {
    public String order(String orderName) {
        StringBuffer sb = new StringBuffer();
        sb.append("오늘의 짜장을 주문하셨군요 ^^");
        sb.append(orderName).append("/ 500000 won");
        return sb.toString();
    }
 
}

src.ex5.IndoOrder.java

1
2
3
4
5
6
7
8
9
10
11
package ex5;
 
public class IndoOrder implements MenuInter {
    public String order(String orderName) {
        StringBuffer sb = new StringBuffer();
        sb.append("오늘은 인도 요리를 주문하셨군요 ^^");
        sb.append(orderName).append("/ 200000 won");
        return sb.toString();
    }
 
}

src.ex5.KorOrder.java

1
2
3
4
5
6
7
8
9
10
package ex5;
 
public class KorOrder implements MenuInter {
    public String order(String orderName) {
        StringBuffer sb = new StringBuffer();
        sb.append("오늘의 메인 코스인 한식을 주문하셨군요 ^^");
        sb.append(orderName).append("/ 100000 won");
        return sb.toString();
    }
}

src.ex5.MenuInter.java

1
2
3
4
5
package ex5;
 
public interface MenuInter {
    public String order(String orderName);
}

src.ex5.OrderSystem.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package ex5;
 
public class OrderSystem {
    //다형성으로 설계된 빈 객체!
    private MenuInter menu;
    //private KorOrder m1;
    //private IndoOrder m2;
    //private ChinaOrder m3;
 
    public MenuInter getMenu() {
        return menu;
    }
 
    public void setMenu(MenuInter menu) {
        this.menu = menu;
    }
 
    public String printMenu(String orderName) {
        return menu.order(orderName);
    }
     
     
}

src.ex5.ex5_menu.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"?>
 
    <bean id="menu1" class="ex5.KorOrder"/>
    <bean id="menu2" class="ex5.IndoOrder"/>
    <bean id="menu3" class="ex5.ChinaOrder"/>
    <bean id="kor" class="ex5.OrderSystem">
        <property name="menu" ref="menu1"/>
    </bean>
    <bean id="indo" class="ex5.OrderSystem">
        <property name="menu" ref="menu2"/>
    </bean>
    <bean id="china" class="ex5.OrderSystem">
        <property name="menu" ref="menu3"/>
    </bean>
 
</beans>

orderForm.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>orderForm.jsp</title>
</head>
 
    <div id="wrap">
        <form method="post" action="orderProcess.jsp">
            <select name="orderName">
                <option value="kor">한식</option>
                <option value="indo">인도식</option>
                <option value="china">중식</option>
            </select>
            <input type="submit" value="send">
        </form>
    </div>

orderProcess.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<%@page import="ex5.OrderSystem"%>
<%@page import="org.springframework.context.support.GenericXmlApplicationContext"%>
<%@page import="org.springframework.context.ApplicationContext"%>
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%
    request.setCharacterEncoding("euc-kr");
    String menu = request.getParameter("orderName");
    String path = "ex5/ex5_menu.xml";
    ApplicationContext ctx = new GenericXmlApplicationContext(path);
    OrderSystem os = ctx.getBean(menu, OrderSystem.class);
    String orderName="";
    if(menu.equals("kor")){
        orderName="한식";
    }else if(menu.equals("indo")){
        orderName="인도식";
    }else if(menu.equals("china")){
        orderName="중식";
    }
    String res = os.printMenu(orderName);
 
%><%=res %>

src.ex6.Ex6_AutoWired.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package ex6;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
 
public class Ex6_AutoWired {
    //byName : property와 같은 이름의 빈을 찾아서 묶어준다.
    //byType : property와 같은 타입의 빈을 찾아서 묶어준다.
    //1.모든 빈을 검색한다.
    //2.같은 타입의 빈이 오면 혼돈을 일으키기 때문에 수식어 지정!
    @Autowired
    @Qualifier("h")
    private String name;
     
    public String printName() {
        return "당신의 이름은"+name+"입니다.";
    }
}

src.ex6.ex6_auto.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"?>
 
    <context:annotation-config/>
    <bean id="name1" class="java.lang.String">
        <constructor-arg><value>김길동</value></constructor-arg>
    </bean>
    <bean id="name2" class="java.lang.String">
        <qualifier value="h"/>
        <constructor-arg><value>버럭 오마바</value></constructor-arg>
    </bean>
    <bean id="myauto" class="ex6.Ex6_AutoWired">
     
    </bean>
 
</beans>

src.ex6.Ex7_Resource.java

1
2
3
4
5
6
7
8
9
10
11
12
package ex6;
 
import javax.annotation.Resource;
 
public class Ex7_Resource {
    @Resource(name="msg2")
    private String msg;
     
    public String printMsg() {
        return "당신의 메세지 :"+msg;
    }
}

src.ex6.ex7_res.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?xml version="1.0" encoding="UTF-8"?>
    <context:annotation-config/>
    <bean id="msg1" class="java.lang.String">
        <constructor-arg><value>AOP진도 나갑시다. ^^</value></constructor-arg>
    </bean>
    <bean id="msg2" name="msg3" class="java.lang.String">
        <constructor-arg><value>재미있는 Spring MVC!</value></constructor-arg>
    </bean>
    <bean id="resv" class="ex6.Ex7_Resource"/>
</beans>

src.ex6.Ex8_LifeCycle.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
package ex6;
 
 
public class Ex8_LifeCycle {
    private String msg;
    public Ex8_LifeCycle() {
        System.out.println("생성자 호출");
    }
     
    public void setMsg(String msg) {
        this.msg = msg;
    }
 
    public void init() {
        System.out.println("init 호출");
    }
    public String printMsg() {
        System.out.println("printMsg 호출");
        return "Hello"+msg;
    }
    public void destroy() {
        System.out.println("destroy 호출");
    }
     
}

src.ex6.Ex8_Main.java

1
2
3
4
5
6
7
8
9
10
11
12
13
package ex6;
 
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
 
public class Ex8_Main {
    public static void main(String[] args) {
        ApplicationContext ctx = new GenericXmlApplicationContext("ex6/ex8_life.xml");
        Ex8_LifeCycle el = ctx.getBean("lifeBean", Ex8_LifeCycle.class);
        System.out.println("------------------------");
        System.out.println(el.printMsg());
    }
}

src.ex6.ex8_life.xml

1
2
3
4
5
6
7
8
9
10
11
<?xml version="1.0" encoding="UTF-8"?>
 
    <bean id="str" class="java.lang.String">
    <constructor-arg><value>빈의 라이프 사이클 테스트</value></constructor-arg>
    </bean>
    <bean id="lifeBean" class="ex6.Ex8_LifeCycle" init-method="init" destroy-method="destroy" p:msg-ref="str"/>
</beans>

ex6_auto1.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<%@page import="ex6.Ex6_AutoWired"%>
<%@page import="org.springframework.context.support.GenericXmlApplicationContext"%>
<%@page import="org.springframework.context.ApplicationContext"%>
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>ex6_auto1.jsp</title>
</head>
 
<%
    ApplicationContext ctx = new GenericXmlApplicationContext("ex6/ex6_auto.xml");
    Ex6_AutoWired ea = ctx.getBean("myauto", Ex6_AutoWired.class);
%>이름 : <%=ea.printName() %>

ex7_auto.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<%@page import="ex6.Ex7_Resource"%>
<%@page import="org.springframework.context.support.GenericXmlApplicationContext"%>
<%@page import="org.springframework.context.ApplicationContext"%>
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>ex7_auto.jsp</title>
</head>
 
<%
    ApplicationContext ctx = new GenericXmlApplicationContext("ex6/ex7_res.xml");
    Ex7_Resource ea = ctx.getBean("resv", Ex7_Resource.class);
%><p><%=ea.printMsg() %></p>


'학원수업 > Spring' 카테고리의 다른 글

학원 24일차 복습(4/16)  (0) 2018.04.16
학원 23일차 복습(4/13)  (0) 2018.04.13
학원 22일차 복습(4/12)  (0) 2018.04.12
학원 21일차 복습(4/11)  (0) 2018.04.11
학원 20일차 복습(4/10)  (0) 2018.04.10

+ Recent posts