티스토리 뷰

영화 데이터베이스를 이용하여

영화의 정보 ( 장르, 감독, 배우, 상영등급 ) 의 정보를 검색, 추가 하는 연습을 하였다.

 

영화 데이터베이스 ERD

 

 

 

 

1. 영화 추가를 누르면 추가할 영화의 정보를 입력하는 페이지로 이동한다. -> addNewMovie.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
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="<c:url value="/resource/js/jquery-1.12.1.js"/>"></script>
<script type="text/javascript">
    
    $(document).ready (function() {
 
        $("#addNewMovie").click( function() {
            
            // Validation Check
            var movieTitle = $("#movieTitle").val();
            movieTitle = $.trim( movieTitle ); // side 의 공백을 날려버린다.
            if ( movieTitle == "" ) {
                alert("영화명을 입력하세요.");
                return//밑에 꺼는 실행 안되게 막는다.
            }
            
            var rate = $("#rate").val();
            rate = $.trim( rate ); // side 의 공백을 날려버린다.
            if ( rate == "" ) {
                alert("평점을 입력하세요.");
                return//밑에 꺼는 실행 안되게 막는다.
            }
            
            //rate = parseFloat(rate); //parseInt하면 소수점이 날라가기 때문에 parseFloat로 한다.
            ifisNaN(rate) ){
                alert("평점을 올바르게 입력하세요!\n평점은 소수점을 포함한 숫자로 적을 수 있습니다.");
                return;
            }
            
            /* var isNumber = isNan(rate); //is not a number
            alert(isNumber);
            return; */
            
            var runningTime = $("#runningTime").val();
            runningTime = $.trim( runningTime ); // side 의 공백을 날려버린다.
            if ( runningTime == "" ) {
                alert("상영시간을 입력하세요.");
                return//밑에 꺼는 실행 안되게 막는다.
            }
            if( runningTime.length > 5 ) { // 한글영어숫자 모두 한 글자를 1로본다. 
                alert("상영시간을 올바르게 입력하세요.");
                return;
            }
            
            var regExp = new RegExp("^[0-2][0-9]:[0-5][0-9]$"); //^는 반드시 [0-9]{1,2}의 문자열로 시작한다는 의미 , $는 반드시 [0-9]{1,2}의 문자열로 끝난다는 의미
            var isValidRunningTime = regExp.test( runningTime ); // side 의 공백을 날려버린다.
            if ( isValidRunningTime == false ) {
                alert("상영시간을 올바르게 입력하세요.");
                return;
            }
            
            
            var openDate = $("#openDate").val();
            openDate = $.trim( openDate ); // side 의 공백을 날려버린다.
            if ( openDate == "" ) {
                alert("개봉일을 입력하세요.");
                return//밑에 꺼는 실행 안되게 막는다.
            }
            
            var grade = $(".grade:checked").val(); //class는 .으로 표현한다.
            grade = $.trim( grade ); // side 의 공백을 날려버린다.
            if ( grade == "" ) {
                alert("등급을 입력하세요.");
                return//밑에 꺼는 실행 안되게 막는다.
            }
            
            var directors = $("#directors option:selected").val().each();
            directors = $.trim( directors ); // side 의 공백을 날려버린다.
            alert(directors);
            if ( directors == "" ) {
                alert("감독을 선택하세요.");
                return//밑에 꺼는 실행 안되게 막는다.
            }
            
            var genres = $(".genres:checked").val(); //class는 .으로 표현한다.
            genres = $.trim( genres ); // side 의 공백을 날려버린다.
            if ( genres == "" ) {
                alert("장르를 선택하세요.");
                return//밑에 꺼는 실행 안되게 막는다.
            }
            
            var form = $("#addNewMovieForm");
            form.attr("method""post");
            form.attr("action""<c:url value="/addNewMovieAction" />");
            form.submit();
        });
        
    }); 
