영보의 SystemOut.log

[Spring] Cookie & Session 영화 출력 게시판 만들기 본문

Spring

[Spring] Cookie & Session 영화 출력 게시판 만들기

영보로그 2020. 11. 19. 18:45
반응형

 개념

 

 

# 쿠키 Cookie

 - Http 프로토콜의 특징인 비연결 성과 상태 유지성의 단점을 보완하고자 상태 유지의 개념으로 사용되는 것
 - 사용자가 서버를 통해 특정 문서를 요청하면 쿠키가 생성되고, 사용자의 컴퓨터의 약 4KB, 도메인당 20개 가능 
 - 쿠키는 세션과 반대되는 개념으로 클라이언트에게 정보를 저장하고, 서버의 부하를 줄일 수 있다. 하지만 Chrome 브라우저에서 개발자 도구-Application탭에서 해당 쿠키의 값을 수정할 수 있기 때문에, 보안에 취약하다는 단점이 있어서, 비밀번호 등의 중요 개인정보는 세션에 관리하는 것이 옳다.



# 어노테이션 Annotation

 - 해당 어노테이션은 함수의 인자로 받아서 사용하면 됨

 - 쿠키의 생성Cookie cookie =new Cookie("key", Value);로 간단히 생성 가능
    → 어노테이션의 name 항목에 내가 받고자 하는 쿠키의 키를 일치시켜주면 됨

1
2
3
4
5
6
7
8
9
 @RequestMapping("movie/detail_before.do")
   public String movie_detail_before(int no,RedirectAttributes ra,HttpServletResponse response)
   {
       // String no=10
       Cookie cookie=new Cookie("m"+no, String.valueOf(no));
       cookie.setMaxAge(60*60*24);
       response.addCookie(cookie); // 클라이언트에 저장 
       return "redirect:detail.do?no="+no;
    }
cs

 - 다음은 쿠키 생성 및 사용 어노테이션 예제 이다.

 

 

 

 코드

qh5944.tistory.com/110?category=418956

 

[Spring] Spring Transaction 답변 게시판 만들기 (1)

 개념 qh5944.tistory.com/106?category=307548 [Oracle] PL/SQL -TRIGGER 개념과 예제  개념 # TRIGGER  1) 데이터베이스에 미리 정해 놓는 조건에 만족하면 자동으로 이벤트 처리 (오라클에서 처리 → 자바에..

qh5944.tistory.com

pom.xml / web.xml 같은 코드 긁어오시면 됩니다 ㅎㅎ

 

 

경로입니다.

 

 

 

# 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
package com.sist.dao;
 
public class MovieVO {
    private String poster;
    private String title;
    private String regdate;
    private String grade;
    private String genre;
    private String actor;
    private String score;
    private String director;
    private String story,key;
    private int hit,no,cateno;
    public String getPoster() {
        return poster;
    }
    public void setPoster(String poster) {
        this.poster = poster;
    }
    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    public String getRegdate() {
        return regdate;
    }
    public void setRegdate(String regdate) {
        this.regdate = regdate;
    }
    public String getGrade() {
        return grade;
    }
    public void setGrade(String grade) {
        this.grade = grade;
    }
    public String getGenre() {
        return genre;
    }
    public void setGenre(String genre) {
        this.genre = genre;
    }
    public String getActor() {
        return actor;
    }
    public void setActor(String actor) {
        this.actor = actor;
    }
    public String getScore() {
        return score;
    }
    public void setScore(String score) {
        this.score = score;
    }
    public String getDirector() {
        return director;
    }
    public void setDirector(String director) {
        this.director = director;
    }
    public String getStory() {
        return story;
    }
    public void setStory(String story) {
        this.story = story;
    }
    public String getKey() {
        return key;
    }
    public void setKey(String key) {
        this.key = key;
    }
    public int getHit() {
        return hit;
    }
    public void setHit(int hit) {
        this.hit = hit;
    }
    public int getNo() {
        return no;
    }
    public void setNo(int no) {
        this.no = no;
    }
    public int getCateno() {
        return cateno;
    }
    public void setCateno(int cateno) {
        this.cateno = cateno;
    }      
}
cs

 

 

# MovieMapper.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package com.sist.dao;
import java.util.*;
 
import org.apache.ibatis.annotations.Select;
public interface MovieMapper {
   @Select("SELECT no,title,poster,rownum "
          +"FROM daum_movie "
          +"WHERE rownum<=20")
   public List<MovieVO> movieListData();
   
   @Select("SELECT * FROM daum_movie "
          +"WHERE no=#{no}")
   public MovieVO movieDetailData(int no);
}
cs

 

 

# MovieDAO.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package com.sist.dao;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import java.util.*;
@Repository
public class MovieDAO {
   @Autowired
   private MovieMapper mapper;
   public List<MovieVO> movieListData()
   {
       return mapper.movieListData();
   }
   
   public MovieVO movieDetailData(int no)
   {
       return mapper.movieDetailData(no);
   }
}
cs
 

 

 

# 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
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
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;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
 
import java.util.*;
 
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import com.sist.dao.*;
@Controller
public class MovieController {
   @Autowired
   private MovieDAO dao;
   
