메뉴 건너뛰기

?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄 첨부
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄 첨부

MVC 패턴 & 도서 목록 컨트롤러에서 해당 URL 받아서 처리하기 

 

 

 

 

1.리스트 화면으로 바로 이동 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE  >
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
 
    <%
        // context path 가져오기
        // context path : 웨프로젝트의 식별자
 
        String context = request.getContextPath();
 
        //페이지 이동
 
        response.sendRedirect(context + "/book_servlet/list.do");
    %>
 
 
</body>
</html>
cs

 

 

2. 북 컨트롤러

 

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
package book;
 
import java.io.IOException;
import java.util.ArrayList;
 
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
//url patter 지정 
//
 
//컨트롤러는 하나인데 다양한 url이 넘어온다. 그래서 구분 작업을 해줘야 한다.
 
@WebServlet("/book_servlet/*")
public class BookController extends HttpServlet {
    private static final long serialVersionUID = 1L;
 
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
 
        System.out.println("서블릿 호출");
 
        // 한글처리
        request.setCharacterEncoding("utf-8");
 
        // 컨텍스트 페스 경로가져오기
        String context = request.getContextPath();
        // DAO생성
        BookDAO dao = new BookDAO();
        // 폼에서 입력 받은 데이터를 DTO에 저장
 
        // http://localhost:8282/web02/book_servlet/list.do
        String url = request.getRequestURL().toString();
 
        // 문자열. indexOf("검색어") 검색어의 인덱스가 리턴됨
        // 검색어가 포함되어 있지 않으면 -1리턴
        
        // 북테이블 리스트
        if (url.indexOf("list.do"!= -1) {
                
            //도서 목록을 List로 리턴받음
            ArrayList<bookDTO> list=dao.bookList();
            
            //request 영역에 저장(요청페이지+출력페이지)
            request.setAttribute("items", list);
                
            //포워딩할 페이지 주소
            String page="/book/book_list2.jsp";
            
            //포워딩할 페이지의 정보분석
            RequestDispatcher rd=request.getRequestDispatcher(page);
            
            //포워드(주소고정, 화면전환, 데이터 전달)
            rd.forward(request, response);
            
            //북 테이블 삽입
        } else if (url.indexOf("insert.do"!= -1) {
 
            String title = request.getParameter("title");
            String author = request.getParameter("author");
            int price = Integer.parseInt(request.getParameter("price"));
            int qty = Integer.parseInt(request.getParameter("qty"));
 
            bookDTO dto = new bookDTO(title, author, price, qty);
 
            // 테이블에 저장
            dao.bookInsert(dto);
 
            // 페이지 이동
            response.sendRedirect(context + "/book/book_list.jsp");
 
        }
        
        //북 테이블 상세 보기
        else if(url.indexOf("view.do"!= -1){
            
            int id = Integer.parseInt(request.getParameter("id"));
            
            //dao에 자료요청
            
            bookDTO dto=dao.bookDetail(id);
            
            // 자료저장
            
            request.setAttribute("dto", dto);
            
            // 페이지 이동
            //포워드 할때는 context 가 자동으로 붙어서 필요없다.
            String page= "/book/book_view.jsp";
            
            RequestDispatcher rd=
            request.getRequestDispatcher(page);
            
            rd.forward(request, response);
        }
        
 
    }
 
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
 
        doGet(request, response);
    }
 
}
 
cs

 

 

3. 리스트 페이지

 

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
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
 
<%@page import="book.*"%>
<%@page import="java.util.ArrayList"%>
<!DOCTYPE  >
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
 
    <h2>도서목록</h2>
 
    <input type="button" value="도서등록" onclick="location.href='insert.jsp' ">
 
 
    <table border="1">
 
        <tr>
            <th>번호</th>
            <th>도서명</th>
            <th>저자</th>
            <th>가격</th>
            <th>수량</th>
 
        </tr>
 
 
        <%
            //request.setAttribute(key,value);
            // request.getAttribute(key);
 
            String path = request.getContextPath();
 
            ArrayList<bookDTO> list = (ArrayList<bookDTO>) request.getAttribute("items");
 
            for (bookDTO dto : list) {
        %>
 
        <tr>
            <td><%=dto.getId()%></td>
 
            <!-- 제목에 하이퍼 링크 걸기 -->
            
            <td><a href"<%=path%>/book_servlet/view.do?id=<%=dto.getId()%> ">
 
                    <%=dto.getTitle()%>
            </a></td>
 
            <td><%=dto.getAuthor()%></td>
            <td><%=dto.getPrice()%></td>
            <td><%=dto.getQty()%></td>
 
        </tr>
 
 
 
        <%
            } //for 문의 끝
        %>
    </table>
 
</body>
</html>
cs

 

 

 

4. 상세 페이지 로 이동

 

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
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
 
<%@ page import="book.bookDTO"%>
<!DOCTYPE  >
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
 
<script src="http://code.jquery.com/jquery-3.1.0.js">
    
</script>
 
<script>
    $(document).ready(function() {
 
        $("#btnAdd").click(function() { //버튼 클릭이벤트
 
            var title = $("#title").val(); //태그입력값
            var author = $("#author").val();
            var price = $("#price").val();
            var qty = $("#qty").val();
 
            if (title == "") { //빈값이면
 
                alert("도서명을 입력하세요")
                $("#title").focus(); //입력포커스 이동
                return//함수 종료
 
            }
 
            if (author == "") {
 
                alert("저자명을 입력하세요")
                $("#author").focus();
                return;
 
            }
 
            if (price == 0) {
 
                alert("가격을 입력하세요")
                $("#price").focus();
                return;
 
            }
 
            if (qty == 0) {
 
                alert("수량을 입력하세요")
                $("#qty").focus();
                return;
 
            }
 
            /* 폼에 입력한 데이터를 서버로 전송 */
            document.form1.submit();
        });
 
    });
</script>
 
</head>
<body>
    <!-- request.getContextPath() = 컨택스트 페스를 리턴함 -->
    a
    <!-- ction ="/컨텍스트/가상디렉토리 / 서블릿 url" -->
    <!-- id 는 jsp에서 쓸 것이고 name은 서블릿에서 사용할 것이다. -->
    <h2>도서 정보 등록</h2>
 
 
    <%
        bookDTO dto = (bookDTO) request.getAttribute("dto");
    %>
 
 
    <form name="form1" method="post">
 
        <table border="1">
            <tr>
                <td>도서명</td>
                <td><input name="title" id="title" value="<%=dto.getTitle() %>"></td>
            </tr>
 
            <tr>
                <td>저자</td>
                <td><input type="text" name="author" id="author" value="<%=dto.getAuthor() %>"></td>
            </tr>
 
 
            <tr>
                <td>가격</td>
                <td><input type="number" name="price" id="price" value="<%=dto.getPrice() %>" required></td>
            </tr>
 
            <tr>
                <td>수량</td>
                <td><input type="number" name="qty" id="qty" value="<%=dto.getQty() %>" required></td>
            </tr>
 
 
            <tr>
                <td colspan="2" align="center"><input type="button" id="btnAdd"
                    value="확인"> <input type="reset" value="취소"></td>
            </tr>
 
 
        </table>
 
    </form>
 
</body>
</html>
cs

 


 


하단 정보를 입력할 수 있습니다

© k2s0o1d4e0s2i1g5n. All Rights Reserved