</script>
</head>
<body>
 
    <h1>영화 등록</h1>
    <hr/>
    <form id="addNewMovieForm">
        영화명 : <input type="text" id="movieTitle" name="movieTitle" /><br/>
        평점 : <input type="text" id="rate" name="rate" /><br/>
        상영시간 : <input type="text" id="runningTime" name="runningTime"/> <br/>
        개봉일 : <input type="date" id="openDate" name="openDate" /><br/>
        상영등급 : 
        
        <c:forEach items="${ gradeList }" var="grade">
        <input type="radio" class="grade" name="grade" value="${ grade.gradeId }" /> ${ grade.gradeTitle }
        </c:forEach>
        <br/>
        감독 : 
        <select id = "directors" name="directors" multiple="multiple">
            <c:forEach items="${ directorList }" var="director">
                <option value="${ director.directorId }">${ director.directorName }</option>
            </c:forEach>
        </select>
        <span id="directorsName"></span>
        
        <br/>
        출연진 :
        <select id = "actors" name="actors" multiple="multiple">
            <c:forEach items="${ actorList }" var="actor">
                <option value="${ actor.actorId }">${ actor.actorName }</option>
            </c:forEach>
        </select>
        <br/>
        장르 : 
        <c:forEach items="${ genreList }" var="genre">
            <input type="checkbox" class="genres" name="genres" value="${ genre.genreId }" />${ genre.genreTitle }
        </c:forEach>
        <br/>    
        <input type="button" id="addNewMovie" value="영화 등록" />
    </form>
</body>
</html>
cs

 

 

 

2. jsp에서 form을 /addNewMovieAction 서블릿으로 보내주어( 89-92번 line ) 테이블에 INSERT 해준다.

 

AddNewMovieActionServlet.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
package com.ktds.jmj.web;
 
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import com.ktds.jmj.dao.ActorDAO;
import com.ktds.jmj.dao.DirectorDAO;
import com.ktds.jmj.dao.GenreDAO;
import com.ktds.jmj.dao.MovieDAO;
import com.ktds.jmj.vo.ActorVO;
import com.ktds.jmj.vo.DirectorVO;
import com.ktds.jmj.vo.GenreVO;
import com.ktds.jmj.vo.MovieVO;
 
/**
 * Servlet implementation class AddNewMovieActionServlet
 */