   @RequestMapping("movie/list.do")
   public String movie_list(Model model,HttpServletRequest request)
   {
       List<MovieVO> list=dao.movieListData();
       model.addAttribute("list", list);
       List<MovieVO> cList=new ArrayList<MovieVO>();
       Cookie[] cookies=request.getCookies();
       if(cookies!=null)
       {
           for(int i=cookies.length-1;i>=0;i--)
           {
               if(cookies[i].getName().startsWith("m"))
               {
                   MovieVO vo=dao.movieDetailData(Integer.parseInt(cookies[i].getValue()));
                   cList.add(vo);
               }
           }
       }
       model.addAttribute("cList", cList);
       return "movie/list";
   }
   // _ok , _before => jsp(X) => 처리 => redirect로 이동 
   @RequestMapping("movie/detail_before.do")
   public String movie_detail_before(int no,RedirectAttributes ra,HttpServletResponse response)
   {
       // String no=10
       Cookie cookie=new Cookie("m"+no, String.valueOf(no));
       cookie.setMaxAge(60*60*24);
       response.addCookie(cookie);// 클라이언트에 저장 
       // 쿠키의 단점 => 저장을 문자열만 저장이 가능 
       //ra.addFlashAttribute("no", no);// GET => POST (URL뒤에 데이터를 볼 수 없다
       return "redirect:detail.do?no="+no;
   }
   
   @RequestMapping("movie/detail.do")
   public String movie_detail(int no,Model model)
   {
       MovieVO vo=dao.movieDetailData(no);
       model.addAttribute("vo", vo);
       return "movie/detail";
   }  
}
cs

 - 쿠키를 저장하고 클라이언트에 전송

 - 쿠키의 단점 : 문자열만 저장이 가능

 

 

# application-context.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
<?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:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mybatis-spring="http://mybatis.org/schema/mybatis-spring"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring-1.2.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
        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
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd">
   <context:component-scan base-package="com.sist.*"/>
   <mvc:annotation-driven/>
   <bean id="ds" class="org.apache.commons.dbcp.BasicDataSource"
       p:driverClassName="oracle.jdbc.driver.OracleDriver"
       p:url="jdbc:oracle:thin:@211.238.142.181:1521:XE"
       p:username="hr"
       p:password="happy"
   />
   <bean id="ssf"
       class="org.mybatis.spring.SqlSessionFactoryBean"
       p:dataSource-ref="ds"
     />
     <bean id="mapper"
        class="org.mybatis.spring.mapper.MapperFactoryBean"
        p:mapperInterface="com.sist.dao.MovieMapper"
        p:sqlSessionFactory-ref="ssf"
      />
     <!-- <mybatis-spring:scan base-package="com.sist.dao" factory-ref="ssf"/> -->
     <bean id="viewResolver"
         class="org.springframework.web.servlet.view.InternalResourceViewResolver"
         p:prefix="/"
         p:suffix=".jsp"
       />
</beans>
cs

 

 

# 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
<%@ 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 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;
}
</style>
</head>
<body>
  <div style="height: 30px"></div>
  <div class="container-fluid">
    <div class="row">
     <c:forEach var="vo" items="${list }">
       <div class="col-md-3">
            <div class="thumbnail">
              <a href="detail_before.do?no=${vo.no}">
                <img src="${vo.poster }" alt="Lights" style="width:100%" class="img-rounded">
                <div class="caption">
                  <p style="font-size:8pt">${vo.title }</p>
                </div>
              </a> 
              
            </div>
        </div>
     </c:forEach>
    </div>
    <hr>
    <div class="row">
      <h3>미리 본 영화목록</h3>
      <c:forEach var="vo" items="${cList }" varStatus="s">
        <c:if test="${s.index<6 }">
        <div class="col-md-2">
            <div class="thumbnail">
              <a href="detail_before.do?no=${vo.no}">
                <img src="${vo.poster }" alt="Lights" style="width:100%" class="img-rounded">
                <div class="caption">
                  <p style="font-size:8pt">${vo.title }</p>
                </div>
              </a> 
            </div>
        </div>
        </c:if>
      </c:forEach>
    </div>
  </div>
</body>
</html>
cs

 

 

# detail.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
<%@ 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:800px;
}
</style>
</head>
<body>
  <div style="height: 30px"></div>
  <div class="container">
    <div class="row">
      <h3 class="text-center">&lt;${vo.title }&gt;상세보기</h3>
      <table class="table">
       <tr>
        <td>
          <iframe src="http://youtube.com/embed/${vo.key }" width=750 height=350></iframe>
        </td>
       </tr>
      </table>
      <table class="table">
        <tr>
         <td width=30% class="text-center" rowspan="7">
           <img src="${vo.poster }" width=100%>
         </td>
         <td colspan="2">${vo.title }</td>
        </tr>
        <tr>
          <td width=20% class="text-right">감독</td>
          <td width=50% class="text-left">${vo.director }</td>
        </tr>
        <tr>
          <td width=20% class="text-right">출연</td>
          <td width=50% class="text-left">${vo.actor }</td>
        </tr>
        <tr>
          <td width=20% class="text-right">장르</td>
          <td width=50% class="text-left">${vo.genre }</td>
        </tr>
        <tr>
          <td width=20% class="text-right">등급</td>
          <td width=50% class="text-left">${vo.grade }</td>
        </tr>
        <tr>
          <td width=20% class="text-right">평점</td>
          <td width=50% class="text-left">${vo.score }</td>
        </tr>
        <tr>
          <td width=20% class="text-right">개봉일</td>
          <td width=50% class="text-left">${vo.regdate }</td>
        </tr>
        <tr>
          <td colspan="3">${vo.story }</td>
        </tr>
        <tr>
          <td colspan="3" class="text-right">
            <a href="list.do" class="btn btn-sm btn-primary">목록</a>
          </td>
        </tr>
      </table>
    </div>
  </div>
</body>
</html>
cs

 

 

 출력 화면

 

 

 

반응형