이안의 평일코딩

Spring 10일차 - 스프링 MVC 본문

Back-end/Spring

Spring 10일차 - 스프링 MVC

이안92 2020. 11. 9. 09:33
반응형

2020.11.09(월)

 

 

.m2

tomcat

sts-bundle(편집기)

 

클래스: 리플렉션 (클래스의 정보를 읽어와서 처리)

 

1) class : Class.forName() => 메모리 할당

2) 멤버변수 : 필요시에 변수의 초기화

3) 생성자 : 멤버변수 초기화 (매개변수)

4) 메소드 : setter/getter

 

 

DL getBean() 클래스 관리자 사용자 요청 => 클래스 찾기

 

DI 주입(필요한데이터 첨부)

=> 1) seter DI (멤버변수 값 주입)

2) 생성자 DI (생성자 매개변수에 값 주입 c:name="")

3)메소드 DI (메소드 init-method destroy-method)

 

 

<DB사용하지 않고 데이터 가져오기 => json>

SpringMovieProject

 

기본설정

1)Properties - Java Compiler, Project Facets에서 JDK 1.8로 수정

2)pom.xml 수정

3)web.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee https://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/config/application-*.xml</param-value>
        </init-param>
    </servlet>
        
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>
    <!-- 한글 변환 -->
    <filter>
        <filter-name>encodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
            <init-param>
                <param-name>encoding</param-name>
                <param-value>UTF-8</param-value>
            </init-param>
            <init-param>
                <param-name>forceEncoding</param-name>
                <param-value>true</param-value>
            </init-param>
    </filter>
    
    <!-- /의 형식으로 시작하는 url에 대하여 UTF-8로 인코딩 -->
    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
 
    <!-- Error 처리 -->
</web-app>
 
cs

 

src/main/java

com.sist.web

MovieController.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
package com.sist.web;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
 
// Model => JSP(HTML(태그형)+Java)
// JSP(HTML(태그형) => VIEW
// JAVA => Model (1.VO, 2.DAO, 3.Manager)
// Controller 스프링안에서는 제작
// => 작동 (메뉴얼 제작=>XML)
// 이 클래스는 => Model역할
import java.util.*;
import com.sist.manager.*;
 
@Controller
public class MovieController {
    @Autowired
    private MovieManager mgr;
    @RequestMapping("movie/main.do")
    public String movie_main(int no, Model model){ //model에 보내줌
        List<MovieVO> list=mgr.jsonAllData(no);
        model.addAttribute("list",list);
        return "movie/main";
    }
}
 
cs

 

com.sist.manager

 

www.kobis.or.kr/kobis/business/main/main.do

//일일 박스오피스
		$.ajax({
			type : "POST",
			url  : "searchMainDailyBoxOffice.do",			
			dataType : "json",
			beforeSend: function(xhr){
				//$("#dailyBoxOffice").prepend("<div id="dailyBoxOffice_ingimg" style="width:300px;height:240px;padding-left:15px;background:url('/kobis/web/comm/images/comm/loading_small.gif') center no-repeat;">");
			},
			success : function(data){ 
				d_box = data;
				var date="";
				var strArg="";
				var strArg2="";
				$("#dailyBoxOffice").remove("table");
				if(data.length>0)
					drawMainTop("dailyBoxOffice",data);	
			}
		});

www.kobis.or.kr/kobis/business/main/searchMainDailyBoxOffice.do

 

url에서 main.do => searchMainDailyBoxOffice.do

 