public class AddNewMovieActionServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private MovieDAO movieDAO;
    private GenreDAO genreDAO;
    private ActorDAO actorDAO;
    private DirectorDAO directorDAO;
    
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AddNewMovieActionServlet() {
        super();
        movieDAO = new MovieDAO();
        genreDAO = new GenreDAO();
        actorDAO = new ActorDAO();
        directorDAO = new DirectorDAO();
        // TODO Auto-generated constructor stub
    }
 
    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.sendError(HttpServletResponse.SC_FORBIDDEN, "잘못된 요청입니다.");
    }
 
    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
        request.setCharacterEncoding("UTF-8");
        
        //jsp에서의 name이 파라미터의 키이다.
        String movieTitle = request.getParameter("movieTitle");
        String rate = request.getParameter("rate");
        String runningTime = request.getParameter("runningTime");
        String openDate = request.getParameter("openDate");
        String grade = request.getParameter("grade");
        
        List<String> directors = Arrays.asList(request.getParameterValues("directors")); //.getParameterValues로 여러개 받아와서 배열을 리스트로 바꾼다.
        // select는 원래 getParameterValues 안쓰지만 multiple때문에 써줬다.
        
        List<String> actors = Arrays.asList(request.getParameterValues("actors"));
        
        List<String> genres = Arrays.asList(request.getParameterValues("genres")); // checkbox는 100%컬랙션이다.
        
        
        if ( movieTitle == null || movieTitle.length() == 0 ){ // 입력하지 않았다면
            response.sendRedirect("/Movie/addNewMovie?errorCode=" + MovieValidateConst.MISSING_MOVIE_TITLE);
            return;
        }
        if (rate == null || rate.length() == 0 ) {
            response.sendRedirect("/Movie/addNewMovie?errorCode=" + MovieValidateConst.MISSING_RATE);
            return;
        }
        try{
            double ratePoint = Double.parseDouble(rate);
        }
        catch(NumberFormatException nfe){
            response.sendRedirect("/Movie/addNewMovie?errorCode=" + MovieValidateConst.MISSING_RATE);
            return;
        }
        
        if (runningTime == null || runningTime.length() == 0 ) {
            response.sendRedirect("/Movie/addNewMovie?errorCode=" + MovieValidateConst.MISSING_RUNNING_TIME);
            return;
        }
        if( runningTime.length() > 5 ) {
            response.sendRedirect("/Movie/addNewMovie?errorCode=" + MovieValidateConst.MISSING_RUNNING_TIME);
            return;
        }
        Pattern p = Pattern.compile("^[0-2][0-9]:[0-5][0-9]$"); // 정규표현식 검사
        Matcher m = p.matcher(runningTime);
        
        if ( ! m.matches() ) {
            response.sendRedirect("/Movie/addNewMovie?errorCode=" + MovieValidateConst.MISSING_RUNNING_TIME);
            return;
        }
        
        if (openDate == null || openDate.length() == 0 ) {
            response.sendRedirect("/Movie/addNewMovie?errorCode=" + MovieValidateConst.MISSING_OPEN_DATE);
            return;
        }
        
        if ( grade == null || grade.length() == 0 ) {
            response.sendRedirect("/Movie/addNewMovie?errorCode=" + MovieValidateConst.MISSING_GRADE);
            return;
        }
        
        if ( directors == null || directors.size() == 0 ) {
            response.sendRedirect("/Movie/addNewMovie?errorCode=" + MovieValidateConst.MISSING_DIRECTORS);
            return;
        }
        
        if ( actors == null || actors.size() == 0 ) {
            response.sendRedirect("/Movie/addNewMovie?errorCode=" + MovieValidateConst.MISSING_ACTORS);
            return;
        }
        
        if ( genres == null || genres.size() == 0 ) {
            response.sendRedirect("/Movie/addNewMovie?errorCode=" + MovieValidateConst.MISSING_GENRES);
            return;
        }
        
        MovieVO movie = new MovieVO();
        movie.setTitle(movieTitle);
        movie.setRate(Double.parseDouble(rate));
        movie.setRunningTime(runningTime);
        movie.setOpenDate(openDate);
        movie.setGradeId(Integer.parseInt(grade));
        
        int newMovieId = movieDAO.insertNewMovie(movie);
        
        if ( newMovieId > 0) {
            GenreVO genre = new GenreVO();
            genre.setMovieId(newMovieId);
            
            forString selectedGenre : genres ) {
                genre.setGenreId(Integer.parseInt(selectedGenre));
                genreDAO.insertNewGenreOfNewMovieId(genre);
            }
            //
            ActorVO actor = new ActorVO();
            actor.setMovieId(newMovieId);
            
            forString selectedActor : actors ){
                actor.setActorId(Integer.parseInt(selectedActor));
                actorDAO.insertNewActorOfNewMovieId(actor);
            }
            //
            DirectorVO director = new DirectorVO();    
            director.setMovieId(newMovieId);
            
            forString selectedDirector : directors ){
                director.setDirectorId(Integer.parseInt(selectedDirector));
                directorDAO.insertNewDirectorOfNewMovieId(director);
            }
        
        }
        
        response.sendRedirect("/Movie/movie");
            
        
    }
 
}
 
cs

 

 

 

3. servlet에서 수행하는 DAO 부분

