스프링 기초 DI 예제 4


[스프링 컨테이너 생명 주기]

      

      스프링 컨테이너 생성   : GenericXmlApplicationContext ctx = new GenericXmlApplicationContext();

       ------> 설정    :  ctx.load("classpath:baseBall.xml");

                     ctx.refresh(); 

       ------> 사용    :  Player player =ctx.getBean("player".Player.class); 

            player.getName();

            player.getPosition();

       ------> 종료    :ctx.close()



 [빈 Life cycle(생명주기)]

   

   ctx.refresh 과정에서 빈이 생성 

   

   ctx.close() 컨테이너가 소멸하는 단계에서 빈도 자동으로 소멸됩니다.

    

   InitializingBean 인터페이스 -  초기화 할때 작동

    구현해야 할 메소드

    public void afterPropertiesSet() throws Exception

   

   DisposableBean 인터페이스 -  소멸될때 작동

    public void destroy() throws Exception  

   InitializingBean, DisposableBean은 따로 구현 해도 되고, 동시에 구현해도 된다.


# 어노테이션을 활용하는 방법

    @PostConstruct

    public void initMethod(){}

     - 빈 초기화 과정에서 빈이 생성되기 전에 해야할 작업을 할 수 있다.

     

     

    @PreDestroy    

public void destroyMethod(){}

- 종료되는 시점에 빈 소멸전에 해야할 작업을 할 수 있다.

(컨테이너 안에 빈이 들어 있다.)


예제1)





   [빈의 범위(scope)]

범위는 해당하는 객체가 어디까지 영향을 미치는지 결정하는 것

<bean> 태그의 속성 값 : default 값은 singleton

  singleton : 스프링 컨테이너에 의해 한개의 빈객체만 생성

  prototype : 빈을 사용할 때 마다 객체를 생성

  request : HTTP 요청 마다 빈 객체를 생성(WebApplicationContext에서만 적용)

  session : HTTP 세션 마다 빈 객체를 생성(WebApplicationContext에서만 적용)

  global-session : 글로발 HTTP 세션에 대해 빈 객체를 생성. 





[커스텀 초기화 메소드/ 커스텀 소멸 메소드]  

:객체의 생성과 소멸시에 특정 메소드를 실행시키고 싶을 때 사용한다.  

- init-method : 커스텀 초기화 메서드를 지정하는 <bean>태그의 속성

- destroy-method : 커스텀 소멸 메서드를 지정하는 <bean>태그의 속성 

** BeanNameAware 인터페이스

: 빈객체가 자기자신의 이름을 알아야 할 경우 사용된다.

: 클래스가 BeanNameAware 인터페이스를 구현한 경우 컨테이너는 setBeanName()메서드를 호출해서 빈객체의 이름을 전달

: setBeanName(String arg) : 객체가 생성될 때 해당 객체의 id나 name값을 전달 받는 메서드



[외부 파일을 이용한 빈 설정]

 

- EnvironmentAware, Envirionment 인터페이스를 활용

 

  . Context  --> getEnvironment() -->Environment 객체 얻기

  . Environment  -->getPropertySources 객체를 얻기

  . PropertySources -->프로퍼티를 추가(addLast)하거나, 추출(getProperty) 작업을 한다.

 

 

- 프로퍼티 파일을 이용한 빈설정

 

  .XML 파일에 외부프로퍼티 파일을 명시하는 방법

 

 

  .Java 파일에 외부 프로퍼티 파일을 명시하는 방법

 

 










springDemo_2.zip


'매일코딩 > Spring' 카테고리의 다른 글

스프링 기초 DI 예제 4  (2) 2018.07.17
스프링 기초 DI 예제 3  (0) 2018.07.17
스프링 기초 DI 예제2  (0) 2018.07.16
스프링 기초 DI 예제1  (0) 2018.07.16
31.스프링프로젝트 - 조회  (0) 2016.11.21
30.스프링프로젝트 - 답변  (0) 2016.11.21
  1. 2018.08.30 15:06

    비밀댓글입니다

  2. 2018.08.31 16:55

    비밀댓글입니다

스프링 기초 DI 예제 3



[의존성 주입 종류]

    setter(설정 메소드)를 이용한 주입 

    : 설정 메소드를 사용해서 의존성을 주입하는 것

    

    Constructor(생성자)를 통한 주입

    : 생성자를 사용해서 의존성을 주입하는 것

   

   

   [의존성 주입(DI)의 장점]

DI를 사용하면 개발 계획시에 시간이 요구가 되지만, 규모가 큰 프로젝트에서 유지보수 업무를 

한다면 DI 개발의 장점을 느낄 수 있다.  

   

   

   [의존 관계 설정 방법]

   - XML파일을 이용한 설정방법

   

   - JAVA를 이용한 설정방법(어노테이션을 이용한다. @Configuration, @Bean)

     

     : 어노테이션(Annotation:Metadata)-JDK5부터 등장한 개념 ex)@Override

         선언시에는 @를 사용하여 선언한다.

         어노테이션은

     . 컴파일러에게 정보를 알려주거나

     . 컴파일 할 때와 설치(deployment)시의 작업을 지정하거나

     . 실행할 때 별도의 처리가 필요한 경우

         사용한다.

   클래스, 메소드, 변수 등 모든 요소에 선언이 가능하다.

   

       

       # @Configuration : 클래스앞에 선언하는데, "이 클래스는 스프링 설정에 사용되는 클래스 입니다" 라고 알려주는 어노테이션

       # @Bean : 메소드 앞에 선언, "객체를 생성"

   


예제1)


예제2) 자바로 빈객체 만들기

예제3)



예제4)자바 코드에서 xml 불러오는 방법


springDemo_1.zip


 

'매일코딩 > Spring' 카테고리의 다른 글

스프링 기초 DI 예제 4  (2) 2018.07.17
스프링 기초 DI 예제 3  (0) 2018.07.17
스프링 기초 DI 예제2  (0) 2018.07.16
스프링 기초 DI 예제1  (0) 2018.07.16
31.스프링프로젝트 - 조회  (0) 2016.11.21
30.스프링프로젝트 - 답변  (0) 2016.11.21

스프링 기초 DI 예제2


코드의 변경 없이 xml 설정만으로 개발자가 원하는 객체의 주입으로 바꿀 있음.

   

   

   [의존성 주입 종류]

    setter(설정 메소드) 이용한 주입 

    : 설정 메소드를 사용해서 의존성을 주입하는

    

    Constructor(생성자) 통한 주입

    : 생성자를 사용해서 의존성을 주입하는

   

   

   [의존성 주입(DI) 장점]

DI 사용하면 개발 계획시에 시간이 요구가 되지만, 규모가 프로젝트에서 유지보수 업무를 

한다면 DI 개발의 장점을 느낄 있다.  




예제1)















예제2)





















'매일코딩 > Spring' 카테고리의 다른 글

스프링 기초 DI 예제 4  (2) 2018.07.17
스프링 기초 DI 예제 3  (0) 2018.07.17
스프링 기초 DI 예제2  (0) 2018.07.16
스프링 기초 DI 예제1  (0) 2018.07.16
31.스프링프로젝트 - 조회  (0) 2016.11.21
30.스프링프로젝트 - 답변  (0) 2016.11.21

스프링 기초 DI 예제1



스프링 프레임워크 특징 1


* 먼저 스프링 프레임워크는 자바언어를 기반으로 한 어플리케이션을 만들때 효율적으로 빠르게 제작할 수 있도록 하는 프로그래밍 툴이다.

* 스프링은 자바의 객체를 담고 있는 컨테이너다.

* 객체의 생성, 소멸과 같은 생명주기를 관리한다.

* DI(의존성 주입패턴)을 지원한다.

* AOP, 트랜잭션이나, 로깅, 보안과 같은 엔터프라이즈 어플리케이션에서 공통으로 필요로 하는 기능을 분리해서 각모듈에 적용할 수 있도록 하는 기능을 제공한다.

* 스프링은 POJO를 지원한다. 즉 특정 인터페이스나 클래스를 상속받지 않는 순수한 자바 객체를 스프링 컨테이너가 저장하고 있다.

* 트랜잭션 처리를 위한 일관된 방식을 제공한다.

* 영속성과 관련된 다양한 API를 제공한다.

* Mybtis, JPA, JDBC 등과 같은 프레임워크와의 연동을 지원한다.


DI(의존성주입)

DI 스프링의 핵심 개념 중의 하나이다.

객체 사이의 의존 관계를 객체 자신이 아닌 외부(스프링 컨테이너)에서 수행하는 개념

* 의존관계의 설정은 설정파일(bean.xml)이나 어노테이션을 이용하여 설정 한다.


예1)

프로젝트 생성


test.xml에 bean을 통해서 TestDAOImp 객체를 만들었다.




인터페이스 메소드 구현


인터페이스




예2) DI 예제



bean으로 객체 생성 -> myGetSum이 GetSum 참조 -> property name 을 이용해서 MyGetSum setter 함수에 값을 할당 했다.







예3) 생성자를 통해서 값 주입하기




예4)















'매일코딩 > Spring' 카테고리의 다른 글

스프링 기초 DI 예제 3  (0) 2018.07.17
스프링 기초 DI 예제2  (0) 2018.07.16
스프링 기초 DI 예제1  (0) 2018.07.16
31.스프링프로젝트 - 조회  (0) 2016.11.21
30.스프링프로젝트 - 답변  (0) 2016.11.21
29.spring- detgul  (0) 2016.11.18



view.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
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
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%-- <%@ page session="false"%> --%>
<c:set var="path" value="${pageContext.request.contextPath}"></c:set> 
 
 
 
 
<jsp:include page="boardHeader.jsp" flush="false"/>
 
 
                    <h1 id="community"><div>COMMUNITY</div></h1>
          <article>
              <h2>게시판</h2>
              
 
    
    <table border="1" align="center" class="tbl_type" WIDTH=50% table-layout: fixed>
        <tr>
            <th  nowrap WIDTH="40">번호</th>
            <th  nowrap WIDTH="100">이름</th>
            <th  nowrap WIDTH="250">제목</th>
            <th  nowrap WIDTH="100">날짜</th>
            <th  nowrap WIDTH="40">조회</th>
            <th  nowrap WIDTH="70">첨부파일</th>
            <th  nowrap WIDTH="70">다운로드</th>
        </tr>
 
 
        <c:forEach var="row" items="${list}">
            <tr>
                <td>${row.idx }</td>
                <td>${row.username }</td>
                <td>
                
                <!-- 답변 들여쓰기 -->
                <c:forEach begin="1" end="${row.depth }">
                &nbsp;&nbsp;
                </c:forEach>
    
    
 
                <a href="${path}/board/view.do?idx=${row.idx}">
                ${row.subject}</a>
                <c:if test="${row.comment_count >0 }">
            
            <span style="color:red">[${row.comment_count}]</span>
                
                </c:if>
                </td>
    
                <td>${row.post_date}</td>
                <td>${row.hit}</td>
                
                
                <!-- 첨부파일의 사이즈가 보다 크면 파일 다운로드 링크 표시 -->
                
                
                <td align="center">
                <c:if test="${row.filesize > 0 }">
                    <a href="${path}/board/down.do?idx=${row.idx}">
                    <img src="${path}/images/file.gif">
                </a>
                </c:if>
                </td>
 
                <td>${row.down}</td>
            </tr>
        </c:forEach>
 
 