New File => movie.json

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
{
"startYearDate":"2020.11.08",
"endYearDate":"2020.11.08",
"startDate":"2020년 11월 08일(일)",
"endDate":"2020년 11월 08일(일)",
"movieCd":"20192193",
"showDt":"20201108",
"thumbUrl":"/common/mast/movie/2020/10/thumb/thn_4ba51ba9b5f3439ca3d036f6391d58ba.jpg",
"movieNm":"도굴",
"movieNmEn":"Collectors",
"synop":"“고물인 줄 알았는데 보물이었다?!”\r\n땅 파서 장사하는 도굴꾼들이 온다!\r\n\r\n흙 맛만 봐도 보물을 찾아내는 타고난 천재 도굴꾼 강동구(이제훈).\r\n자칭 한국의 '인디아나 존스'로 불리는 고분벽화 도굴 전문가 존스 박사(조우진), 전설의 삽질 달인 삽다리(임원희)를 만나 환상(?)의 팀플레이를 자랑하며 위험천만하고도 짜릿한 도굴의 판을 키운다.\r\n\r\n한편, 그의 재능을 알아본 고미술계 엘리트 큐레이터 윤실장(신혜선)은\r\n강동구에게 매력적이면서도 위험한 거래를 제안하는데...!\r\n\r\n황영사 금동불상, 고구려 고분벽화 그리고 서울 강남 한복판 선릉까지!\r\n팔수록 판이 커지는 도굴의 세계!\r\n",
"prdtYear":"2020",
"indieYn":null,
"artmovieYn":null,
"multmovieYn":null,
"showTm":"114",
"showTs":"50",
"director":"박정배",
"prNm":"(주)싸이런픽쳐스",
"dtNm":"씨제이이앤엠(주)",
"repNationCd":"한국",
"movieType":"장편",
"moviePrdtStat":"개봉예정",
"genre":"범죄",
"watchGradeNm":"12세이상관람가",
"openDt":"20201104",
"salesAmt":1595995930,
"audiCnt":167850,
"scrCnt":1621,
"showCnt":7020,
"rank":1,
"rankInten":0,
"rankOldAndNew":"OLD",
"rownum":1
}
cs

 

com.sist.manager

MovieVO.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
package com.sist.manager;
/*
"thumbUrl":"/common/mast/movie/2020/10/thumb/thn_4ba51ba9b5f3439ca3d036f6391d58ba.jpg",
"movieNm":"도굴",
"movieNmEn":"Collectors", 영문제목
"synop": 줄거리 
"showTm":"114", 상영시간
"director":"박정배",
"prNm":"(주)싸이런픽쳐스",
"dtNm":"씨제이이앤엠(주)",
"repNationCd":"한국",
"movieType":"장편",
"moviePrdtStat":"개봉예정",
"genre":"범죄",
"watchGradeNm":"12세이상관람가",
"openDt":"20201104", 개봉일 regdate
"rank":1, 영화순위
"rankInten":0, 영화순위 변동
 
=> .do => Model(RequestMapping) <=> DAO(Manager)
                    | request.setAttribute(), model.addAttribute()
                   JSP
                1. Tiles
                2. 인터셉트
                3. RedirectAttribute
                    return "redirect:list.do?page=1";
                4. Profile
                5. Transaction
 */
public class MovieVO {
    private int mno;
    private int rank;
    private String title_ko;
    private String title_en;
    private String poster;
    private String director;
    private String genre;
    private String grade;
    private String regdate;
    private String nation;
    private String time;
    private String story;
    private int rank_id; // increment, decrement
    public int getMno() {
        return mno;
    }
    public void setMno(int mno) {
        this.mno = mno;
    }
    public int getRank() {
        return rank;
    }
    public void setRank(int rank) {
        this.rank = rank;
    }
    public String getTitle_ko() {
        return title_ko;
    }
    public void setTitle_ko(String title_ko) {
        this.title_ko = title_ko;
    }
    public String getTitle_en() {
        return title_en;
    }
    public void setTitle_en(String title_en) {
        this.title_en = title_en;
    }
    public String getPoster() {
        return poster;
    }
    public void setPoster(String poster) {
        this.poster = poster;
    }
    public String getDirector() {
        return director;
    }
    public void setDirector(String director) {
        this.director = director;
    }
    public String getGenre() {
        return genre;
    }
    public void setGenre(String genre) {
        this.genre = genre;
    }
    public String getGrade() {
        return grade;
    }
    public void setGrade(String grade) {
        this.grade = grade;
    }
    public String getRegdate() {
        return regdate;
    }
    public void setRegdate(String regdate) {
        this.regdate = regdate;
    }
    public String getNation() {
        return nation;
    }
    public void setNation(String nation) {
        this.nation = nation;
    }
    public String getTime() {
        return time;
    }
    public void setTime(String time) {
        this.time = time;
    }
    public String getStory() {
        return story;
    }
    public void setStory(String story) {
        this.story = story;
    }
    public int getRank_id() {
        return rank_id;
    }
    public void setRank_id(int rank_id) {
        this.rank_id = rank_id;
    }
    
}
 
cs

 

MovieManager

일반클래스는 Component로 메모리할당

www.kobis.or.kr/kobis/business/main/main.do

페이지 소스 300번대에 .do 가져오기

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
package com.sist.manager;
 
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.jsoup.Jsoup;
import org.jsoup.nodes.*;
import org.springframework.stereotype.Component;
import java.util.*;
 