MovieDAO.java  부분의 insertNewMoive를 수행하는 부분

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
public int insertNewMovie( MovieVO movie ){//movieID를 리턴할것이다.
        int insertCount = 0;
        
        // 1. DriverLoading
        loadOracleDriver();
        
        Connection conn = null;
        PreparedStatement stmt = null;
//        ResultSet rs = null; insert 할것이므로 필요없다.
        
        try {
            conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE""MOVIE""MOVIE");
            
            String query = XML.getNodeString("//query/movie/insertNewMovie/text()");
            stmt = conn.prepareStatement(query);
            
            //SQL Parameter Mapping
            //?에 데이터 넣기
            stmt.setString(1, movie.getTitle());// 파라미터 맵핑?
            stmt.setDouble(2, movie.getRate());
            stmt.setString(3, movie.getRunningTime());
            stmt.setString(4, movie.getOpenDate());
            stmt.setInt(5, movie.getGradeId());
            
            insertCount = stmt.executeUpdate();
            //parameterIndex : 하나의 쿼리에서 몇번째 물음표인지 물어보는것            
            
            if ( insertCount > 0 ) { // 잘 등록 되었다면
                stmt.close(); // close를 시켜줘야 다음쿼리를 할 수 있다.
                query = XML.getNodeString("//query/movie/getLastestMovieId/text()");
                stmt = conn.prepareStatement(query);
                
                ResultSet rs = stmt.executeQuery();
                
                int movieId = 0;
                
                if( rs.next() ) {
                    movieId = rs.getInt(1); // 첫번째 컬럼을 가지고 와라.
                }
                
                rs.close();
                return movieId;
            }
                    
        } catch (SQLException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
        finally {
            closeDB(conn, stmt, null);
        }
        
        return insertCount; 
    }
cs

 

 

4. 1번의 입력 폼에서 감독과 배우 장르를 모두 등록해줬기 때문에 movie를 Insert 한 이후

감독, 배우, 장르를 INSERT 하기 위해 이들의 FK가 되는 현재 insert한 MOVIE_ID를 가져온다.

방금 등록한 MOVIE의 MOVIE_ID를 가져오기 위하여 INSERT 쿼리를 수행한 이후 stmt를 닫아준 이후 새로운 쿼리를 수행한다.

   SELECT MOVIE_ID_SEQ.CURRVAL
   FROM   DUAL

의 쿼리로 현재 시퀀스의 값을 가져온다.

가져온 MOVIE_ID에 해당하는 감독, 배우, 장르를 INSERT 한다.

 

DirectorDAO.java 에서 Insert 하는 부분

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
public void insertNewDirectorOfNewMovieId( DirectorVO director ){
        
        // 1. DriverLoading
        loadOracleDriver();
        
        Connection conn = null;
        PreparedStatement stmt = null;
//        ResultSet rs = null; insert 할것이므로 필요없다.
        
        try {
            conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE""MOVIE""MOVIE");
            
            String query = XML.getNodeString("//query/movie/insertNewDirectedMovie/text()");
            stmt = conn.prepareStatement(query);
            
            //SQL Parameter Mapping
            //?에 데이터 넣기
            stmt.setInt( 1, director.getDirectorId() );// 파라미터 맵핑?
            stmt.setInt( 2, director.getMovieId() );            
            //parameterIndex : 하나의 쿼리에서 몇번째 물음표인지 물어보는것            
            
            stmt.executeUpdate();
            
            
        } catch (SQLException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
        finally {
            closeDB(conn, stmt, null);
        }
    }
cs

 

 

ActorDAO.java 에서 insert 하는 부분

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
public void insertNewActorOfNewMovieId( ActorVO actor ){
        // 1. DriverLoading
        loadOracleDriver();
        
        Connection conn = null;
        PreparedStatement stmt = null;
//        ResultSet rs = null; insert 할것이므로 필요없다.
        
        try {
            conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE""MOVIE""MOVIE");
            
            String query = XML.getNodeString("//query/movie/insertNewActorList/text()");
            stmt = conn.prepareStatement(query);
            
            //SQL Parameter Mapping
            //?에 데이터 넣기
            stmt.setInt( 1, actor.getMovieId() );// 파라미터 맵핑?
            stmt.setInt( 2, actor.getActorId() );            
            //parameterIndex : 하나의 쿼리에서 몇번째 물음표인지 물어보는것        
            stmt.executeUpdate();
 
                    
        } catch (SQLException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
        finally {
            closeDB(conn, stmt, null);
        }
        
    }
cs

 

 

GenreDAO.java 에서 insert 하는 부분 

 

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
    public void insertNewGenreOfNewMovieId( GenreVO genre ) {
        
        // 1. DriverLoading
        loadOracleDriver();
        
        Connection conn = null;
        PreparedStatement stmt = null;
//        ResultSet rs = null; insert 할것이므로 필요없다.
        
        try {
            conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE""MOVIE""MOVIE");
            
            String query = XML.getNodeString("//query/movie/insertNewGenreList/text()");
            stmt = conn.prepareStatement(query);
            
            //SQL Parameter Mapping
            //?에 데이터 넣기
            stmt.setInt( 1, genre.getMovieId() );// 파라미터 맵핑?
            stmt.setInt( 2, genre.getGenreId() );
            
            //parameterIndex : 하나의 쿼리에서 몇번째 물음표인지 물어보는것            
            stmt.executeUpdate();
            
 
                    
        } catch (SQLException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
        finally {
            closeDB(conn, stmt, null);
        }
        
    }
cs

 

 

 

'BackEnd > JSP' 카테고리의 다른 글

[JSP] jQuery 사용하기  (0) 2016.03.07
[JSP] JSP, JSTL, Servlet을 이용한 간단한 회원가입 폼  (0) 2016.02.05
[JSP] JSTL, taglib  (0) 2016.02.05
[JSP] JSTL 설치  (0) 2016.02.05
[JSP] JSP, Servlet ( forward, redirect )  (0) 2016.02.03
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/11   »
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
글 보관함