<!-- page navigation -->
<tr align="center">
<td colspan="7">
<!-- 이전 -->
<c:if test="${page.curPage>1 }">
<a href="${path}/board/board_list.do?curPage=1&search_option=${search_option}&search=${search}">[시작] </a>
</c:if>
 
<c:if test="${page.curBlock > 1 }">
<a href="${path}/board/board_list.do?curPage=${page.prevPage}&search_option=${search_option}&search=${search}">[이전] </a>
</c:if>
 
 
 
<c:forEach var="pageNum" begin="${page.blockStart}" end="${page.blockEnd}">
 
<c:choose>
    <c:when test="${pageNum==page.curPage }">
 
    <span style="color:red">[${pageNum}]</span>
    </c:when>
    
    <c:otherwise>
<a href="${path}/board/board_list.do?curPage=${pageNum}&search_option=${search_option}&search=${search}">[${pageNum}] </a>&nbsp;
    </c:otherwise>
</c:choose>
 
</c:forEach>
 
<!-- 다음 -->
 
 
<c:if test="${page.curBlock <= page.totBlock}">
 
<a href="${path}/board/board_list.do?curPage=${page.nextPage}&search_option=${search_option}&search=${search}">[다음] </a>
</c:if>
 
<!-- 마지막 페이지 -->
 
<c:if test="${page.curPage < page.totPage}">
 
<a href="${path}/board/board_list.do?curPage=${page.totPage}&search_option=${search_option}&search=${search}">[끝] </a>
 
</c:if>
</td>
 
</tr>
 
    </table>
 
<br>
<!-- 검색폼 -->
 
    <form method="post" action="${path}/board/board_list.do">
        <div align="center"><select name="search_option">
            <option value="username"
            
            <c:if test= "${search_option =='username'}"> selected </c:if> >
            이름
            </option>
            
            <option value="subject" <c:if test= "${search_option =='subject'}"> selected </c:if> >제목</option>
            <option value="content" <c:if test= "${search_option =='content'}"> selected </c:if> >내용</option>
            <option value="all" <c:if test= "${search_option =='all'}"> selected </c:if> >전체</option>
        </select>
        
        <input type="text" name="search" value="${search}">
        <input type="submit" value="확인">&nbsp;&nbsp;&nbsp;
        <input type="button" id="btnWrite" value="글쓰기"></div>
    </form>    
 
    </article>
          <jsp:include page="boardSidebar.jsp" flush="false"/>
 
          <jsp:include page="boardFooter.jsp" flush="false"/>
 
cs