@Component
public class MovieManager {
    public static void main(String[] args) {
        MovieManager m=new MovieManager();
        String json="";//m.jsonAllData(1);
        json=json.substring(json.indexOf("["),json.lastIndexOf("]")+1);
        try{
            /*
             * [] (배열) ==> JSONArray
             * {} (JSON) ==> JSONObject => JavaScript (객체)
             * let sa={"sabun":1,"name":"홍길동"};
             * ======
             *   sa=new Sawon();
             *   sa.sabun
             */
            JSONParser jp=new JSONParser();
            JSONArray arr=(JSONArray)jp.parse(json);
            System.out.println("JSONArray => arr");
            System.out.println(arr.toJSONString());
            for(int i=0;i<arr.size();i++){
                JSONObject obj=(JSONObject)arr.get(i);
                //System.out.println((i+1)+":"+obj);
                System.out.println("영화명:"+obj.get("movieNm")); //movie.json에 있는 컬럼명과 동일해야함!
                System.out.println("감독:"+obj.get("director"));
                System.out.println("장르:"+obj.get("genre"));
                System.out.println("등급:"+obj.get("watchGradeNm"));
                System.out.println("개봉일:"+obj.get("openDt"));
                System.out.println("줄거리:"+obj.get("synop"));
                System.out.println("====================================");
            }
        }catch(Exception ex){}
        //System.out.println(json);
    }
    
    //List에 값만채운다면 jsp에 출력가능
    public List<MovieVO> jsonAllData(int type){
        List<MovieVO> list=new ArrayList<MovieVO>();
        String url="http://www.kobis.or.kr/kobis/business/main/";
        switch(type){
        case 1:
            url+="searchMainDailyBoxOffice.do";
            break;
        case 2:
            url+="searchMainRealTicket.do";
            break;
        case 3:
            url+="searchMainDailySeatTicket.do";
            break;
        case 4:
            url+="searchMainOnlineDailyBoxOffice.do";
            break;
        }
        try{
            Document doc=Jsoup.connect(url).get();
            String json=doc.toString();
            json=json.substring(json.indexOf("["),json.lastIndexOf("]")+1);
            
            JSONParser jp=new JSONParser();
            JSONArray arr=(JSONArray)jp.parse(json);
            System.out.println("JSONArray => arr");
            System.out.println(arr.toJSONString());
            for(int i=0;i<arr.size();i++){
                JSONObject obj=(JSONObject)arr.get(i);
                //System.out.println((i+1)+":"+obj);
                MovieVO vo=new MovieVO();
                vo.setMno(i+1);
                vo.setRank((int)obj.get("rank"));
                vo.setTitle_ko((String)obj.get("movieNm"));
                vo.setTitle_en((String)obj.get("movieNmEn"));
                vo.setDirector((String)obj.get("director"));
                vo.setGenre((String)obj.get("genre"));
                vo.setPoster("http://www.kobis.or.kr"+(String)obj.get("thumbUrl"));
                vo.setGrade((String)obj.get("watchGradeNm"));
                vo.setRegdate((String)obj.get("openDt"));
                vo.setStory((String)obj.get("synop"));
                vo.setTime((String)obj.get("showTm"));
                vo.setRank_id((int)obj.get("rankInten"));
                vo.setNation((String)obj.get("repNationCd"));
                list.add(vo);
                /*
                System.out.println("영화명:"+obj.get("movieNm")); //movie.json에 있는 컬럼명과 동일해야함!
                System.out.println("감독:"+obj.get("director"));
                System.out.println("장르:"+obj.get("genre"));
                System.out.println("등급:"+obj.get("watchGradeNm"));
                System.out.println("개봉일:"+obj.get("openDt"));
                System.out.println("줄거리:"+obj.get("synop"));
                System.out.println("====================================");
                */
            }
        }catch(Exception ex){}
        return list;
    }
}
 
cs

 

src/main/webapp

movie폴더 생성

main.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
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<style type="text/css">
.row{
    margin: 0px auto;
    width:900px;
}
</style>
<script type="text/javascript" src="http://code.jquery.com/jquery.js"></script>
<script type="text/javascript">
$(function(){
    $.ajax({
        type:'POST',
        url:'main.do',
        data:{"no":1},
        success:function(result){
            
        }
    })
});
</script>
</head>
<body>
    <div style="height: 30px"></div>
    <div class="container">
        <div class="row">
            <span class="btn btn-sm btn-primary links" value="1">박스오피스</span>
            <span class="btn btn-sm btn-danger links" value="2">실시간 예매율</span>
            <span class="btn btn-sm btn-warning links" value="3">예매율 좌석 점유율</span>
            <span class="btn btn-sm btn-success links" value="4">온라인 이름순위</span>
        </div>
    </div>
</body>
</html>
cs

 

index.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="http://code.jquery.com/jquery.js"></script>
<script type="text/javascript">
$(function(){
    $.ajax({
        type:'POST',
        url:'main.do',
        data:{"no":1},
        success:function(result){
            location.href="main.do?no=1";
        }
    })
});
</script>
</head>
<body>
 
</body>
</html>
cs

 

 

src/main/webapp

WEB-INF폴더에 config 폴더 생성

Bean생성

application-context.xml (beans, context, p) =>메모리할당해라 지시

MovieController.java에 @Controller, @Autowired, @RequestMapping

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">
    <!-- Annotation 메모리 할당 -->
    <context:component-scan base-package="com.sist.*"/>
    <!-- 
    MovieManager.java
        @Component
        public class MovieManager { => MovieController new MovieController() => 100
        
    MovieController.java에
        @Controller
        public class MovieController {   => MovieManager new MovieManager() => 200
        @Autowired
        private MovieManager mgr; => 100
        
     -->
    <!-- 
        @Component,
        @Repository,
        @Service,
        @Controller,
        @RestController,
        @ControllerAdvice,
        @Configuration
        
        == 주입
        @Required, @Autowired, @PostConstruct, @PreDestroy, @Resource
     -->
     <!-- 실행 => 데이터를 JSP로 전송 : ViewResolver(경로명, 확장자) -->
     <!-- 
           .do ==> DispatcherServlet 요청 ==> HandlerMapping 모델찾아줌 => Model(@Controller)
                 ==> DAO(Manager) ==> Model(@Controller) => DispatcherServlet 데이터가지고
                 ==> ViewResolver 출력 ==> View(JSP)
                 
           .do ==> Model(@Controller)
                 ==> DAO(Manager) ==> Model(@Controller) => View(JSP)
      -->
      <bean id="viewResolver"
          class="org.springframework.web.servlet.view.InternalResourceViewResolver"
          p:prefix="/"
          p:suffix=".jsp"
          />
</beans>
 
cs

 

MovieController

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
package com.sist.web;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
 
// Model => JSP(HTML(태그형)+Java)
// JSP(HTML(태그형) => VIEW
// JAVA => Model (1.VO, 2.DAO, 3.Manager)
// Controller 스프링안에서는 제작
// => 작동 (메뉴얼 제작=>XML)
// 이 클래스는 => Model역할
import java.util.*;
import com.sist.manager.*;
 
@Controller
public class MovieController {
    @Autowired
    private MovieManager mgr;
    @RequestMapping("movie/main.do")
    public String movie_main(String no, Model model){ //int로 받으면 500오류뜸 //model에 보내줌
        if(no==null)
            no="1"// 안주면 ?no=1 로 쳐야 오류가안뜸
        List<MovieVO> list=mgr.jsonAllData(Integer.parseInt(no));
        model.addAttribute("list",list);
        return "movie/main";
    }
}
 
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
package com.sist.web;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
 
// Model => JSP(HTML(태그형)+Java)
// JSP(HTML(태그형) => VIEW
// JAVA => Model (1.VO, 2.DAO, 3.Manager)
// Controller 스프링안에서는 제작
// => 작동 (메뉴얼 제작=>XML)
// 이 클래스는 => Model역할
import java.util.*;
import com.sist.manager.*;
 
@Controller
public class MovieController {
    @Autowired
    private MovieManager mgr;
    @RequestMapping("movie/main.do")
    public String movie_main(int no, Model model){
        List<MovieVO> list=mgr.jsonAllData(no);
        model.addAttribute("list",list);
        return "movie/main";
    }
}
 
cs

 

반응형

'Back-end > Spring' 카테고리의 다른 글

Spring 12일차 - PL/SQL Procedure 게시판 만들기  (0) 2020.11.12
Spring 11일차 - React  (0) 2020.11.11
Spring 8일차 - MyBatis 연동  (0) 2020.11.03
Spring 7일차 - XML MVC구조  (0) 2020.11.02
Spring 6일차 - ComponentScan  (0) 2020.10.31
Comments