controller

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
    @RequestMapping("board/board_list.do")
    public String board_list(@RequestParam(defaultValue = "1"int curPage, Model model,
            @RequestParam(required = false, defaultValue = "username"String search_option,
            @RequestParam(required = false, defaultValue = ""String search) {
 
        /*
         * @RequestParam에 지정된 변수에 값이 넘어오지 않으면 400에러 발생 required=false 필수 입력항목이
         * 아님, 기본값은 required=true defaultValue= "기본값"
         */
 
        
        /*total page*/
        int count = boardService.boardCount(search_option, search);
 
        PageDAO pageDao = new PageDAO(count, curPage);
 
        int start = pageDao.getPageBegin();
        int end = pageDao.getPageEnd();
 
        List<BoardDTO> list = boardService.boardList(start, end, search_option, search);
 
        model.addAttribute("list", list);
 
        // 페이지 네비게이션 관련자료 저장
        model.addAttribute("page", pageDao);
 
        // 검색관련 정보 저장
        model.addAttribute("search_option", search_option);
        model.addAttribute("search", search);
 
        Logger.info("�럹�씠吏��젙蹂�:" + pageDao);
 
        return "board/board_list";
 
    }
cs



dao



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
@Override
    public List<BoardDTO> boardList(int start, int end, String search_option, String search) {
 
        List<BoardDTO> list = null;
 
        try {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("start", start);
            map.put("end", end);
            map.put("search_option", search_option);
            map.put("search", search);
            
            list = sqlSession.selectList("boardList", map);
 
        } catch (Exception e) {
            e.printStackTrace();
        }
 
        return list;
    }
 
 
 
// 媛쒖떆臾� �쟾泥� 媛쒖닔
    @Override
    public int boardCount(String search_option, String search) {
 
        int result = 0;
 
        try {
            
            Map<String,Object> map=new HashMap<String,Object>();
            map.put("search_option", search_option);
            map.put("search", search);
            
            result = sqlSession.selectOne("boardCount",map);
        } catch (Exception e) {
                e.printStackTrace();
        }
 
        return result;
    }
cs


mapper


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
<select id="boardCount" resultType="int">
 
        select count(*)
        from board b, TBL_MEMBER m
        where b.userid=m.userid
 
        <if test="search_option !='all' ">
            and
            ${search_option} like '%'||#{search}||'%'
 
        </if>
 
        <if test="search_option=='all' ">
 
            and
            (username like '%'||#{search}||'%'
 
            or subject like '%' || #{search} ||'%'
            or content like '%' || #{search}
            ||'%'
            )
 
        </if>
 
 
    </select>
 
 
 
 
<select id="boardList" resultType="boardDto">
        select
        idx,userid,username,subject,hit,post_date,filename,filesize,down,comment_count,ref,
        depth, reorder
        from
        (
        select A.*,rownum as rn
        from
        (
        select b.IDX, m.USERID,
        m.USERNAME,
        b.SUBJECT, b.hit, b.POST_DATE, b.filesize, b.filename,
        b.down,
        (select
        count(*) from board_comment where board_idx=b.idx)
        comment_count
        ,ref, depth, reorder
        from
        board b,
        TBL_MEMBER m
        where
        b.USERID = m.USERID
        
        <if test="search_option !='all' ">
            and
            ${search_option} like '%'||#{search}||'%'
 
        </if>
 
        <if test="search_option=='all' ">
 
            and
            (username like '%'||#{search}||'%'
 
            or subject like '%' || #{search} ||'%'
            or content like '%' || #{search}
            ||'%'
            )
 
        </if>
        order by ref desc, reorder asc )
        A
        )
        where rn
        between
        #{start} and #{end}
 
 
    </select>
 
cs


'매일코딩 > Spring' 카테고리의 다른 글

스프링 기초 DI 예제2  (0) 2018.07.16
스프링 기초 DI 예제1  (0) 2018.07.16
31.스프링프로젝트 - 조회  (0) 2016.11.21
30.스프링프로젝트 - 답변  (0) 2016.11.21
29.spring- detgul  (0) 2016.11.18
28.spring - hitup  (0) 2016.11.18





maper

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
-- list - det gul
 
 
select idx, b.userid,name,subject,hit,post_date,filename,filesize, (select count(*
 from board_comment
 where board_idx=b.idx) comment_count,b.ref,b.reorder,b.depth
from board b,member m 
where b.userid=m.userid 
order by b.ref desc, b.reorder asc limit 0,10;
 
 
 
update board set reorder=reorder+1
where ref=1
and reorder > 0;
        
        
        
        
        insert into board( userid, subject,content, ref,
        depth, reorder)
        values(
        'kim',
        'jemok',
        'content',103
 
        );
        
        commit;
cs



viw.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
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
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%-- <%@ page session="false"%> --%>
<c:set var="path" value="${pageContext.request.contextPath}"></c:set> 
 
 
<jsp:include page="boardHeader.jsp" flush="false"/>
 
 
                    <h1 id="product"><div>COMMUNITY</div></h1>
          <article>
              <h2>게시판</h2>
              
    <!-- 개발 경로가 아닌 실제 경로 -->
    <%-- <%=application.getRealPath("/upload")%> --%>
 
 
    <form name="form1" method="post" enctype="multipart/form-data">
        <table border="1" width="650px" align="center" >
 
 
 
            <tr>
                <td align="center">날짜</td>
                <td align="center">${dto.post_date}</td>
                <td align="center">조회수</td>
                <td align="center">${dto.hit}</td>
            </tr>
 
            <tr>
                <td align="center">제목</td>
                <td colspan="3"><input name="subject" size="80"
                    value="${dto.subject}"></td>
            </tr>
            <tr>
                <td align="center">내용</td>
                <td colspan="3"><textarea rows="5" cols="80" name="content"
                        id="content">${dto.content}</textarea>
                        
                        
                         <script>
                            //textarea의 id값과 일치해야함//textarea의 id값과 일치해야함
                            CKEDITOR
                                    .replace(
                                            'content',
                                            {
                                                filebrowserUploadUrl : '${pageContext.request.contextPath}/imageUpload.do'
 
                                            });
                        </script>
                        
                        
                        </td>
            <tr>
                <td align="center">첨부파일</td>
                <td colspan="3" width='30'>
                <c:if test="${dto.filesize>0 }">
                ${dto.filename} (${dto.filesize} bytes)
                <br>
                
                <input type="checkbox" name="fileDel">첨부파일 삭제
                
                </c:if>
                
                <input type="file" name="file1"></td>
 
            </tr>
 
 
 
 
            <tr>
                <td colspan="4" align="center">
                
                
                <!-- 로그인 했을때 답변달 수있게 했음 -->    
                <c:if test="${sessionScope.id != null}">
                <input type="button" value="답변" id="btnReply">
                </c:if>
            
            
                 <!-- 본인글만 수정/삭제가 가능하도록 처리 -->
                <c:if test="${sessionScope.id==dto.userid }">
                        <input type="button" value="수정" id="btnUpdate">
                        <input type="button" value="삭제" id="btnDelete">
                        <input type="button" value="목록" id="btnList">
                </c:if>
            
            
                </td>
            
            
            </tr>
        </table>
    </form>
 
 
 <!-- 답변글 작성을 위해 게시물 번호를 넘겨야함 -->
<input type="hidden" name="idx" id="idx" value="${dto.idx}">
 
    <!-- 댓글 작성폼(로그인한 사용자만 댓글 달기 허용) -->
 
 
    <div align="center" >
    
        <!-- if user is not null  only login-->
        <c:if test="${sessionScope.id != null }">
 
            <table style="width: 650px;" class="tbl_type">
                
<br>
                <font size="4" style="text-decoration : underline ;"><B>댓글달기</B></font>
                
      
        <br>
                
                <tr>
                <br>
                    <td ><textarea rows="3" cols="81" id="comment_content"></textarea></td>
                    <td><input type="button" style="width:40pt;height:40pt;" value="댓글" id="btnSave"></td>
                </tr>
            </table>
        </c:if>
    </div>
 
    <div id="commentList" align="center"></div>
 
 
    </article>
          <jsp:include page="boardSidebar.jsp" flush="false"/>
 
          <jsp:include page="boardFooter.jsp" flush="false"/>
cs



viwheader.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
   <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
 
<c:set var="path" value="${pageContext.request.contextPath}"></c:set> 
    
<html>
<head>
<meta charset="utf-8">
<title>Company</title>
 
<link href="../resources/css/reset.css" rel="stylesheet" type="text/css">
 
<link href="../resources/css/jquery.fancybox.css" rel="stylesheet" type="text/css">
 
 
<link href='http://fonts.googleapis.com/css?family=Droid+Sans'
    rel='stylesheet' type='text/css'>
    
    
    <style>
/* UI Object */
.tbl_type,.tbl_type th,.tbl_type td{border:0}
.tbl_type{width:75%;border-bottom:2px solid #dcdcdc;font-family:'돋움',dotum;font-size:12px;text-align:center;border-collapse:collapse}
.tbl_type caption{display:none}
.tbl_type tfoot{background-color:#f5f7f9;font-weight:bold}
.tbl_type th{padding:7px 4px;border-top:2px solid #dcdcdc;border-right:1px solid #dcdcdc;border-left:1px solid #dcdcdc;background-color:#f5f7f9;color:#666;font-family:'돋움',dotum;font-size:12px;font-weight:bold}
.tbl_type td{padding:6px 4px;border:1px solid #e5e5e5;color:#4c4c4c}
.tbl_type td.ranking{font-weight:bold}
/* //UI Object */
</style>
    
    <script src="http://code.jquery.com/jquery-1.12.4.js"></script>
    <script type="text/javascript">
    $(document).ready(
            function() { //웹페이지가 로딩되면
 
                comment_list('1'); //댓글 목록 가져오기
 
                //수정 버튼 클릭
                
                 $("#btnUpdate").click(function(){
                     
                     document.form1.action="${path}/board/board_update.do?idx="+$("#idx").val();
                         
                         /* ?idx="+$("#idx").val()
                             +"?subject="+$("#subject").val()+"?filename="+$("#filename").val()
                             +"?filesize="+$("#filesize").val()+"?content="+$(content).val(); */
                     document.form1.submit();
                 })
                
                
                
                 //글쓰기 버튼 클릭
                $("#btnWrite").click(function(){
                    location.href="${path}/board/write.do";
                });
                 
                 
                //목록 버튼 클릭
                $("#btnList").click(function(){
                    location.href="${path}/board/board_list.do";
                });
 
                //답변 버튼 클릭
                
                $("#btnReply").click(function(){
                
                    document.form1.action="${path}/board/board_reply.do?idx="+$("#idx").val();
                    document.form1.submit();
                });
                
                //삭제 버튼 클릭
                
                $("#btnDelete").click(function(){
                    
                    if(confirm("삭제하시겠습니까?")){
                        document.form1.action ="${path}/board/board_delete.do?idx="+$("#idx").val();
                        document.form1.submit();
                    }
                
                });
                
                
                
                
                
                $("#btnSave").click(
                        function() {//버튼 클릭 이벤트 등록
 
                            var param = "board_idx=${dto.idx}&content="
                                    + $("#comment_content").val();
                            //비동기 방식으로 댓글 쓰기, 결과값은 json 형식으로 리턴받음
 
                            $.ajax({
                                type : "post",
                                
                                /*  if this is empty..defalut type is html */
                                contentType : "application/json",
                                url : "${path}/board/comment_insert.do?"+param,
                                success : function() {
                                    
                                    //댓글쓰기가 완료되면 댓글 목록 갱신
                                    comment_list('1');
                                    
                                    //댓글 입력 텍스트상자 초기화
                                    $("#comment_content").val("");
                                }
 
                            });
 
                        });
            });
 
    //댓글 목록 가져오기
    function comment_list(page) {
 
        $.ajax({
            type : "post",
            contentType : "application/json",
            url : "${path}/board/comment_list.do?board_idx=${dto.idx}&curPage="+page,
            success : function(data) {
 
                /* var output = "<table width='800px' border='1'>";
                for ( var i in json) {
                    output += "<tr>";
                    output += "<td>" + json[i].post_date + "</td>";
                    output += "<td>" + json[i].content + "</td>";
                    output += "</tr>";
                }
                output += "</table>"; */
 
                $("#commentList").html(data);
            }
 
        });
 
    }
</script>
 
<script type="text/javascript" src="${path}/ckeditor/ckeditor.js"></script>
    
</head>
 
 
 
 
<body>
        <div id="wrap">
            
            <!-- 헤더부분 -->
            
            <header>
                <div id="logo"><a href="${pageContext.request.contextPath}/main/main.html">YNG Corp.</a> </div>
                <div id="hlink">
                    <ul>
                                    <c:choose>
                        <c:when test="${sessionScope.id==null }">
                            <!-- 세션변수 id 값이 없을때 -->
                            <li><a href="${path}/member/login">로그인·회원가입</a></li>
                        <!--     <li><a href="/web03/member/memberInsert">회원가입</a></li> -->
                        </c:when>
 
                        <c:otherwise>
                            <!-- 세션 변수 id 값이 있을때 -->
        
    [  ${sessionScope.name}님 로그인 중 ]
    <li><a href="${path}/member/logout">로그아웃</a></li>
    
                            <%-- <a href="${path}/pdf/pdf_save.do">pdf문서생성</a>
                            <a href="${path}/chart/chart1.do">차트보기</a> --%>
                            <%-- <li><a href="${path}/member/member_info.do">회원정보 수정</a></li> --%>
                        </c:otherwise>
 
                    </c:choose>
                    
                    </ul>
                </div>
                
                <nav>
                    <ul>
                        <li class="n1"><a href="${pageContext.request.contextPath}/company/company.html">회사소개</a></li>                    
                        <li class="n2"><a href="${pageContext.request.contextPath}/product/product.html">제품정보</a></li>
                        <li class="n3"><a href="${pageContext.request.contextPath}/board/board_list.do">커뮤니티</a></li>
                        <li class="n4"><a href="${pageContext.request.contextPath}/mail/mail_form.do">고객지원</a></li>
                    </ul>
                </nav>
            </header>    
cs


boardcontroller.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
    // 답변달기
    @RequestMapping("board/board_reply.do")
    public String board_reply(@RequestParam int idx, Model model) {
        BoardDTO dto = boardService.boardView(idx);
        
        String content = "================게시물의 내용================/n";
 
        dto.setContent(content + dto.getContent());
        model.addAttribute("dto", dto); // 모델에 저장
 
        // board/board_reply 로 포워딩
 
        return "board/board_reply";
    }
 
    // 답변글 입력하기
 
    @RequestMapping("board/reply_insert.do")
 
    public String reply_insert(@RequestParam int idx, @RequestParam String subject, @RequestParam String content,
            HttpSession session) {
 
        BoardDTO dto = boardService.boardView(idx);
        int ref = dto.getRef(); // 게시물그룹 번호
        int depth = dto.getDepth() + 1// 답변 단계
        int reorder = dto.getReorder() + 1// 같은 그룹 내에서의 순서
 
        String id = (String) session.getAttribute("id"); // 사용자 아이디
 
        // 게시물 그룹 내에서의 순서 조정
        boardService.reorderUpdate(ref, reorder);
 
        // 테이블에 저장
 
        dto = new BoardDTO();
        dto.setUserid(id);
        dto.setSubject(subject);
        dto.setContent(content);
        dto.setRef(ref);
        dto.setDepth(depth);
        dto.setReorder(reorder);
 
        boardService.replyInsert(dto);
        return "redirect:/board/board_list.do";
    }
cs



boardreply.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
    // 답변달기
    @RequestMapping("board/board_reply.do")
    public String board_reply(@RequestParam int idx, Model model) {
        BoardDTO dto = boardService.boardView(idx);
        
        String content = "================게시물의 내용================/n";
 
        dto.setContent(content + dto.getContent());
        model.addAttribute("dto", dto); // 모델에 저장
 
        // board/board_reply 로 포워딩
 
        return "board/board_reply";
    }
 
    // 답변글 입력하기
 
    @RequestMapping("board/reply_insert.do")
 
    public String reply_insert(@RequestParam int idx, @RequestParam String subject, @RequestParam String content,
            HttpSession session) {
 
        BoardDTO dto = boardService.boardView(idx);
        int ref = dto.getRef(); // 게시물그룹 번호
        int depth = dto.getDepth() + 1// 답변 단계
        int reorder = dto.getReorder() + 1// 같은 그룹 내에서의 순서
 
        String id = (String) session.getAttribute("id"); // 사용자 아이디
 
        // 게시물 그룹 내에서의 순서 조정
        boardService.reorderUpdate(ref, reorder);
 
        // 테이블에 저장
 
        dto = new BoardDTO();
        dto.setUserid(id);
        dto.setSubject(subject);
        dto.setContent(content);
        dto.setRef(ref);
        dto.setDepth(depth);
        dto.setReorder(reorder);
 
        boardService.replyInsert(dto);
        return "redirect:/board/board_list.do";
    }
cs



boardDAOImpl.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
@Override
    public void reorderUpdate(int ref, int reorder) {
 
        try {
 
            Map<String, Object> map = new HashMap<String, Object>();
 
            map.put("ref", ref);// 게시물 그룹 번호
            map.put("reorder", reorder); // 같은 게시물 그룹 내에서의 순서
            sqlSession.update("reorderUpdate", map);
 
        } catch (Exception e) {
            e.printStackTrace();
        }
 
    }
 
    @Override
    public void replyInsert(BoardDTO dto) {
 
        try {
 
            sqlSession.insert("replyInsert", dto);
 
        } catch (Exception e) {
 
            e.printStackTrace();
        }
 
    }
cs



boardList.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
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
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%-- <%@ page session="false"%> --%>
<c:set var="path" value="${pageContext.request.contextPath}"></c:set> 
 
 
 
 
<jsp:include page="boardHeader.jsp" flush="false"/>
 
 
                    <h1 id="community"><div>COMMUNITY</div></h1>
          <article>
              <h2>게시판</h2>
              
 
    
    <table border="1" align="center" class="tbl_type" WIDTH=50% table-layout: fixed>
        <tr>
            <th  nowrap WIDTH="40">번호</th>
            <th  nowrap WIDTH="100">이름</th>
            <th  nowrap WIDTH="250">제목</th>
            <th  nowrap WIDTH="100">날짜</th>
            <th  nowrap WIDTH="40">조회</th>
            <th  nowrap WIDTH="70">첨부파일</th>
            <th  nowrap WIDTH="70">다운로드</th>
        </tr>
 
 
        <c:forEach var="row" items="${list}">
            <tr>
                <td>${row.idx }</td>
                <td>${row.username }</td>
                <td>
                
                <!-- 답변 들여쓰기 -->
                <c:forEach begin="1" end="${row.depth }">
                &nbsp;&nbsp;
                </c:forEach>
    
    
 
                <a href="${path}/board/view.do?idx=${row.idx}">
                ${row.subject}</a>
                <c:if test="${row.comment_count >0 }">
            
            <span style="color:red">[${row.comment_count}]</span>
                
                </c:if>
                </td>
    
                <td>${row.post_date}</td>
                <td>${row.hit}</td>
                
                
                <!-- 첨부파일의 사이즈가 보다 크면 파일 다운로드 링크 표시 -->
                
                
                <td align="center">
                <c:if test="${row.filesize > 0 }">
                    <a href="${path}/board/down.do?idx=${row.idx}">
                    <img src="${path}/images/file.gif">
                </a>
                </c:if>
                </td>
 
                <td>${row.down}</td>
            </tr>
        </c:forEach>
 
 
<!-- page navigation -->
<tr align="center">
<td colspan="7">
<!-- 이전 -->
<c:if test="${page.curPage>1 }">
<a href="${path}/board/board_list.do?curPage=1&search_option=${search_option}&search=${search}">[시작] </a>
</c:if>
 
<c:if test="${page.curBlock > 1 }">
<a href="${path}/board/board_list.do?curPage=${page.prevPage}&search_option=${search_option}&search=${search}">[이전] </a>
</c:if>
 
 
 
<c:forEach var="pageNum" begin="${page.blockStart}" end="${page.blockEnd}">
 
<c:choose>
    <c:when test="${pageNum==page.curPage }">
 
    <span style="color:red">[${pageNum}]</span>
    </c:when>
    
    <c:otherwise>
<a href="${path}/board/board_list.do?curPage=${pageNum}&search_option=${search_option}&search=${search}">[${pageNum}] </a>&nbsp;
    </c:otherwise>
</c:choose>
 
</c:forEach>
 
<!-- 다음 -->
 
 
<c:if test="${page.curBlock <= page.totBlock}">
 
<a href="${path}/board/board_list.do?curPage=${page.nextPage}&search_option=${search_option}&search=${search}">[다음] </a>
</c:if>
 
<!-- 마지막 페이지 -->
 
<c:if test="${page.curPage < page.totPage}">
 
<a href="${path}/board/board_list.do?curPage=${page.totPage}&search_option=${search_option}&search=${search}">[끝] </a>
 
</c:if>
</td>
 
</tr>
 
    </table>
 
<br>
<!-- 검색폼 -->
 
    <form method="post" action="${path}/board/board_list.do">
        <div align="center"><select name="search_option">
            <option value="username"
            
            <c:if test= "${search_option =='username'}"> selected </c:if> >
            이름
            </option>
            
            <option value="subject" <c:if test= "${search_option =='subject'}"> selected </c:if> >제목</option>
            <option value="content" <c:if test= "${search_option =='content'}"> selected </c:if> >내용</option>
            <option value="all" <c:if test= "${search_option =='all'}"> selected </c:if> >전체</option>
        </select>
        
        <input type="text" name="search" value="${search}">
        <input type="submit" value="확인">&nbsp;&nbsp;&nbsp;
        <input type="button" id="btnWrite" value="글쓰기"></div>
    </form>    
 
    </article>
          <jsp:include page="boardSidebar.jsp" flush="false"/>
 
          <jsp:include page="boardFooter.jsp" flush="false"/>
 
cs



<insert id="replyInsert">


insert into board(idx, userid, subject,content, ref,

depth, reorder)

values(

(select nvl(max(idx)+1,1) from

board),#{userid},

#{subject},

#{content},#{ref}, #{depth}, #{reorder}


)

</insert>


<update id="reorderUpdate">


update board set reorder=reorder+1

where ref=#{ref}

and reorder > #{reorder}

</update>

'매일코딩 > Spring' 카테고리의 다른 글

스프링 기초 DI 예제1  (0) 2018.07.16
31.스프링프로젝트 - 조회  (0) 2016.11.21
30.스프링프로젝트 - 답변  (0) 2016.11.21
29.spring- detgul  (0) 2016.11.18
28.spring - hitup  (0) 2016.11.18
27.springproject - log  (0) 2016.11.18

* 컨트롤러를 @RestController로 선언

* 컨트롤러의 method를 @ResponseBody 로 선언

@RestController  // 스프링 4.0 이후 사용 가능

public class FileController {

@Inject

BoardDao boardDao;

@ResponseBody

@RequestMapping("board/board_ajax_list.do")

public  List boardList(){

List<BoardDto> list=boardDao.getBoardList(1,10);

return list;

}

}

* pom.xml에 라이브러리 추가

<!-- json 라이브러리 -->

<dependency>

    <groupId>com.fasterxml.jackson.core</groupId>

    <artifactId>jackson-databind</artifactId>

    <version>2.5.0</version>

</dependency>


CONTENT FROM:http://edu.lifesoft.org/board/show.aspx?category=spring&idx=375&page=0


0.view header.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
   <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
 
<c:set var="path" value="${pageContext.request.contextPath}"></c:set> 
    
<html>
<head>
<meta charset="utf-8">
<title>Company</title>
 
<link href="../resources/css/reset.css" rel="stylesheet" type="text/css">
 
<link href="../resources/css/jquery.fancybox.css" rel="stylesheet" type="text/css">
 
 
<link href='http://fonts.googleapis.com/css?family=Droid+Sans'
    rel='stylesheet' type='text/css'>
    
    
    <style>
/* UI Object */
.tbl_type,.tbl_type th,.tbl_type td{border:0}
.tbl_type{width:75%;border-bottom:2px solid #dcdcdc;font-family:'돋움',dotum;font-size:12px;text-align:center;border-collapse:collapse}
.tbl_type caption{display:none}
.tbl_type tfoot{background-color:#f5f7f9;font-weight:bold}
.tbl_type th{padding:7px 4px;border-top:2px solid #dcdcdc;border-right:1px solid #dcdcdc;border-left:1px solid #dcdcdc;background-color:#f5f7f9;color:#666;font-family:'돋움',dotum;font-size:12px;font-weight:bold}
.tbl_type td{padding:6px 4px;border:1px solid #e5e5e5;color:#4c4c4c}
.tbl_type td.ranking{font-weight:bold}
/* //UI Object */
</style>
    
    <script src="http://code.jquery.com/jquery-1.12.4.js"></script>
    <script type="text/javascript">
    $(document).ready(
            function() { //웹페이지가 로딩되면
 
                comment_list('1'); //댓글 목록 가져오기
 
                //수정 버튼 클릭
                
                 $("#btnUpdate").click(function(){
                     
                     document.form1.action="${path}/board/board_update.do?idx="+$("#idx").val();
                         
                         /* ?idx="+$("#idx").val()
                             +"?subject="+$("#subject").val()+"?filename="+$("#filename").val()
                             +"?filesize="+$("#filesize").val()+"?content="+$(content).val(); */
                     document.form1.submit();
                 })
                
                
                
                 //글쓰기 버튼 클릭
                $("#btnWrite").click(function(){
                    location.href="${path}/board/write.do";
                });
                 
                 
                //목록 버튼 클릭
                $("#btnList").click(function(){
                    location.href="${path}/board/board_list.do";
                });
 
                //답변 버튼 클릭
                
                $("#btnReply").click(function(){
                
                    document.form1.action="${path}/board/board_reply.do?idx="+$("#idx").val();
                    document.form1.submit();
                });
                
                //삭제 버튼 클릭
                
                $("#btnDelete").click(function(){
                    
                    if(confirm("삭제하시겠습니까?")){
                        document.form1.action ="${path}/board/board_delete.do?idx="+$("#idx").val();
                        document.form1.submit();
                    }
                
                });
                
                
                
                
                
                $("#btnSave").click(
                        function() {//버튼 클릭 이벤트 등록
 
                            var param = "board_idx=${dto.idx}&content="
                                    + $("#comment_content").val();
                            //비동기 방식으로 댓글 쓰기, 결과값은 json 형식으로 리턴받음
 
                            $.ajax({
                                type : "post",
                                
                                /*  if this is empty..defalut type is html */
                                contentType : "application/json",
                                url : "${path}/board/comment_insert.do?"+param,
                                success : function() {
                                    
                                    //댓글쓰기가 완료되면 댓글 목록 갱신
                                    comment_list('1');
                                    
                                    //댓글 입력 텍스트상자 초기화
                                    $("#comment_content").val("");
                                }
 
                            });
 
                        });
            });
 
    //댓글 목록 가져오기
    function comment_list(page) {
 
        $.ajax({
            type : "post",
            contentType : "application/json",
            url : "${path}/board/comment_list.do?board_idx=${dto.idx}&curPage="+page,
            success : function(data) {
 
                /* var output = "<table width='800px' border='1'>";
                for ( var i in json) {
                    output += "<tr>";
                    output += "<td>" + json[i].post_date + "</td>";
                    output += "<td>" + json[i].content + "</td>";
                    output += "</tr>";
                }
                output += "</table>"; */
 
                $("#commentList").html(data);
            }
 
        });
 
    }
</script>
 
<script type="text/javascript" src="${path}/ckeditor/ckeditor.js"></script>
    
</head>
 
 
 
 
<body>
        <div id="wrap">
            
            <!-- 헤더부분 -->
            
            <header>
                <div id="logo"><a href="${pageContext.request.contextPath}/main/main.html">YNG Corp.</a> </div>
                <div id="hlink">
                    <ul>
                                    <c:choose>
                        <c:when test="${sessionScope.id==null }">
                            <!-- 세션변수 id 값이 없을때 -->
                            <li><a href="${path}/member/login">로그인·회원가입</a></li>
                        <!--     <li><a href="/web03/member/memberInsert">회원가입</a></li> -->
                        </c:when>
 
                        <c:otherwise>
                            <!-- 세션 변수 id 값이 있을때 -->
        
    [  ${sessionScope.name}님 로그인 중 ]
    <li><a href="${path}/member/logout">로그아웃</a></li>
    
                            <%-- <a href="${path}/pdf/pdf_save.do">pdf문서생성</a>
                            <a href="${path}/chart/chart1.do">차트보기</a> --%>
                            <%-- <li><a href="${path}/member/member_info.do">회원정보 수정</a></li> --%>
                        </c:otherwise>
 
                    </c:choose>
                    
                    </ul>
                </div>
                
                <nav>
                    <ul>
                        <li class="n1"><a href="${pageContext.request.contextPath}/company/company.html">회사소개</a></li>                    
                        <li class="n2"><a href="${pageContext.request.contextPath}/product/product.html">제품정보</a></li>
                        <li class="n3"><a href="${pageContext.request.contextPath}/board/board_list.do">커뮤니티</a></li>
                        <li class="n4"><a href="${pageContext.request.contextPath}/mail/mail_form.do">고객지원</a></li>
                    </ul>
                </nav>
            </header>    
cs



1.view.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
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
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%-- <%@ page session="false"%> --%>
<c:set var="path" value="${pageContext.request.contextPath}"></c:set> 
 
 
<jsp:include page="boardHeader.jsp" flush="false"/>
 
 
                    <h1 id="product"><div>COMMUNITY</div></h1>
          <article>
              <h2>게시판</h2>
              
    <!-- 개발 경로가 아닌 실제 경로 -->
    <%-- <%=application.getRealPath("/upload")%> --%>
 
 
    <form name="form1" method="post" enctype="multipart/form-data">
        <table border="1" width="650px" align="center" >
 
 
 
            <tr>
                <td align="center">날짜</td>
                <td align="center">${dto.post_date}</td>
                <td align="center">조회수</td>
                <td align="center">${dto.hit}</td>
            </tr>
 
            <tr>
                <td align="center">제목</td>
                <td colspan="3"><input name="subject" size="80"
                    value="${dto.subject}"></td>
            </tr>
            <tr>
                <td align="center">내용</td>
                <td colspan="3"><textarea rows="5" cols="80" name="content"
                        id="content">${dto.content}</textarea>
                        
                        
                         <script>
                            //textarea의 id값과 일치해야함//textarea의 id값과 일치해야함
                            CKEDITOR
                                    .replace(
                                            'content',
                                            {
                                                filebrowserUploadUrl : '${pageContext.request.contextPath}/imageUpload.do'
 
                                            });
                        </script>
                        
                        
                        </td>
            <tr>
                <td align="center">첨부파일</td>
                <td colspan="3" width='30'>
                <c:if test="${dto.filesize>0 }">
                ${dto.filename} (${dto.filesize} bytes)
                <br>
                
                <input type="checkbox" name="fileDel">첨부파일 삭제
                
                </c:if>
                
                <input type="file" name="file1"></td>
 
            </tr>
 
 
 
 
            <tr>
                <td colspan="4" align="center">
                
                
                <!-- 로그인 했을때 답변달 수있게 했음 -->    
                <c:if test="${sessionScope.id != null}">
                <input type="button" value="답변" id="btnReply">
                </c:if>
            
            
                 <!-- 본인글만 수정/삭제가 가능하도록 처리 -->
                <c:if test="${sessionScope.id==dto.userid }">
                        <input type="button" value="수정" id="btnUpdate">
                        <input type="button" value="삭제" id="btnDelete">
                        <input type="button" value="목록" id="btnList">
                </c:if>
            
            
                </td>
            
            
            </tr>
        </table>
    </form>
 
 
 <!-- 답변글 작성을 위해 게시물 번호를 넘겨야함 -->
<input type="hidden" name="idx" id="idx" value="${dto.idx}">
 
    <!-- 댓글 작성폼(로그인한 사용자만 댓글 달기 허용) -->
 
 
    <div align="center" >
    
        <!-- if user is not null  only login-->
        <c:if test="${sessionScope.id != null }">
 
            <table style="width: 650px;" class="tbl_type">
                
<br>
                <font size="4" style="text-decoration : underline ;"><B>댓글달기</B></font>
                
      
        <br>
                
                <tr>
                <br>
                    <td ><textarea rows="3" cols="81" id="comment_content"></textarea></td>
                    <td><input type="button" style="width:40pt;height:40pt;" value="댓글" id="btnSave"></td>
                </tr>
            </table>
        </c:if>
    </div>
 
    <div id="commentList" align="center"></div>
 
 
    </article>
          <jsp:include page="boardSidebar.jsp" flush="false"/>
 
          <jsp:include page="boardFooter.jsp" flush="false"/>
cs


2.commentDTO


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
package com.example.web03.model.board.dto;
 
import java.sql.Date;
 
public class CommentDTO {
 
    
    private int comment_idx;
    private int board_idx;
    private String userid;
    private String username;
    private String content;
    
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    private Date post_date;
    public int getComment_idx() {
        return comment_idx;
    }
    public void setComment_idx(int comment_idx) {
        this.comment_idx = comment_idx;
    }
    public int getBoard_idx() {
        return board_idx;
    }
    public void setBoard_idx(int board_idx) {
        this.board_idx = board_idx;
    }
    public String getUserid() {
        return userid;
    }
    public void setUserid(String userid) {
        this.userid = userid;
    }
    public String getContent() {
        return content;
    }
    public void setContent(String content) {
        this.content = content;
    }
    public Date getPost_date() {
        return post_date;
    }
    public void setPost_date(Date post_date) {
        this.post_date = post_date;
    }
    @Override
    public String toString() {
        return "CommentDTO [comment_idx=" + comment_idx + ", board_idx=" + board_idx + ", userid=" + userid
                + ", content=" + content + ", post_date=" + post_date + "]";
    }
    
    
    
    
}
 
cs





3.COMMENTCONTROOLER


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
package com.example.web03.controller.board;
 
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
import javax.inject.Inject;
import javax.servlet.http.HttpSession;
 
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
 
import com.example.web03.model.board.dao.PageDAO;
import com.example.web03.model.board.dto.CommentDTO;
import com.example.web03.service.board.BoardService;
 
//RestController : ajax 처리 전용 컨트롤러 (백그라운드에서 실행되는 컨트롤러)
 
@RestController // 스프링 4.0이상 부터 가능
public class CommentController {
 
    @Inject
    BoardService boardService;
 
    // 댓글목록을 리턴
    @ResponseBody // 리턴자료형을 json으로 변환
    @RequestMapping("board/comment_list.do")
    public ModelAndView comment_list(
            @RequestParam(defaultValue="1"int curPage,
            @RequestParam int board_idx, Model model) {
        
        //댓글 갯수 개산
        int count =boardService.commentCount(board_idx);
        
        //페이지 나누기 관련 클래스
        PageDAO pageDao=new PageDAO(count,curPage);
                int start=pageDao.getPageBegin();
                int end=pageDao.getPageEnd();
        
                
                
        // 게시물 번호가 board_idx 변수에 저장됨
        List<CommentDTO> list = boardService.commentList(board_idx,start,end);
 
        Map<String,Object> map=new HashMap<String,Object>();
        map.put("list", list);    //맵에 리스트 추가
        map.put("page", pageDao);    // 맵에 페이지 정보 추가
        
        //board/comment_list.jsp 로 포워딩
        ModelAndView mav=new ModelAndView("board/comment_list","map",map);
    
        // new ModelAndView("포워딩할 jsp 페이지",모델변수명, 모델변수 값);
        // 뷰로 포워딩되지 않고 데이터만 ajax를 호출한 페이지로 넘김(json포멧)
        return mav;
    }
 
    @RequestMapping("board/comment_insert.do")
    public void comment_insert(@RequestParam int board_idx, @RequestParam String content, HttpSession session) {
 
        String id=(String)session.getAttribute("id");
        
        CommentDTO dto=new CommentDTO();
        dto.setUserid(id);
        dto.setBoard_idx(board_idx);
        dto.setContent(content);
        
        boardService.commentInsert(dto);
    }
 
}
 
cs



COMMENTDAO

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
package com.example.web03.model.board.dao;
 
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
import javax.inject.Inject;
 
import org.apache.ibatis.session.SqlSession;
import org.springframework.stereotype.Repository;
 
import com.example.web03.model.board.dto.CommentDTO;
 
@Repository // 스프링에서 관리하는 dao bean
public class CommentDAOImpl implements CommentDAO {
 
    // 주입
    @Inject
    SqlSession sqlSession;
 
    @Override
    public List<CommentDTO> commentList(int board_idx,int start,int end) {
 
        List<CommentDTO> list = null;
 
        
        Map<String,Object> map=new HashMap<String,Object>();
        
        map.put("board_idx", board_idx);
        map.put("start", start);
        map.put("end", end);
        
        try {
 
            list = sqlSession.selectList("commentList", map);
 
        } catch (Exception e) {
            e.printStackTrace();
        }
 
        return list;
    }
 
    @Override
    public void commentInsert(CommentDTO dto) {
 
        try {
            sqlSession.insert("commentInsert", dto);
        } catch (Exception e) {
            e.printStackTrace();
        }
 
    }
 
    @Override
    public int commentCount(int board_idx) {
 
        int count = 0;
 
        try {
            count = sqlSession.selectOne("commentCount", board_idx);
        } catch (Exception e) {
        }
 
        return count;
    }
 
}
 
cs


BOARDSERVICE

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
package com.example.web03.service.board;
 
import java.io.File;
import java.util.List;
 
import javax.inject.Inject;
 
import org.springframework.stereotype.Service;
 
import com.example.web03.model.board.dao.BoardDAO;
import com.example.web03.model.board.dao.CommentDAO;
import com.example.web03.model.board.dto.BoardDTO;
import com.example.web03.model.board.dto.CommentDTO;
 
@Service // �쁽�옱 �겢�옒�뒪瑜� �뒪�봽留� �꽌鍮꾩뒪 鍮덉쑝濡� �벑濡앹떆�궡
public class BoardServiceImpl implements BoardService {
 
    @Inject
    BoardDAO boardDAO; // BoardDAOImpl �씤�뒪�꽩�뒪瑜� �깮�꽦�븯�뿬 二쇱엯�떆�궡
 
    @Inject
    CommentDAO commentDao;
    
    @Override
    public List<BoardDTO> boardList(int start, int end,String search_option, String search) {
 
        List<BoardDTO> list;
 
        list = boardDAO.boardList(start, end,search_option,search);
 
        return list;
    }
 
    // 湲��벐湲�+ �뙆�씪�뾽濡쒕뱶
    @Override
    public void boardInsert(BoardDTO dto) {
        boardDAO.boardInsert(dto);
 
    }
 
    // �뙆�씪�씠由� �뼸湲�
    @Override
    public String getFilename(int idx) {
        return boardDAO.getFilename(idx);
    }
 
    // �떎�슫濡쒕뱶 �슏�닔 利앷�
    @Override
    public void downUp(int idx) {
 
        boardDAO.downUp(idx);
 
    }
    //珥앷컻�떆臾쇱닔 援ы븯湲�
    @Override
    public int boardCount(String search_option, String search) {
 
        return boardDAO.boardCount(search_option,search);
    }
 
    
    
    @Override
    public BoardDTO boardView(int idx) {
        System.out.println("check service");
        
        return boardDAO.boardView(idx);
    }
 
    @Override
    public void hitUp(int id) {
        
        boardDAO.hitUp(id);
        
    }
 
    @Override
    public List<CommentDTO> commentList(int board_idx,int start,int end) {
        
        return commentDao.commentList(board_idx,start,end);
    }
 
    @Override
    public void commentInsert(CommentDTO dto) {
        
        commentDao.commentInsert(dto);
    }
 
    @Override
    public int commentCount(int board_idx) {
        
        return commentDao.commentCount(board_idx);
    }
 
    @Override
    public void reorderUpdate(int ref, int reorder) {
        boardDAO.reorderUpdate(ref, reorder);
        
    }
 
    @Override
    public void replyInsert(BoardDTO dto) {
 
        boardDAO.replyInsert(dto);
        
    }
    
    
    //게시물 삭제
    @Override
    public void boardDelete(int idx) {
        
        
        boardDAO.boardDelete(idx);
    }
 
    @Override
    public void boardUpdate(BoardDTO dto) {
        boardDAO.boardUpdate(dto);
        
    }
 
 
    @Override
    public void deleteFile(String filename) {
        
        try {
            File f=new File("d:\\upload\\"+filename);
            if(f!=null && f.exists()){
                
                f.delete();//파일을 삭제함    
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        
    }
 
}
 
cs




POM.XML INSERT

1
2
3
4
5
6
7
8
        <!-- json라이브러리 -->
        <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.5.0</version>
        </dependency>
 
cs




-- det gul  list & comment count query


1
2
3
4
5
6
7
8
9
10
11
12
13
 
 -- det gul  list & comment count query
 
 
 select idx, b.userid,name,subject,hit,post_date,filename,filesize,
    
    (select count(*
     from board_comment
     where board_idx=b.idx) comment_count
 
from board b,member m 
where b.userid=m.userid 
order by idx limit 0,10;





cs


-- detgul pazing



select *

from board_comment b, member m

where b.userid=m.userid

and board_idx = 572

order by comment_idx limit 0,10;


board_list.jsp


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
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
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%-- <%@ page session="false"%> --%>
<c:set var="path" value="${pageContext.request.contextPath}"></c:set> 
 
 
 
 
<jsp:include page="boardHeader.jsp" flush="false"/>
 
 
                    <h1 id="community"><div>COMMUNITY</div></h1>
          <article>
              <h2>게시판</h2>
              
 
    
    <table border="1" align="center" class="tbl_type" WIDTH=50% table-layout: fixed>
        <tr>
            <th  nowrap WIDTH="40">번호</th>
            <th  nowrap WIDTH="100">이름</th>
            <th  nowrap WIDTH="250">제목</th>
            <th  nowrap WIDTH="100">날짜</th>
            <th  nowrap WIDTH="40">조회</th>
            <th  nowrap WIDTH="70">첨부파일</th>
            <th  nowrap WIDTH="70">다운로드</th>
        </tr>
 
 
        <c:forEach var="row" items="${list}">
            <tr>
                <td>${row.idx }</td>
                <td>${row.username }</td>
                <td>
                
                <!-- 답변 들여쓰기 -->
                <c:forEach begin="1" end="${row.depth }">
                &nbsp;&nbsp;
                </c:forEach>
    
    
 
                <a href="${path}/board/view.do?idx=${row.idx}">
                ${row.subject}</a>
                <c:if test="${row.comment_count >0 }">
            
            <span style="color:red">[${row.comment_count}]</span>
                
                </c:if>
                </td>
    
                <td>${row.post_date}</td>
                <td>${row.hit}</td>
                
                
                <!-- 첨부파일의 사이즈가 보다 크면 파일 다운로드 링크 표시 -->
                
                
                <td align="center">
                <c:if test="${row.filesize > 0 }">
                    <a href="${path}/board/down.do?idx=${row.idx}">
                    <img src="${path}/images/file.gif">
                </a>
                </c:if>
                </td>
 
                <td>${row.down}</td>
            </tr>
        </c:forEach>
 
 
<!-- page navigation -->
<tr align="center">
<td colspan="7">
<!-- 이전 -->
<c:if test="${page.curPage>1 }">
<a href="${path}/board/board_list.do?curPage=1&search_option=${search_option}&search=${search}">[시작] </a>
</c:if>
 
<c:if test="${page.curBlock > 1 }">
<a href="${path}/board/board_list.do?curPage=${page.prevPage}&search_option=${search_option}&search=${search}">[이전] </a>
</c:if>
 
 
 
<c:forEach var="pageNum" begin="${page.blockStart}" end="${page.blockEnd}">
 
<c:choose>
    <c:when test="${pageNum==page.curPage }">
 
    <span style="color:red">[${pageNum}]</span>
    </c:when>
    
    <c:otherwise>
<a href="${path}/board/board_list.do?curPage=${pageNum}&search_option=${search_option}&search=${search}">[${pageNum}] </a>&nbsp;
    </c:otherwise>
</c:choose>
 
</c:forEach>
 
<!-- 다음 -->
 
 
<c:if test="${page.curBlock <= page.totBlock}">
 
<a href="${path}/board/board_list.do?curPage=${page.nextPage}&search_option=${search_option}&search=${search}">[다음] </a>
</c:if>
 
<!-- 마지막 페이지 -->
 
<c:if test="${page.curPage < page.totPage}">
 
<a href="${path}/board/board_list.do?curPage=${page.totPage}&search_option=${search_option}&search=${search}">[끝] </a>
 
</c:if>
</td>
 
</tr>
 
    </table>
 
<br>
<!-- 검색폼 -->
 
    <form method="post" action="${path}/board/board_list.do">
        <div align="center"><select name="search_option">
            <option value="username"
            
            <c:if test= "${search_option =='username'}"> selected </c:if> >
            이름
            </option>
            
            <option value="subject" <c:if test= "${search_option =='subject'}"> selected </c:if> >제목</option>
            <option value="content" <c:if test= "${search_option =='content'}"> selected </c:if> >내용</option>
            <option value="all" <c:if test= "${search_option =='all'}"> selected </c:if> >전체</option>
        </select>
        
        <input type="text" name="search" value="${search}">
        <input type="submit" value="확인">&nbsp;&nbsp;&nbsp;
        <input type="button" id="btnWrite" value="글쓰기"></div>
    </form>    
 
    </article>
          <jsp:include page="boardSidebar.jsp" flush="false"/>
 
          <jsp:include page="boardFooter.jsp" flush="false"/>
 
cs



'매일코딩 > Spring' 카테고리의 다른 글

31.스프링프로젝트 - 조회  (0) 2016.11.21
30.스프링프로젝트 - 답변  (0) 2016.11.21
29.spring- detgul  (0) 2016.11.18
28.spring - hitup  (0) 2016.11.18
27.springproject - log  (0) 2016.11.18
26.스프링프로젝트 - 페이징 처리  (0) 2016.11.17

1.controller


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
    @RequestMapping("board/view.do")
    public String view(@RequestParam int idx, Model model) throws Exception {
 
        
        
        boardService.hitUp(idx);
 
        BoardDTO dto = boardService.boardView(idx);
 
        model.addAttribute("dto", dto);
 
        return "board/view";
    }
    
    
    
    
cs




2.service,  dao


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
@Override
    public BoardDTO boardView(int idx) {
 
        System.out.println("check dao");
 
        BoardDTO dto = null;
 
        try {
            dto = sqlSession.selectOne("boardView", idx);
        } catch (Exception e) {
            e.printStackTrace();
        }
 
        return dto;
    }
 
    @Override
    public void hitUp(int idx) {
 
        try {
            sqlSession.update("hitUp", idx);
        } catch (Exception e) {
 
            e.printStackTrace();
        }
 
    }
    
    
cs


3.mapper


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<update id="hitUp">
 
        update board set hit=hit+where idx=#{idx}
    </update>
 
 
 
    <select id="boardView" resultType="boardDto">
 
        select * from board
        where idx =
        #{idx}
    </select>
 
    
    
    
    
    
cs


4. view.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
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
 
    <%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%-- <%@ page session="false"%> --%>
<c:set var="path" value="${pageContext.request.contextPath}"></c:set> 
 
 
<jsp:include page="boardHeader.jsp" flush="false"/>
 
 
                    <h1 id="product"><div>COMMUNITY</div></h1>
          <article>
              <h2>게시판</h2>
              
    <!-- 개발 경로가 아닌 실제 경로 -->
    <%-- <%=application.getRealPath("/upload")%> --%>
 
 
    <form name="form1" method="post" enctype="multipart/form-data">
        <table border="1" width="650px" align="center" >
 
 
 
            <tr>
                <td align="center">날짜</td>
                <td align="center">${dto.post_date}</td>
                <td align="center">조회수</td>
                <td align="center">${dto.hit}</td>
            </tr>
 
            <tr>
                <td align="center">제목</td>
                <td colspan="3"><input name="subject" size="80"
                    value="${dto.subject}"></td>
            </tr>
            <tr>
                <td align="center">내용</td>
                <td colspan="3"><textarea rows="5" cols="80" name="content"
                        id="content">${dto.content}</textarea>
                        
                        
                         <script>
                            //textarea의 id값과 일치해야함//textarea의 id값과 일치해야함
                            CKEDITOR
                                    .replace(
                                            'content',
                                            {
                                                filebrowserUploadUrl : '${pageContext.request.contextPath}/imageUpload.do'
 
                                            });
                        </script>
                        
                        
                        </td>
            <tr>
                <td align="center">첨부파일</td>
                <td colspan="3" width='30'>
                <c:if test="${dto.filesize>0 }">
                ${dto.filename} (${dto.filesize} bytes)
                <br>
                
                <input type="checkbox" name="fileDel">첨부파일 삭제
                
                </c:if>
                
                <input type="file" name="file1"></td>
 
            </tr>
 
 
 
 
            <tr>
                <td colspan="4" align="center">
                
                
                <!-- 로그인 했을때 답변달 수있게 했음 -->    
                <c:if test="${sessionScope.id != null}">
                <input type="button" value="답변" id="btnReply">
                </c:if>
            
            
                 <!-- 본인글만 수정/삭제가 가능하도록 처리 -->
                <c:if test="${sessionScope.id==dto.userid }">
                        <input type="button" value="수정" id="btnUpdate">
                        <input type="button" value="삭제" id="btnDelete">
                        <input type="button" value="목록" id="btnList">
                </c:if>
            
            
                </td>
            
            
            </tr>
        </table>
    </form>
 
 
 <!-- 답변글 작성을 위해 게시물 번호를 넘겨야함 -->
<input type="hidden" name="idx" id="idx" value="${dto.idx}">
 
    <!-- 댓글 작성폼(로그인한 사용자만 댓글 달기 허용) -->
 
 
    <div align="center" >
        <c:if test="${sessionScope.id != null }">
 
            <table style="width: 650px;" class="tbl_type">
                
<br>
                <font size="4" style="text-decoration : underline ;"><B>댓글달기</B></font>
                
      
        <br>
                
                <tr>
                <br>
                    <td ><textarea rows="3" cols="81" id="comment_content"></textarea></td>
                    <td><input type="button" style="width:40pt;height:40pt;" value="댓글" id="btnSave"></td>
                </tr>
            </table>
        </c:if>
    </div>
 
    <div id="commentList" align="center"></div>
 
 
    </article>
          <jsp:include page="boardSidebar.jsp" flush="false"/>
 
          <jsp:include page="boardFooter.jsp" flush="false"/>
cs


'매일코딩 > Spring' 카테고리의 다른 글

30.스프링프로젝트 - 답변  (0) 2016.11.21
29.spring- detgul  (0) 2016.11.18
28.spring - hitup  (0) 2016.11.18
27.springproject - log  (0) 2016.11.18
26.스프링프로젝트 - 페이징 처리  (0) 2016.11.17
25.스프링프로젝트 - aop  (0) 2016.11.17

* 로깅툴을 사용하는 이유


- System.out.println() 명령어는 IO 리소스를 많이 사용하여 시스템이 느려질 수 있음


- 로그를 파일로 저장하여 분석할 필요가 있음




* 로깅툴의 종류


- commons-logging : 스프링 3에서 사용하던 로깅툴


- log4j : 효율적인 메모리 관리로 그동안 많이 사용되었음


- logback : log4j 보다 성능이 더 우수하여 최근에 많이 사용되고 있음




* SLF4J : logback을 사용하기 위한 인터페이스



from : http://edu.lifesoft.org/board/show.aspx?category=spring&idx=379&page=0




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
* 설정방법
 
 
 
1. pom.xml 의 slf4j-version 을 1.7.21 로 수정
 
 
 
    <properties>
 
        <java-version>1.8</java-version>
 
        <org.springframework-version>4.3.0.RELEASE</org.springframework-version>
 
        <org.aspectj-version>1.6.10</org.aspectj-version>
 
        <org.slf4j-version>1.7.21</org.slf4j-version>
 
    </properties>
 
 
 
2. pom.xml 에 라이브러리 추가
 
        <!-- logback 로깅 관련 -->
 
        <dependency>
 
            <groupId>org.slf4j</groupId>
 
            <artifactId>jcl-over-slf4j</artifactId>
 
            <version>1.7.21</version>
 
        </dependency>
 
        <dependency>
 
            <groupId>ch.qos.logback</groupId>
 
            <artifactId>logback-classic</artifactId>
 
            <version>1.1.7</version>
 
        </dependency>
 
cs




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
3. src/main/resources 에 logback.xml 파일 작성
 
 
 
<?xml version="1.0" encoding="UTF-8"?>
 
<configuration>
 
 
 
    <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
 
        <layout class="ch.qos.logback.classic.PatternLayout">
 
            <pattern>%d{HH:mm:ss.SSS} [%thread] %-4level [%logger.%method:%line]-
 
                %msg%n</pattern>
 
        </layout>
 
    </appender>
 
 
 
    <appender name="LOGFILE"
 
        class="ch.qos.logback.core.rolling.RollingFileAppender">
 
        <file>/WEB-INF/logback.log</file>
 
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
 
            <fileNamePattern>logback.%d{yyyy-MM-dd}.log</fileNamePattern>
 
            <!-- 30일 지난 파일은 삭제한다. -->
 
            <maxHistory>30</maxHistory>
 
        </rollingPolicy>
 
        <encoder>
 
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} %-4level [%logger.%method:%line]
 
                - %msg %n</pattern>
 
        </encoder>
 
    </appender>
 
 
 
    <!-- 로그의 레벨( 지정된 로그 레벨 이상만 수집 ) : DEBUG < INFO < WARN < ERROR < FATAL -->
 
    <logger name="myweb" additivity="false">
 
        <level value="INFO" />
 
        <appender-ref ref="LOGFILE" />
 
        <appender-ref ref="CONSOLE" />
 
    </logger>
 
 
 
    <root>
 
        <level value="INFO" />
 
        <appender-ref ref="CONSOLE" />
 
    </root>
 
 
 
</configuration>
 
cs



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
4. 로그를 수집할 클래스에 변수 선언
 
 
 
private static final Logger logger = LoggerFactory.getLogger(클래스이름.class);
 
 
 
private : 외부에서 로그를 가로채지 못하도록 하기 위해서
 
static final : 로그 내용이 바뀌지 않으므로
 
 
 
5. 로그를 수집할 method에서 로그 수집 명령어 호출 
 
 
 
logger.info("로그 타이틀",  출력할 값);
 
 
 
* 로그의 level
 
1. Debug : Debug, Info, Warn, Error 포함
 
2. Info : Info, Warn, Error 포함
 
3. Warn : Warn, Error 포함
 
4. Error : Error만 포함
 
 
 
<!-- logback 로깅 관련 -->
 
        <dependency>
 
            <groupId>org.slf4j</groupId>
 
            <artifactId>jcl-over-slf4j</artifactId>
 
            <version>1.7.21</version>
 
        </dependency>
 
        <dependency>
 
            <groupId>ch.qos.logback</groupId>
 
            <artifactId>logback-classic</artifactId>
 
            <version>1.1.7</version>
 
        </dependency>
        
        
        
        
        
        
        
@Controller // 
 
public class BoardController {
 
    // log fild
    private static final Logger Logger = LoggerFactory.getLogger(BoardController.class);
 
    
    
    @Inject
    BoardService boardService; // BoardServiceImpl�쓣 二쇱엯�떆�궡
 
    @RequestMapping("board/board_delete.do")
    public String board_delete(@RequestParam int idx) {
 
        boardService.boardDelete(idx);
        return "redirect:/board/board_list.do";
    }
 
    @RequestMapping("board/board_list.do")
    public String board_list(@RequestParam(defaultValue = "1"int curPage, Model model,
            @RequestParam(required = false, defaultValue = "username"String search_option,
            @RequestParam(required = false, defaultValue = ""String search) {
 
        /*
         * @RequestParam에 지정된 변수에 값이 넘어오지 않으면 400에러 발생 required=false 필수 입력항목이
         * 아님, 기본값은 required=true defaultValue= "기본값"
         */
 
        int count = boardService.boardCount(search_option, search);
 
        PageDAO pageDao = new PageDAO(count, curPage);
 
        int start = pageDao.getPageBegin();
        int end = pageDao.getPageEnd();
 
        List<BoardDTO> list = boardService.boardList(start, end, search_option, search);
 
        model.addAttribute("list", list);
 
        // 페이지 네비게이션 관련자료 저장
        model.addAttribute("page", pageDao);
 
        // 검색관련 정보 저장
        model.addAttribute("search_option", search_option);
        model.addAttribute("search", search);
 
        //log output
        Logger.info("pageinfo:" + pageDao);
 
        return "board/board_list";
 
    }
    
    
    
    
    
    
    -> if there is a problem ->maven -> updatemaven
    
    
    
    
    
cs




systemout.println() =====> loger


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 com.example.web03.aop;
 
import java.util.Arrays;
 
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
 
import com.example.web03.controller.board.BoardController;
 
//종단 관심 - 핵심적인 비즈니스 로직 join , buy,
//횡단관심(aspect) 공통적인 로직 (로그, 트랜젝션 등등)
// Advice - 횡단관심을 모든 코드에서 처리하지 않고 공통적으로 처리 할 수 있도록 지원하는 코드
 
@Component // 스프링에서 관리하는 빈
@Aspect // 스프링에서 관리하는 aop bean
 
public class LogAdvice {
    // 포인트컷 - before, after,실행 시점, around 실행 전후
    // 컨트롤러의 모든 method 실행 전후에 logPrint method가 호출됨
 
    // 로거 변수 만들기
    private static final Logger Logger = LoggerFactory.getLogger(LogAdvice.class);
 
    @Around("execution(* com.example.web03.controller..*Controller.*(..))"
            + " or execution(* com.example.web03.service..*Impl.*(..))"
            + " or execution(* com.example.web03.model..*Impl.*(..))")
    public Object logPrint(ProceedingJoinPoint joinPoint) throws Throwable {
 
        // 현재 시스템의 시간
        long startTime = System.currentTimeMillis();
 
        // 컨트롤러의 method가 실행됨
        Object result = joinPoint.proceed();
 
        // 클래스 이름
        String type = joinPoint.getSignature().getDeclaringTypeName();
        // method 이름
        String method = joinPoint.getSignature().getName();
        // 매개변수
        String args = Arrays.toString(joinPoint.getArgs());
 
        /*
         * System.out.println("클래스" + type); System.out.println("method" +
         * method); System.out.println("매개변수" + args);
         */
        // 로깅 툴을 이용한 로거 찍기
 
        Logger.info("클래스=" + type);
        Logger.info("method=" + method);
        Logger.info("매개변수=" + args);
 
        long endTime = System.currentTimeMillis();
 
        Logger.info("실행시간=" + (endTime - startTime));
        Logger.info("=================================================");
        /*
         * System.out.println("실행시간" + (endTime - startTime));
         * System.out.println(
         * "=================================================");
         */
        return result;
    }
}
cs


'매일코딩 > Spring' 카테고리의 다른 글

29.spring- detgul  (0) 2016.11.18
28.spring - hitup  (0) 2016.11.18
27.springproject - log  (0) 2016.11.18
26.스프링프로젝트 - 페이징 처리  (0) 2016.11.17
25.스프링프로젝트 - aop  (0) 2016.11.17
24.스프링프로젝트 - download  (0) 2016.11.17





1. list page


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
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%-- <%@ page session="false"%> --%>
<c:set var="path" value="${pageContext.request.contextPath}"></c:set> 
 
 
 
 
<jsp:include page="boardHeader.jsp" flush="false"/>
 
 
                    <h1 id="community"><div>COMMUNITY</div></h1>
          <article>
              <h2>게시판</h2>
              
 
    
    <table border="1" align="center" class="tbl_type" WIDTH=50% table-layout: fixed>
        <tr>
            <th  nowrap WIDTH="40">번호</th>
            <th  nowrap WIDTH="100">이름</th>
            <th  nowrap WIDTH="250">제목</th>
            <th  nowrap WIDTH="100">날짜</th>
            <th  nowrap WIDTH="40">조회</th>
            <th  nowrap WIDTH="70">첨부파일</th>
            <th  nowrap WIDTH="70">다운로드</th>
        </tr>
 
 
        <c:forEach var="row" items="${list}">
            <tr>
                <td>${row.idx }</td>
                <td>${row.username }</td>
                <td>
                
                <!-- 답변 들여쓰기 -->
                <c:forEach begin="1" end="${row.depth }">
                &nbsp;&nbsp;
                </c:forEach>
    
    
 
                <a href="${path}/board/view.do?idx=${row.idx}">
                ${row.subject}</a>
                <c:if test="${row.comment_count >0 }">
            
            <span style="color:red">[${row.comment_count}]</span>
                
                </c:if>
                </td>
    
                <td>${row.post_date}</td>
                <td>${row.hit}</td>
                
                
                <!-- 첨부파일의 사이즈가 보다 크면 파일 다운로드 링크 표시 -->
                
                
                <td align="center">
                <c:if test="${row.filesize > 0 }">
                    <a href="${path}/board/down.do?idx=${row.idx}">
                    <img src="${path}/images/file.gif">
                </a>
                </c:if>
                </td>
 
                <td>${row.down}</td>
            </tr>
        </c:forEach>
 
 
<!-- page navigation -->
<tr align="center">
<td colspan="7">
<!-- 이전 -->
<c:if test="${page.curPage>1 }">
<a href="${path}/board/board_list.do?curPage=1&search_option=${search_option}&search=${search}">[시작] </a>
</c:if>
 
<c:if test="${page.curBlock > 1 }">
<a href="${path}/board/board_list.do?curPage=${page.prevPage}&search_option=${search_option}&search=${search}">[이전] </a>
</c:if>
 
 
 
<c:forEach var="pageNum" begin="${page.blockStart}" end="${page.blockEnd}">
 
<c:choose>
    <c:when test="${pageNum==page.curPage }">
 
    <span style="color:red">[${pageNum}]</span>
    </c:when>
    
    <c:otherwise>
<a href="${path}/board/board_list.do?curPage=${pageNum}&search_option=${search_option}&search=${search}">[${pageNum}] </a>&nbsp;
    </c:otherwise>
</c:choose>
 
</c:forEach>
 
<!-- 다음 -->
 
 
<c:if test="${page.curBlock <= page.totBlock}">
 
<a href="${path}/board/board_list.do?curPage=${page.nextPage}&search_option=${search_option}&search=${search}">[다음] </a>
</c:if>
 
<!-- 마지막 페이지 -->
 
<c:if test="${page.curPage < page.totPage}">
 
<a href="${path}/board/board_list.do?curPage=${page.totPage}&search_option=${search_option}&search=${search}">[끝] </a>
 
</c:if>
</td>
 
</tr>
 
    </table>
 
<br>
<!-- 검색폼 -->
 
    <form method="post" action="${path}/board/board_list.do">
        <div align="center"><select name="search_option">
            <option value="username"
            
            <c:if test= "${search_option =='username'}"> selected </c:if> >
            이름
            </option>
            
            <option value="subject" <c:if test= "${search_option =='subject'}"> selected </c:if> >제목</option>
            <option value="content" <c:if test= "${search_option =='content'}"> selected </c:if> >내용</option>
            <option value="all" <c:if test= "${search_option =='all'}"> selected </c:if> >전체</option>
        </select>
        
        <input type="text" name="search" value="${search}">
        <input type="submit" value="확인">&nbsp;&nbsp;&nbsp;
        <input type="button" id="btnWrite" value="글쓰기"></div>
    </form>    
 
    </article>
          <jsp:include page="boardSidebar.jsp" flush="false"/>
 
          <jsp:include page="boardFooter.jsp" flush="false"/>
 
cs





controller 



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
 
 
@RequestMapping("board/board_list.do")
    public String board_list(@RequestParam(defaultValue = "1"int curPage, Model model,
            @RequestParam(required = false, defaultValue = "username"String search_option,
            @RequestParam(required = false, defaultValue = ""String search) {
 
        /*
         * @RequestParam에 지정된 변수에 값이 넘어오지 않으면 400에러 발생 required=false 필수 입력항목이
         * 아님, 기본값은 required=true defaultValue= "기본값"
         */
 
        int count = boardService.boardCount(search_option, search);
 
        PageDAO pageDao = new PageDAO(count, curPage);
 
        int start = pageDao.getPageBegin();
        int end = pageDao.getPageEnd();
 
        List<BoardDTO> list = boardService.boardList(start, end, search_option, search);
 
        model.addAttribute("list", list);
 
        // 페이지 네비게이션 관련자료 저장
        model.addAttribute("page", pageDao);
 
        // 검색관련 정보 저장
        model.addAttribute("search_option", search_option);
        model.addAttribute("search", search);
 
        Logger.info("�럹�씠吏��젙蹂�:" + pageDao);
 
        return "board/board_list";
 
    }
    
    
cs




3.page dao


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
package com.example.web03.model.board.dao;
 
public class PageDAO {
 
    public static final int PAGE_SCALE = 10// 페이지당 게시물 수
    public static final int BLOCK_SCALE = 5// 블록당 페이지수
 
    private int curPage; // 현재 페이지 번호
    private int prevPage; // 이전 페이지
    private int nextPage; // 다음 페이지
    private int totPage; // 전체 페이지 갯수
    private int curBlock; // 현재 페이지 블록 번호
    private int totBlock; // 전체 페이지 블록 갯수
    private int pageBegin; // 페이지 내에서의 레코드 시작 번호
    private int pageEnd; // 페이지 내에서의 레코드 마지막 번호
    private int blockStart; // 페이지 블록 내에서의 시작 페이지 번호
    private int blockEnd; // 페이지 블록 내에서의 마지막 페이지 번호
 
    public int getCurPage() {
        return curPage;
    }
 
    public void setCurPage(int curPage) {
        this.curPage = curPage;
    }
 
    public int getPrevPage() {
        return prevPage;
    }
 
    public void setPrevPage(int prevPage) {
        this.prevPage = prevPage;
    }
 
    public int getNextPage() {
        return nextPage;
    }
 
    public void setNextPage(int nextPage) {
        this.nextPage = nextPage;
    }
 
    public int getTotPage() {
        return totPage;
    }
 
    public void setTotPage(int count) {
 
        totPage = (int) Math.ceil(count * 1./ PAGE_SCALE);
 
    }
 
    public int getCurBlock() {
        return curBlock;
    }
 
    public void setCurBlock(int curBlock) {
        this.curBlock = curBlock;
    }
 
    public int getTotBlock() {
        return totBlock;
    }
 
    public void setTotBlock(int totBlock) {
        this.totBlock = totBlock;
    }
 
    public int getPageBegin() {
        return pageBegin;
    }
 
    public void setPageBegin(int pageBegin) {
        this.pageBegin = pageBegin;
    }
 
    public int getPageEnd() {
        return pageEnd;
    }
 
    public void setPageEnd(int pageEnd) {
        this.pageEnd = pageEnd;
    }
 
    public int getBlockStart() {
        return blockStart;
    }
 
    public void setBlockStart(int blockStart) {
        this.blockStart = blockStart;
    }
 
    public int getBlockEnd() {
        return blockEnd;
    }
 
    public void setBlockEnd(int blockEnd) {
        this.blockEnd = blockEnd;
    }
 
    // 생성자
    public PageDAO(int count, int curPage) {
 
        curBlock = 1// 현재 페이지 블록을 1로 설정
        this.curPage = curPage; // 현재 페이지 번호 설정
        setTotPage(count); // 전체 페이저 갯수 설정
        setPageRange(); // 편재 페이지 시작번호, 끝번호 계산
        setTotBlock(); // 전체 페이지 블록 갯수 계산
        setBlockRange(); // 현재 페이지 블록의 시작 페이지 끝페이지 번호 계산
 
    }
 
    // 현재 페이지가 몇번째 페이지에 속하는지 계산
    public void setBlockRange() {
 
        
        //현재 페이지가 몇번째 페이지 블록에 속하는지 계산
        curBlock = (int) Math.ceil((curPage - 1/ BLOCK_SCALE) + 1
        blockStart = (curBlock - 1* BLOCK_SCALE + 1;    //시작번호
 
        blockEnd = blockStart + BLOCK_SCALE - 1;        //끝번호
 
        if (blockEnd > totPage) {        //마지막 페이지가 범위를 초과할 경우
            blockEnd = totPage;
        }
        
        //현재 블록이 1이면 이전 페이지를 1로 설정
        prevPage = curBlock == : (curBlock - 1* BLOCK_SCALE;
 
        //현재 블록이 마지막 블록이면 다음 페이지를 마지막 페이지 번호로 설정
        nextPage = curBlock > totBlock ? (curBlock * BLOCK_SCALE) : (curBlock * BLOCK_SCALE) + 1;
 
        //마지막 페이지가 범위를 넘지 않도록 처리
        if (nextPage >= totPage) {
 
            nextPage = totPage;
        }
    }
 
    // 전체 페이지 블록 갯수 계산
    public void setTotBlock() {
 
        totBlock = (int) Math.ceil(totPage / BLOCK_SCALE);
 
    }
 
    // 현제페이지의 시작번호, 끝번호 계산
    public void setPageRange() {
 
        pageBegin = (curPage - 1* PAGE_SCALE + 1;
        pageEnd = pageBegin + PAGE_SCALE - 1;
 
    }
 
}
 
 
cs




4service


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
    
    @Service 
public class BoardServiceImpl implements BoardService {
 
    @Inject
    BoardDAO boardDAO; // BoardDAOImpl �씤�뒪�꽩�뒪瑜� �깮�꽦�븯�뿬 二쇱엯�떆�궡
 
    @Inject
    CommentDAO commentDao;
    
    @Override
    public List<BoardDTO> boardList(int start, int end,String search_option, String search) {
 
        List<BoardDTO> list;
 
        list = boardDAO.boardList(start, end,search_option,search);
 
        return list;
    }
    
    
    
        //count
    @Override
    public int boardCount(String search_option, String search) {
 
        return boardDAO.boardCount(search_option,search);
    }
 
    
cs



5dao


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
//dao 
    
    
        public List<BoardDTO> boardList(int start, int end, String search_option, String search) {
 
        List<BoardDTO> list = null;
 
        try {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("start", start);
            map.put("end", end);
            map.put("search_option", search_option);
            map.put("search", search);
            
            list = sqlSession.selectList("boardList", map);
 
        } catch (Exception e) {
            e.printStackTrace();
        }
 
        return list;
    }
    
    
    
        @Override
    public int boardCount(String search_option, String search) {
 
        int result = 0;
 
        try {
            
            Map<String,Object> map=new HashMap<String,Object>();
            map.put("search_option", search_option);
            map.put("search", search);
            
            result = sqlSession.selectOne("boardCount",map);
        } catch (Exception e) {
                e.printStackTrace();
        }
 
        return result;
    }
    
    
cs



mapper 


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
//mapper
    
    
    <select id="boardList" resultType="boardDto">
        select
        idx,userid,username,subject,hit,post_date,filename,filesize,down,comment_count,ref,
        depth, reorder
        from
        (
        select A.*,rownum as rn
        from
        (
        select b.IDX, m.USERID,
        m.USERNAME,
        b.SUBJECT, b.hit, b.POST_DATE, b.filesize, b.filename,
        b.down,
        (select
        count(*) from board_comment where board_idx=b.idx)
        comment_count
        ,ref, depth, reorder
        from
        board b,
        TBL_MEMBER m
        where
        b.USERID = m.USERID
        <if test="search_option !='all' ">
            and
            ${search_option} like '%'||#{search}||'%'
 
        </if>
 
        <if test="search_option=='all' ">
 
            and
            (username like '%'||#{search}||'%'
 
            or subject like '%' || #{search} ||'%'
            or content like '%' || #{search}
            ||'%'
            )
 
        </if>
        order by ref desc, reorder asc )
        A
        )
        where rn
        between
        #{start} and #{end}
 
 
    </select>
 
    
    
    
    <select id="boardCount" resultType="int">
 
        select count(*)
        from board b, TBL_MEMBER m
        where b.userid=m.userid
 
        <if test="search_option !='all' ">
            and
            ${search_option} like '%'||#{search}||'%'
 
        </if>
 
        <if test="search_option=='all' ">
 
            and
            (username like '%'||#{search}||'%'
 
            or subject like '%' || #{search} ||'%'
            or content like '%' || #{search}
            ||'%'
            )
 
        </if>
 
 
    </select>
    
    
    
 -----------------------------------------------------   
    
    
-- mysql procduer insert 
 
DELIMITER $$
DROP PROCEDURE IF EXISTS FILL_RATE_TEST_DATA$$
CREATE PROCEDURE FILL_RATE_TEST_DATA()
BEGIN
    DECLARE i INT DEFAULT 1;
    
 
    WHILE i <= 567 DO
        
insert into board(userid,subject,content,ref) values
('kim2','제목','내용',(select * from (select ifnull ( max(idx)+1) from board) as idx));
        
        SET i = i + 1;
    END WHILE;
END$$
DELIMITER $$
 
 
-- call proceduer
CALL FILL_RATE_TEST_DATA();
 
 
select userid from member;
select userid from board;
 
 
--  board , member join 
 
select idx, b.userid,name,subject,hit,post_date
from board b,member m
where b.userid=m.userid 
order by idx limit 0,10;
 
-- board count
select count(*) from board;
    
    
cs


'매일코딩 > Spring' 카테고리의 다른 글

28.spring - hitup  (0) 2016.11.18
27.springproject - log  (0) 2016.11.18
26.스프링프로젝트 - 페이징 처리  (0) 2016.11.17
25.스프링프로젝트 - aop  (0) 2016.11.17
24.스프링프로젝트 - download  (0) 2016.11.17
23.스프링프로젝트 - board write  (0) 2016.11.17

+ Recent posts

티스토리 툴바