Back-End/Spring 2019. 8. 12. 17:07
- 게시판 게시글 쓰기 -
memberboard.jsp 페이지에서 "글쓰기" 버튼을 클릭하면 컨트롤러를 거쳐 memberboardwrite.jsp 페이지로 이동
memberboardwrite.jsp 페이지에서 글 내용과 제목을 작성후 "확인" 버튼을 누르면 컨트롤러->서비스->dao->mapper->컨트롤러
를 거쳐서 게시글이 insert되고, 게시글 리스트 페이지로 돌아온다.
memberboard.jsp 중 일부
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<script >
//글쓰기 폼으로 이동하게 하는 함수
$(function (){
$("#btnWrite" ).click(function (){
location .href= "write.do" ;
});
});
</script >
=============================================================
<button type = "button" id = "btnWrite" align = "right" >글쓰기</button >
cs
MemberBoardController.java 중 일부
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
//글쓰기 버튼을 눌렀을때 뷰에서 맵핑되는 메소드
@RequestMapping("/board/write.do" )
public String write(HttpSession session, HttpServletResponse write) throws Exception{
//글쓰기 폼 페이지로 이동함
String user_id = (String )session.getAttribute("user_id" );
//로그인 되어있는지 확인하는 if문, 로그인이 안되어있으면 경고메시지를 출력하고 홈으로 넘어간다.
if (user_id = = null ) {
write.setContentType("text/html; charset=UTF-8" );
PrintWriter out_write = write.getWriter();
out_write.println ("<script>alert('로그인이 되어있지 않습니다. 로그인을 먼저 해주세요.');</script>" );
out_write.flush();
return "home" ;
} else {
//로그인이 되어있다면!
return "board/memberboardwrite" ; //회원게시판 글쓰기 폼으로 이동함
}
}
cs
memberboardwrite.jsp (ckeditor을 사용함)
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
<%@ page language ="java" contentType ="text/html; charset=UTF-8"
pageEncoding ="UTF-8" % >
<!DOCTYPE html >
<html >
<head >
<meta charset ="UTF-8" >
<title >Insert title here</title >
</head >
<%@ include file ="../include/header.jsp" % >
<%@ include file ="../include/menu.jsp" % ><br ><br >
< script src = "${path}/ckeditor/ckeditor.js" > < / script >
<!-- ckeditor 사용을 위해 js파일을 연결함 -->
<body >
<!-- 글쓰기 폼 작성 -->
<h2 >글쓰기</h2 >
< form method = "post" action = "insert.do" >
<div >제목 : <input name = "title" id = "title" size = "80" placeholder = "제목을 입력하세요" ></div ><br ><br >
내용 : <div style = "width:800px; height:100px;" > <textarea id = "content " name = "content" rows = "6" cols = "80" placeholder = "내용을 입력하세요" ></textarea ></div >
<br >
<br >
<br >
<br >
<br >
<br >
<br >
<br >
<br >
<br >
<br >
<br >
<div style = "width:700px; text-align:right;" ><button type = "submit" name = "submit" >확인</button ></div >
<script >
//id가 description인 태그에 ckeditor을 적용시킴
//이미지 업로드 안됨
CKEDITOR.replace( "content" );
</script >
</form >
</body >
</html >
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
//write.jsp에서 입력한 내용들이 MemberBoardDTO에 저장됨
@RequestMapping("/board/insert.do" )
public String insert (@ModelAttribute MemberBoardDTO dto, HttpSession session, HttpServletResponse insert) throws Exception{
//로그인한 사용자의 아이디를 체크
//아이디를 체크해서 자신의 글에만 수정과 삭제가 가능하게 할 예정
String user_id = (String )session.getAttribute("user_id" );
dto.setUser_id(user_id);
insert.setContentType("text/html; charset=UTF-8" );
PrintWriter out_write = insert.getWriter();
out_write.println ("<script>alert('글이 작성되었습니다.');</script>" );
out_write.flush();
//레코드를 저장함
memberboardservice.create(dto);
//게시물을 저장한 후에 게시물 목록페이지로 다시 이동함
return "forward:/board/list.do" ;
}
cs
MemberBoardServiceImpl.java 중 일부
@Override
public void create(MemberBoardDTO dto) throws Exception {
memberboarddao.create(dto);
//dto를 매개값으로 dao를 호출한다.
}
cs
MemberBoardDAOImpl.java 중 일부
@Override
public void create(MemberBoardDTO dto) throws Exception {
sqlSession.insert("memberboard.insert",dto);
}
cs
boardMapper.xml 중 일부
<insert id = "insert">
<!-- 게시글 번호는 시퀀스로 하고 생성할때마다 숫자가 1씩 하도록 설정함 -->
<!-- 제목, 글내용, 작성자를 삽입함 -->
insert into member_board (member_bno, title, content, user_id) values
( seq_board.nextval, #{title}, #{content}, #{user_id} )
</insert>
cs
================================================================================
- 게시판 게시글 상세보기 -
게시글 목록 페이지에서 게시글 제목에 링크를 달아 링크를 클릭하면 게시글의 제목과 내용을 볼 수 있도록 한다.
게시글 수정과 삭제는 글을 작성한 당사자만 할 수 있고, 글 목록은 당사자가 아니라도 할 수 있도록 한다.
그리고 게시글을 한번 클릭할 때마다 조회수가 1씩 증가하도록 한다.
memberboard.jsp 중 일부
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<!-- forEach var = "개별데이터" items = "집합데이터" -->
<c:forEach var = "row" items = "${map.list}" > <!-- 컨트롤러에서 map안에 list를 넣었기 때문에 이렇게 받는다. -->
<tr >
<td >${row.member_bno}</td > <!-- 글번호 -->
<!-- 클릭하면 컨트롤러의 view.do로 이동하고, 게시물번호, 페이지 번호, 검색옵션, 키워드를 같이 넘긴다 -->
<!-- 같이 넘겨야 값들이 초기화 되지 않기 때문에 -->
<td >
< a href = "view.do?member_bno=${row.member_bno}
&curPage=${map.pager.curPage}
&search_option=${map.search_option}
&keyword=${map.keyword}" > ${row.title} < / a > < / td > <!-- 글제목 -->
<td >${row.user_id}</td > <!-- 작성자의 이름 -->
<td >${row.content}</td > <!-- 글의내용 -->
<td >${row.reg_date}</td > <!-- 날짜의 출력형식을 변경함 -->
<td >${row.viewcnt}</td > <!-- 조회수 -->
<td >${row.recommend}</td > <!-- 추천수 -->
</tr >
</c:forEach >
cs
MemberBoardController.java 중 일부
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
@RequestMapping(value = "/board/view.do" , method= RequestMethod.GET)
public ModelAndView view(@RequestParam int member_bno,
@RequestParam int curPage,
@RequestParam String search_option,
@RequestParam String keyword,
HttpSession session ) throws Exception{
//조회수 증가 쿼리
memberboardservice.increaseViewcnt(member_bno, session);
MemberBoardServiceImpl.java 중 일부
//조회수를 증가하게하는 쿼리
//조회수 처리를 할때 일정 시간이 지난후 다시 클릭할때만 조회수가 증가하도록 설정 @Override public void increaseViewcnt(int member_bno, HttpSession session) throws Exception { long update_time = 0; //null을 방지하기 위해 초기값을 null로 설정함 if(session.getAttribute("update_time_"+member_bno)!=null) { //최근에 조회수를 올린 시간이 null이 아니면 update_time = (long)session.getAttribute("update_time_"+member_bno); } long current_time = System.currentTimeMillis(); //일정 시간이 경과한 후에 조회수를 증가시킨다. if(current_time - update_time > 5 * 1000) { //조회수가 1증가했을때로부터 5000초 후에 다시 클릭을 해야 조회수가 다시 1 증가한다는 말이다. //조회수 증가 처리 memberboarddao.increateViewcnt(member_bno); //조회수를 올린 시간을 저장함 session.setAttribute("update_time_"+member_bno, current_time); } }
MemberBoardDAOImpl.java 중 일부
//조회수 증가처리를 하는 메소드 @Override public void increateViewcnt(int member_bno) throws Exception { sqlSession.update("memberboard.increaseViewcnt", member_bno); }
boardMapper.xml 중 일부
<!-- 조회수 증가처리를 하는 구문 --> <update id = "increaseViewcnt"> <!-- 글번호에 해당하는 조회수를 +1하는 쿼리문 --> update member_board set viewcnt=viewcnt+1 where member_bno=#{bno} </update>
//페이지를 이동하면서 자료를 같이 넘기기 위해서 modelandview를 사용한다.
ModelAndView mav = new ModelAndView();
mav.setViewName("board/memberboardview" );
//view로 자료를 넘기기위해서 mav에 값들을 저장해서 view.jsp로 리턴시킨다.
mav.addObject( "dto" , memberboardservice.read(member_bno)); //상세보기를 한번 클릭하면 조회수를 1증가시킨다.
MemberBoardServiceImpl.java 중 일부
@Override
public MemberBoardDTO read(int member_bno) throws Exception {
return memberboarddao.read(member_bno);
}
cs
MemberBoardDAOImpl.java 중 일부
//게시글 상세정보
@Override
public MemberBoardDTO read(int member_bno) throws Exception {
return sqlSession.selectOne("memberboard.read", member_bno);
}
cs
boardMapper.xml 중 일부
1
2
3
4
5
6
7
8
9
10
11
12
< ! -- 게시글 상세정보를 확인하는 쿼리문 -->
< select id = "read"
resultType = "com.example.hansub_project.model.board.dto.MemberBoardDTO" >
< ! -- member_board테이블의 작성자와 member테이블의 아이디가 같고, 글번호가 클릭한 글번호와 같은 글번호와 같은
글번호, 제목, 조회수, 날짜, 내용, 이름, 작성자를 검색한다. -->
select member_bno, title, reg_date, content, viewcnt, user_id
from member_board
where member_bno= #{member_bno}
< / select >
cs
mav.addObject("curPage" , curPage);
mav.addObject("search_option" , search_option);
mav.addObject("keyword" , keyword);
return mav; //view로 넘어가서 출력이 된다.
}
cs
자료를 받을 view 페이지
memberboardview.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
<% @ page language= "java" contentType= "text/html; charset=UTF-8"
pageEncoding= "UTF-8" %>
<!DOCTYPE html >
<html >
<head >
<meta charset ="UTF-8" >
<title >Insert title here</title >
</head >
<% @ include file= "../include/header.jsp" %>
<% @ include file= "../include/menu.jsp" %>
<script src ="${path}/include/js/common.js" ></script >
< script src = "${path}/ckeditor/ckeditor.js" > < / script > //ck에디터
<script src ="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js" ></script >
<script >
//목록 버튼
$(function (){
$("#btnList" ).click(function (){
location .href= "list.do" ;
});
});
//수정 버튼
$(function (){$("#btnUpdate" ).click(function (){
//첨부파일 이름들을 폼에 추가
var str= "" ;
$("#uploadedList .file" ).each(function (i){
str+ =
"<input type='hidden' name='files[" + i+ "]' value='"
+ $(this).val()+ "'>" ;
});
$("#form1" ).append(str);
document .form1.action= "${path}/board/update.do" ;
document .form1.submit();
});
});
//삭제 버튼
$(function (){$("#btnDelete" ).click(function (){
if (confirm ("삭제하시겠습니까?" )){
document .form1.action= "${path}/board/delete.do" ;
document .form1.submit();
}
});
});
listAttach();
</script >
<h2 >게시물 보기</h2 >
<!-- 게시물을 작성하기 위해 컨트롤러의 insert.do로 맵핑 -->
<form id ="form1" name ="form1" method ="post"
action ="${path}/board/insert.do" >
<div >제목 <input name ="title" id ="title" size ="80"
value ="${dto.title}"
placeholder ="제목을 입력하세요" ><br ><br >
<!-- placeholder은 제목을 입력할 수 있도록 도움말을 출력함 -->
</div >
<div >조회수 : ${dto.viewcnt} </div ><br ><br >
<div style ="width:800px;" >
내용 <textarea id ="content" name ="content"
rows ="3" cols ="80"
placeholder ="내용을 입력하세요" >${dto.content}</textarea ><br ><br >
<!-- 마찬가지로 내용을 입력하도록 도움말을 출력함 -->
<script >
// ckeditor 적용
//id가 content인 태그 (글의 내용을 입력하는 태그)를 ck에디터를 적용한다는 의미
CKEDITOR.replace("content" ,{
filebrowserUploadUrl: "${path}/imageUpload.do" ,
height: "300px"
});
</script >
<div style = "width:700px; text-align:center;" >
<!-- 수정, 삭제에 필요한 글번호를 hidden 태그에 저장한다. -->
< input type = "hidden" name = "member_bno" value = "${dto.member_bno }" >
<!-- 본인만 수정, 삭제 버튼을 표시한다. -->
<c:if test = "${sessionScope.user_id == dto.user_id }" >
<button type = "button" id = "btnUpdate" >수정</button >
<button type = "button" id = "btnDelete" >삭제</button >
</c:if >
<!-- 글목록은 본인이 아니어도 확인 가능하게 한다. -->
<button type = "button" id = "btnList" >목록</button >
<body >
</body >
</html >
cs
servlet-context.xml에 ckeditor관련 코드 추가
<resources location="/WEB-INF/views/ckeditor/" mapping="/ckeditor/**"></resources>
cs
아래 책은 제가 공부할때 활용했던 책으로 추천드리는 책이니 한번씩 읽어보시는것을 추천드립니다!! ㅎㅎ
이 포스팅은 쿠팡 파트너스 활동의 일환으로, 이에 따른 일정액의 수수료를 제공받습니다.
Back-End/Spring 2019. 8. 9. 17:15
검색창에서 작성자, 제목, 내용, 작성자+내용+제목의 옵션으로 글을 검색 할 수 있게 검색기능구현함
1. 게시판 view 페이지에 검색기능 관련 폼 태그 추가
memberboard.jsp 중 일부
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
//컨트롤러의 list.do로 맵핑되고, user_id, title, content값을 매개값으로 넘긴다.
//검색옵션은 작성자, 제목, 내용, 작성자+제목+내용으로 검색할 수 있도록 한다.
<form name ="form1" method ="post" action ="list.do" >
<select name ="search_option" >
<option value ="user_id"
<c:if test ="${map.search_option == 'user_id'}" >selected</c:if >
>작성자</option >
<option value ="title"
<c:if test ="${map.search_option == 'title'}" >selected</c:if >
>제목</option >
<option value ="content"
<c:if test ="${map.search_option == 'content'}" >selected</c:if >
>내용</option >
<option value ="all"
<c:if test ="${map.search_option == 'all'}" >selected</c:if >
>작성자+내용+제목</option >
</select >
<input name ="keyword" value ="${map.keyword}" >
<input type ="submit" value ="조회" >
</form >
cs
MemberBoardController.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
@RequestMapping("list.do" ) //세부적인 url mapping
public ModelAndView list(//RequestParam으로 옵션, 키워드, 페이지의 기본값을 각각 설정해준다.
@RequestParam(defaultValue= "1" ) int curPage,
@RequestParam(defaultValue = "user_id" ) String search_option, //기본 검색 옵션값을 작성자로 한다.
@RequestParam(defaultValue = "" ) String keyword //키워드의 기본값을 ""으로 한다.
)
throws Exception{
//레코드 갯수를 계산
int count = 1000 ;
//페이지 관련 설정, 시작번호와 끝번호를 구해서 각각 변수에 저장한다.
Pager pager = new Pager(count, curPage);
int start = pager.getPageBegin();
int end = pager.getPageEnd();
//map에 저장하기 위해 list를 만들어서 검색옵션과 키워드를 저장한다.
List< MemberBoardDTO> list = memberboardservice.listAll(search_option , keyword , start, end);
ModelAndView mav = new ModelAndView();
Map< String ,Object> map = new HashMap< > (); //넘길 데이터가 많기 때문에 해쉬맵에 저장한 후에 modelandview로 값을 넣고 페이지를 지정
map.put("list" , list); //map에 list(게시글 목록)을 list라는 이름의 변수로 자료를 저장함.
map.put("pager" , pager);
map.put("count" , count);
map.put( "search_option" , search_option);
map.put( "keyword" , keyword);
mav.addObject("map" , map); //modelandview에 map를 저장
System .out .println ("map : " + map);
mav.setViewName( "board/memberboard" ); //자료를 넘길 뷰의 이름
return mav; //게시판 페이지로 이동
}
cs
게시판 목록 기능 구현할때와 동일하게 서비스 -> dao를 거쳐서 mapper로 이동
boardMapper.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
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
<?xml version ="1.0" encoding ="UTF-8" ? >
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<!-- 다른 mapper와 중복되지 않도록 네임스페이스 기재 -->
<mapper namespace ="memberboard" >
<!-- rownum을 rn이란 문자로 줄여쓴다. 밑에 from문을 A로 줄여쓴다. -->
<!-- 이 from문이 먼저 실행된 다음에 번호를 붙였기 때문에 일련번호가 다시 새로 매겨졌다. -->
<!-- 이 안쪽의 쿼리가 가장 중요함 -->
<select id ="listAll" resultType ="com.example.hansub_project.model.board.dto.MemberBoardDTO" >
<!-- 결과는 boardDTO타입이 된 -->
<include refid ="paging_header" / >
<!-- ref는 다른테이블을 의미한다. -->
<!-- 번호, 제목, 작성자, 이름, 날짜, 조회수 , 그리고 댓글의 갯수를 검색 -->
<!-- board 테이블과 member 테이블로 부터 검색 -->
select member_bno, user_id, reg_date, viewcnt, title, rcnt, content, recommend
from member_board
<!-- bno의 내림차순으로 검색 -->
<!-- where절은 (조건)은 include 태그를 이용했음 -->
< include refid = "search" / >
order by member_bno desc
<include refid ="paging_footer" / >
</select >
<sql id ="paging_header" >
<!-- 게시물을 한페이지에 10개씩 볼 수 있게하는 쿼리 윗부분-->
select *
from (
select rownum as rn, A.*
from (
</sql >
<sql id ="paging_footer" >
<!-- 게시물을 한페이지에 10개씩 볼 수 있게하는 쿼리 아랫 부분-->
<!-- 새로 매겨진 일련번호 1~10번 글까지 1페이지 -->
<!-- 11~20번 글까지 2페이지.. -->
) A
) where rn between #{start} and #{end}
</sql >
< sql id = "search" >
<choose >
//작성자+제목+내용의 검색조건으로 게시물을 검색하는 쿼리
< when test = "search_option == 'all' " >
where
user_id like '%'||#{keyword}||'%'
or content like '%' || #{keyword}||'%'
or title like '%'||#{keyword}||'%'
</when >
<otherwise >
//내가 지정한 조건 (작성자, 제목, 내용) 의 검색조건으로 게시물을 검색하는 쿼리
where ${search_option} like '%'||#{keyword}||'%'
</otherwise >
</choose >
</sql >
</mapper >
cs
아래 책은 제가 공부할때 활용했던 책으로 추천드리는 책이니 한번씩 읽어보시는것을 추천드립니다!! ㅎㅎ
이 포스팅은 쿠팡 파트너스 활동의 일환으로, 이에 따른 일정액의 수수료를 제공받습니다.
Back-End/Spring 2019. 8. 9. 16:41
1. 게시판 관련 Controller, model, service , view, Pager(게시판 목록 페이징 관련 ), Mapper을 생성
2. 각 파일들을 생성해서 연동
Pager.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
package com.example.hansub_project;
public class Pager {
public static final int PAGE_SCALE= 25 ; //페이지당 게시물수
public static final int BLOCK_SCALE= 10 ; //화면당 페이지수
private int curPage; //현재 페이지
private int prevPage; //이전 페이지
private int nextPage; //다음 페이지
private int totPage; //전체 페이지 갯수
private int totBlock; //전체 페이지블록 갯수
private int curBlock; //현재 블록
private int prevBlock; //이전 블록
private int nextBlock; //다음 블록
private int pageBegin; // #{start} 변수에 전달될 값
private int pageEnd; // #{end} 변수에 전달될 값
private int blockBegin; //블록의 시작페이지 번호
private int blockEnd; //블록의 끝페이지 번호
//생성자
// Pager(레코드갯수, 출력할페이지번호)
public Pager(int count, int curPage) {
curBlock = 1 ; //현재블록 번호
this .curPage = curPage; //현재 페이지 번호
setTotPage(count); //전체 페이지 갯수 계산
setPageRange(); // #{start}, #{end} 값 계산하는 메소드
setTotBlock(); // 전체 블록 갯수 계산
setBlockRange(); //블록의 시작,끝 번호 계산
}
public void setBlockRange() {
//원하는 페이지가 몇번째 블록에 속하는지 계산
curBlock= (curPage- 1 )/ BLOCK_SCALE + 1 ;
//블록의 시작페이지,끝페이지 번호 계산
blockBegin= (curBlock- 1 )* BLOCK_SCALE+ 1 ;
blockEnd= blockBegin+ BLOCK_SCALE- 1 ;
//마지막 블록 번호가 범위를 초과하지 않도록 처리
if (blockEnd > totPage) {
blockEnd = totPage;
}
//[이전][다음]을 눌렀을 때 이동할 페이지 번호
prevPage= (curBlock= = 1 ) ? 1 : (curBlock- 1 )* BLOCK_SCALE;
nextPage= curBlock> totBlock ? (curBlock* BLOCK_SCALE)
: (curBlock* BLOCK_SCALE)+ 1 ;
//마지막 페이지가 범위를 초과하지 않도록 처리
if (nextPage > = totPage) {
nextPage= totPage;
}
}
//페이지블록의 총 갯수 계산 (총 100페이지라면 10개의 블록이다)
public void setTotBlock() {
totBlock = (int )Math.ceil(totPage* 1. 0 / BLOCK_SCALE);
}
// where rn between #{start} and #{end}에 입력될 값
public void setPageRange() {
// 시작번호=(현재페이지-1)x페이지당 게시물수 + 1
// 끝번호=시작번호 + 페이지당 게시물수 - 1
pageBegin = (curPage- 1 ) * PAGE_SCALE + 1 ;
pageEnd = pageBegin + PAGE_SCALE - 1 ;
}
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 totPage) {
this .totPage = totPage;
}
public int getTotBlock() {
return totBlock;
}
public void setTotBlock(int totBlock) {
this .totBlock = totBlock;
}
public int getCurBlock() {
return curBlock;
}
public void setCurBlock(int curBlock) {
this .curBlock = curBlock;
}
public int getPrevBlock() {
return prevBlock;
}
public void setPrevBlock(int prevBlock) {
this .prevBlock = prevBlock;
}
public int getNextBlock() {
return nextBlock;
}
public void setNextBlock(int nextBlock) {
this .nextBlock = nextBlock;
}
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 getBlockBegin() {
return blockBegin;
}
public void setBlockBegin(int blockBegin) {
this .blockBegin = blockBegin;
}
public int getBlockEnd() {
return blockEnd;
}
public void setBlockEnd(int blockEnd) {
this .blockEnd = blockEnd;
}
}
cs
view를 작성 ( memberboard.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
<% @ page language= "java" contentType= "text/html; charset=UTF-8"
pageEncoding= "UTF-8" %>
<!DOCTYPE html >
<html >
<head >
<meta charset ="UTF-8" >
<title >Insert title here</title >
<% @ include file= "../include/header.jsp" %>
<script src ="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js" ></script >
<script >
//아래쪽에서 이 함수를 호출해서 페이지값을 컨트롤러에 맵핑시킨다
function list(page){
console .log( "페이지를 이동합니다." );
location .href = "list.do?curPage=" + page;
}
</script >
</head >
<body >
<br ><% @ include file= "../include/menu.jsp" %> <br >
<center >
<h2 >회원 게시판</h2 >
<table border = "1" width = "600px" >
<center >
<tr >
<th >번호</th >
<th >제목</th >
<th >작성자</th >
<th >내용</th >
<th >날짜</th >
<th >조회수</th >
<th >추천수</th >
<!-- forEach var = "개별데이터" items = "집합데이터" -->
<c:forEach var = "row" items = "${map.list}" > <!-- 컨트롤러에서 map안에 list를 넣었기 때문에 이렇게 받는다. -->
<tr >
<td >${row.member_bno}</td > <!-- 글번호 -->
<td >${row.title}</td > <!-- 글제목 -->
<td >${row.user_id}</td > <!-- 작성자의 이름 -->
<td >${row.content}</td > <!-- 글의내용 -->
<td >${row.reg_date}</td > <!-- 날짜의 출력형식을 변경함 -->
<td >${row.viewcnt}</td > <!-- 조회수 -->
<td >${row.recommend}</td > <!-- 추천수 -->
</tr >
</c:forEach >
<!-- 페이지 네비게이션 (페이지 알고리즘 관련) 출력 -->
<tr >
<td colspan = "7" align = "center" >
<c:if test ="${map.pager.curBlock > 1}" >
< a href = "#" onclick = "list('1')" >[처음]</ a >
</c:if > <!-- 현재 블록이 1블록보다 크면 (뒤쪽에 있기때문에) 처음으로 갈 수 있도록 링크를 추가 -->
<c:if test ="${map.pager.curBlock > 1}" >
< a href = "#" onclick = "list('${map.pager.prevPage}')" >[이전]</ a >
</c:if > <!-- 현재 블록이 1블록보다 크면 이전 블록으로 이동할 수 있도록 링크 추가 -->
<c:forEach var ="num"
begin ="${map.pager.blockBegin}"
end ="${map.pager.blockEnd}" >
<c:choose >
<c:when test ="${num == map.pager.curPage}" >
<!-- 현재 페이지인 경우 하이퍼링크 제거 -->
<!-- 현재 페이지인 경우에는 링크를 빼고 빨간색으로 처리를 한다. -->
< span style = "color:red;" >${num}</ span >
</c:when >
<c:otherwise >
< a href = "#" onclick = "list('${num}')" >${num}</ a >
</c:otherwise >
</c:choose >
</c:forEach >
<c:if test ="${map.pager.curBlock <= map.pager.totBlock}" >
< a href = "#" onclick = "list('${map.pager.nextPage}')" >[다음]</ a >
</c:if > <!-- 현재 페이지블록이 총 페이지블록보다 작으면 다음으로 갈 수있도록 링크를 추가 -->
<c:if test ="${map.pager.curPage <= map.pager.totPage}" >
< a href = "#" onclick = "list('${map.pager.totPage}')" >[끝]</ a >
</c:if > <!-- 현재 페이지블록이 총 페이지블록보다 작거나 같으면 끝으로 갈 수 있도록 링크를 추가함-->
</td >
</tr >
</center >
</table >
cs
게시판 관련 컨트롤러 (MemberBoardController.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
package com.example.hansub_project.controller.board;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.inject.Inject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import com.example.hansub_project.Pager;
import com.example.hansub_project.controller.member.MemberController;
import com.example.hansub_project.model.board.dto.MemberBoardDTO;
import com.example.hansub_project.service.board.MemberBoardService;
import com.example.hansub_project.service.member.MemberService;
@Controller //게시판 관련 컨트롤러를 선언함
public class MemberBoardController {
@Inject //서비스를 호출하기위해서 의존성을 주입함
MemberBoardService memberboardservice;
//로깅을 위한 변수
private static final Logger logger=
LoggerFactory.getLogger(MemberBoardController.class );
@RequestMapping( "list.do" ) //세부적인 url mapping
public ModelAndView list(//RequestParam으로 옵션, 키워드, 페이지의 기본값을 각각 설정해준다.
//초기값을 설정해야 에러가 발생되지 않는다.
@RequestParam(defaultValue= "1" ) int curPage,
@RequestParam(defaultValue= "user_id" ) String search_option,
@RequestParam(defaultValue= "" ) String keyword
)
throws Exception{
//레코드 갯수를 계산
int count = 1000 ;
//페이지 관련 설정, 시작번호와 끝번호를 구해서 각각 변수에 저장한다.
Pager pager = new Pager(count, curPage);
int start = pager.getPageBegin();
int end = pager.getPageEnd();
//map에 담기위해 리스트에 검색옵션, 키워드, 시작과 끝번호 를 저장
List< MemberBoardDTO> list = m emberboardservice.listAll(search_option, keyword, start, end);
ModelAndView mav = new ModelAndView();
Map< String ,Object> map = new HashMap< > (); //넘길 데이터가 많기 때문에 해쉬맵에 저장한 후에 modelandview로 값을 넣고 페이지를 지정
map.put("list" , list); //map에 list(게시글 목록)을 list라는 이름의 변수로 자료를 저장함.
map.put("pager" , pager);
map.put("count" , count);
map.put("search_option" , search_option);
map.put("keyword" , keyword);
mav.addObject("map" , map); //modelandview에 map를 저장
mav.setViewName("board/memberboard" ); //자료를 넘길 뷰의 이름
return mav; //게시판 페이지로 이동
}
}
cs
게시판 관련 서비스 인터페이스와 구현 클래스를 생성
MemberBoardService (서비스 인터페이스 )
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
package com.example.hansub_project.service.board;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpSession;
import com.example.hansub_project.model.board.dto.MemberBoardDTO;
public interface MemberBoardService {
//목록 (페이지 나누기, 검색 기능을 포함)
//매개변수는 시작 레코드 번호, 끝번호, 옵션과 키워드가 들어간다.
public List< MemberBoardDTO> listAll(String search_option, String keyword, int start, int end)throws Exception;
}
cs
MemberBoardServiceImpl.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
package com.example.hansub_project.service.board;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.inject.Inject;
import javax.servlet.http.HttpSession;
import org.springframework.stereotype.Service;
import com.example.hansub_project.model.board.dao.MemberBoardDAO;
import com.example.hansub_project.model.board.dto.MemberBoardDTO;
@Service //서비스 빈으로 설정함
public class MemberBoardServiceImpl implements MemberBoardService {
@Inject //dao를 호출하기 때문에 의존성을 주입한다.
MemberBoardDAO memberboarddao;
@Override
public List< MemberBoardDTO> listAll(String search_option, String keyword,int start, int end) throws Exception {
return memberboarddao.listAll(search_option, keyword, start, end);
}
}
cs
DAO관련 인터페이스와 구현 클래스 생성
MemberBoardDAO (인터페이스)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package com.example.hansub_project.model.board.dao;
import java.util.List;
import com.example.hansub_project.model.board.dto.MemberBoardDTO;
//DAO 클래스
public interface MemberBoardDAO {
//게시글 리스트를 출력하는 메소드 (검색옵션, 키워드, 시작번호와 끝번호 포함)
public List< MemberBoardDTO> listAll(String search_option, String keyword,int start, int end) throws Exception;
}
cs
구현 클래스를 작성
MemberBoardDAOImpl.java (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
package com.example.hansub_project.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.hansub_project.model.board.dto.MemberBoardDTO;
import com.example.hansub_project.model.member.dao.MemberDAO;
@Repository //dao 선언
public class MemberBoardDAOImpl implements MemberBoardDAO {
@Inject //db에 접속하기 위해 의존관계를 주입
SqlSession sqlSession;
//게시물 목록을 리턴
@Override
public List< MemberBoardDTO> listAll(String search_option, String keyword, int start, int end) throws Exception {
//맵에 자료 저장
Map< String ,Object> map = new HashMap< > ();
map.put("search_option" , search_option);
map.put("keyword" , keyword);
map.put("start" , start);
map.put("end" , end);
//매개변수는 시작 레코드의 번호, 끝 번호, 옵션과 키워드가 들어간다.
return sqlSession.selectList( "memberboard.listAll" , map);
}
}
cs
계층별 자료 전송을 위해 DTO 클래스 작성
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
package com.example.hansub_project.model.board.dto;
import java.sql.Date;
//회원 게시판 관련 dto 클래스
public class MemberBoardDTO {
private int member_bno; //게시글 번호
private String user_id; //작성자 아이디
private Date reg_date; //작성 날짜
private int viewcnt; //조회수
private String title; //제목
private int rcnt; //댓글 갯수
private String content; //댓글 내용
private int recommend; //추천수
public int getMember_bno() {
return member_bno;
}
public void setMember_bno(int member_bno) {
this .member_bno = member_bno;
}
public String getUser_id() {
return user_id;
}
public void setUser_id(String user_id) {
this .user_id = user_id;
}
public Date getReg_date() {
return reg_date;
}
public void setReg_date(Date reg_date) {
this .reg_date = reg_date;
}
public int getViewcnt() {
return viewcnt;
}
public void setViewcnt(int viewcnt) {
this .viewcnt = viewcnt;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this .title = title;
}
public int getRcnt() {
return rcnt;
}
public void setRcnt(int rcnt) {
this .rcnt = rcnt;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this .content = content;
}
public int getRecommend() {
return recommend;
}
public void setRecommend(int recommend) {
this .recommend = recommend;
}
@Override
public String toString () {
return "MemberBoardDTO [member_bno=" + member_bno + ", user_id=" + user_id + ", reg_date=" + reg_date
+ ", viewcnt=" + viewcnt + ", title=" + title + ", rcnt=" + rcnt + ", content=" + content
+ ", recommend=" + recommend + "]" ;
}
}
cs
게시판 목록과 페이지 관련, 검색기능을 추가한 쿼리를 mapper에 작성
BoardMapper.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
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
<?xml version ="1.0" encoding ="UTF-8" ? >
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<!-- 다른 mapper와 중복되지 않도록 네임스페이스 기재 -->
< mapper namespace = "memberboard" >
<!-- rownum을 rn이란 문자로 줄여쓴다. 밑에 from문을 A로 줄여쓴다. -->
<!-- 이 from문이 먼저 실행된 다음에 번호를 붙였기 때문에 일련번호가 다시 새로 매겨졌다. -->
<!-- 이 안쪽의 쿼리가 가장 중요함 -->
< select id = "listAll" resultType = "com.example.hansub_project.model.board.dto.MemberBoardDTO" >
<!-- 쿼리의 결과를 출력시키기 위해서 dto 타입으로 반환한다.-->
< include refid = "paging_header" / > //밑에 있는 sql문을 include 한다
<!-- ref는 다른테이블을 의미한다. -->
<!-- 번호, 제목, 작성자, 이름, 날짜, 조회수 , 그리고 댓글의 갯수를 검색 -->
<!-- board 테이블과 member 테이블로 부터 검색 -->
select member_bno, user_id, reg_date, viewcnt, title, rcnt, content, recommend
from member_board
<!-- bno의 내림차순으로 검색 -->
<!-- where절은 (조건)은 include 태그를 이용했음 -->
< include refid = "search" / >
order by member_bno desc
< include refid = "paging_footer" / >
</select >
<sql id ="paging_header" >
<!-- 게시물을 한페이지에 10개씩 볼 수 있게하는 쿼리 윗부분-->
select *
from (
select rownum as rn, A.*
from (
</sql >
<sql id ="paging_footer" >
<!-- 게시물을 한페이지에 10개씩 볼 수 있게하는 쿼리 아랫 부분-->
<!-- 새로 매겨진 일련번호 1~10번 글까지 1페이지 -->
<!-- 11~20번 글까지 2페이지.. -->
) A
) where rn between #{start} and #{end}
</sql >
<sql id ="search" >
<choose >
//작성자 , 내용, 제목으로 각각 검색할 수 있게끔 한다.
<when test ="search_option == 'all' " >
where
user_id like '%'||#{keyword}||'%'
or content like '%' || #{keyword}||'%'
or title like '%'||#{keyword}||'%'
</when >
<otherwise >
//작성자 + 내용 + 제목을 포함한 항목을 검색할 수 있게끔 한다.
where ${search_option} like '%'||#{keyword}||'%'
</otherwise >
</choose >
</sql >
</mapper >
cs
Back-End/Spring 2019. 8. 7. 11:46
어제 구현한 이메일을 활용한 인증을 조금 수정해서 메인페이지에서 이메일을 발송할 수 있도록 기능을 추가함
받는 사람의 이메일 주소와 이메일 제목, 내용을 입력후 버튼을 누르면 이메일이 발송되도록 추가함
home.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
<!-- 이메일 보내기 폼 -->
<form action ="e_mailForm.do" method = "post" >
<table border = "1" align ="right" width = "450" height = "250" >
<tr >
<td >
<center >
<br >
<span style ="color: green; font-weight: bold;" >이메일 보내기</span >
</center >
<ul >
<li >보내는 사람 : <input type ="text" name ="sender_front" placeholder ="이메일 아이디 입력" >
<select type = "text" name = "sender_back" >
<option value = "@naver.com" >@naver.com</option >
<option value = "@hanmail.net" >@hanmail.net</option >
<option value = "@gmail.com" >@gmail.com</option >
</select >
</li >
<br >
<li >받는 사람 : <input type ="text" name = "recipient_front" placeholder ="이메일 아이디 입력" >
<select name ="recipient_back" type ="text" >
<option value = "@naver.com" >@naver.com</option >
<option value = "@hanmail.net" >@hanmail.net</option >
<option value = "@gmail.com" >@gmail.com</option >
<option value = "@chol.com" >@chol.com</option >
<option value = "@empal.com" >@empal.com</option >
<option value = "@freechal.com" >@freechal.com</option >
<option value = "@hanmir.com" >@hanmir.com</option >
<option value = "@hitel.net" >@hitel.net</option >
<option value = "@nete.com" >@nate.com</option >
</select >
</li >
<br >
<li >제목 : <input type ="text" name ="title" placeholder =" 이메일의 제목 입력" / ></li ><br >
<li >내용 : <textarea name ="text" name = "text" placeholder =" 보낼 내용 입력 " ></textarea > </li ><br >
<center >
<button type = "submit" name = "submit" >이메일 전송</button >
</center >
</ul >
</td >
</tr >
</table >
</form >
cs
MemberController.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
// mailSending 코드 (메인페이지에서 메일을 보낼때 맵핑되는 메소드)
@RequestMapping(value = "e_mailForm.do" , method= RequestMethod.POST )
public ModelAndView main_mailSending(HttpServletRequest request, String sender_front, String sender_back,
String recipient_front, String recipient_back, String title, String text, HttpServletResponse response_email) throws IOException {
String setfrom = request.getParameter("sender_front" )+ request.getParameter("sender_back" ); //보내는 사람 이메일
String tomail = request.getParameter("recipient_front" )+ request.getParameter("recipient_back" ); // 받는 사람 이메일
String mail_title = request.getParameter("title" ); // 제목
String content = request.getParameter("text" ); //이메일 내용
System .out .println (setfrom); //값이 잘 담겼는지 테스트
System .out .println (tomail);
System .out .println (mail_title);
System .out .println (content);
try {
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper messageHelper = new MimeMessageHelper(message,
true , "UTF-8" );
messageHelper.setFrom(setfrom); // 보내는사람 생략하면 정상작동을 안함
messageHelper.setTo(tomail); // 받는사람 이메일
messageHelper.setSubject(mail_title); // 메일제목은 생략이 가능하다
messageHelper.setText(content); // 메일 내용
mailSender.send(message);
} catch (Exception e) {
System .out .println (e);
}
ModelAndView mv = new ModelAndView(); //ModelAndView로 보낼 페이지를 지정하고, 보낼 값을 지정한다.
mv.setViewName("home" ); //뷰의이름
//이메일이 발송될때 자바스크립트로 발송되었다고 출력시킴
response_email.setContentType("text/html; charset=UTF-8" );
PrintWriter out_email = response_email.getWriter();
out_email.println ("<script>alert('이메일이 발송되었습니다.');</script>" );
out_email.flush();
return mv;
}
cs
Back-End/Spring 2019. 8. 6. 15:58
기본 구조
1. 메인페이지에서 "회원가입" 을 클릭
2. 이메일 인증 페이지에서 이메일을 작성후 인증코드 전송 버튼을 클릭
3. 입력한 이메일에 들어가서 메일로 도착한 인증코드를 인증코드 입력창에 입력함
4. 인증코드가 맞으면 회원가입 창으로 이동하고, 인증코드가 틀리면 경고창을 출력한 후에 다시 입력하게 한다.
1. pom.xml에 이메일 관련 라이브러리를 추가함
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<!-- 메일 전송 -->
<!-- https://mvnrepository.com/artifact/org.springframework/spring-context-support -->
<dependency >
<groupId >org.springframework</groupId >
<artifactId >spring-context-support</artifactId >
<version >${org.springframework-version}</version >
</dependency >
<!-- https://mvnrepository.com/artifact/com.sun.mail/javax.mail -->
<dependency >
<groupId >com.sun.mail</groupId >
<artifactId >javax.mail</artifactId >
<version >1.6.2</version >
</dependency >
<dependency >
<groupId >javax.mail</groupId >
<artifactId >mail</artifactId >
<version >1.4</version >
</dependency >
cs
2. root-context.xml에 사용할 이메일에 대한 빈 작성 (나같은 경우는 gmail을 사용함)
<!-- Gmail -->
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host" value="smtp.gmail.com" />
<property name="port" value="587" />
<property name="username" value="아이디@gmail.com" />
<property name="password" value="비밀번호 " />
<property name="javaMailProperties">
<props>
<prop key="mail.smtp.auth">true</prop>
<prop key="mail.smtp.starttls.enable">true</prop>
</props>
</property>
</bean>
cs
3. view 파일들 작성
email.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
<% @ page language= "java" contentType= "text/html; charset=UTF-8"
pageEncoding= "UTF-8" %>
<!DOCTYPE html >
<html >
<head >
<meta charset ="UTF-8" >
<title >Insert title here</title >
</head >
<body >
<table border ="1" width ="300" height ="300" align = "center" >
<center >
<span style ="color: green; font-weight: bold;" >이메일 인증 (이메일을 인증 받아야 다음 단계로 넘어갈 수 있습니다.)</span > <br > <br >
<br > <br >
<div style ="text-align:center;" >
<tr >
<td >
<center >
<form action ="auth.do" method ="post" >
<center >
<br >
<div >
이메일 : <input type ="email" name ="e_mail"
placeholder =" 이메일주소를 입력하세요. " >
</div >
<br > <br >
<button type ="submit" name ="submit" >이메일 인증받기 (이메일 보내기)</button >
</div >
</td >
</tr >
</center >
</table >
</form >
</center >
</body >
</html >
cs
email_injeung.jsp (인증번호를 입력하는 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
<% @ page language= "java" contentType= "text/html; charset=UTF-8"
pageEncoding= "UTF-8" %>
<!DOCTYPE html >
<html >
<head >
<meta charset ="UTF-8" >
<title >Insert title here</title >
</head >
<body >
<table border ="1" width ="300" height ="300" align = "center" >
<center >
<span style ="color: green; font-weight: bold;" >입력한 이메일로 받은 인증번호를 입력하세요. (인증번호가 맞아야 다음 단계로 넘어가실 수 있습니다.)</span > <br > <br >
<br > <br >
<div style ="text-align:center;" >
<tr >
<td >
<center >
<form action ="join_injeung.do${dice} " method ="post" > //받아온 인증코드를 컨트롤러로 넘겨서 일치하는지 확인
<center >
<br >
<div >
인증번호 입력 : <input type ="number" name ="email_injeung"
placeholder =" 인증번호를 입력하세요. " >
</div >
<br > <br >
<button type ="submit" name ="submit" >인증번호 전송</button >
</div >
</td >
</tr >
</center >
</table >
</form >
</center >
</body >
</html >
cs
4. 컨트롤러 작성 (Member Controller.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
@Controller //컨트롤러 빈 선언
public class MemberController {
@Inject //서비스를 호출하기 위해서 의존성을 주입
JavaMailSender mailSender; //메일 서비스를 사용하기 위해 의존성을 주입함.
MemberService memberservice; //서비스를 호출하기 위해 의존성을 주입
//로깅을 위한 변수
private static final Logger logger=
LoggerFactory.getLogger(MemberController.class );
private static final String String = null ;
// mailSending 코드
@RequestMapping( value = "/member/auth.do" , method= RequestMethod.POST )
public ModelAndView mailSending(HttpServletRequest request, String e_mail, HttpServletResponse response_email) throws IOException {
Random r = new Random ();
int dice = r.nextInt( 4589362 ) + 49311 ; //이메일로 받는 인증코드 부분 (난수)
String setfrom = "dlgkstjq623@gamil.com" ;
String tomail = request.getParameter("e_mail" ); // 받는 사람 이메일
String title = "회원가입 인증 이메일 입니다." ; // 제목
String content =
System .getProperty( "line.separator" ) + //한줄씩 줄간격을 두기위해 작성
System .getProperty("line.separator" )+
"안녕하세요 회원님 저희 홈페이지를 찾아주셔서 감사합니다"
+ System .getProperty("line.separator" )+
System .getProperty("line.separator" )+
" 인증번호는 " + dice+ " 입니다. "
+ System .getProperty("line.separator" )+
System .getProperty("line.separator" )+
"받으신 인증번호를 홈페이지에 입력해 주시면 다음으로 넘어갑니다." ; // 내용
try {
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper messageHelper = new MimeMessageHelper(message,
true , "UTF-8" );
messageHelper.setFrom(setfrom); // 보내는사람 생략하면 정상작동을 안함
messageHelper.setTo(tomail); // 받는사람 이메일
messageHelper.setSubject(title); // 메일제목은 생략이 가능하다
messageHelper.setText(content); // 메일 내용
mailSender.send(message);
} catch (Exception e) {
System .out .println (e);
}
ModelAndView mv = new ModelAndView(); //ModelAndView로 보낼 페이지를 지정하고, 보낼 값을 지정한다.
mv.setViewName("/member/email_injeung" ); //뷰의이름
mv.addObject("dice" , dice);
System .out .println ("mv : " + mv);
response_email.setContentType("text/html; charset=UTF-8" );
PrintWriter out_email = response_email.getWriter();
out_email.println ("<script>alert('이메일이 발송되었습니다. 인증번호를 입력해주세요.');</script>" );
out_email.flush();
return mv;
}
//이메일 인증 페이지 맵핑 메소드
@RequestMapping("/member/email.do" )
public String email() {
return "member/email" ;
}
//이메일로 받은 인증번호를 입력하고 전송 버튼을 누르면 맵핑되는 메소드.
//내가 입력한 인증번호와 메일로 입력한 인증번호가 맞는지 확인해서 맞으면 회원가입 페이지로 넘어가고,
//틀리면 다시 원래 페이지로 돌아오는 메소드
@RequestMapping(value = "/member/join_injeung.do{dice}" , method = RequestMethod.POST)
public ModelAndView join_injeung(String email_injeung, @PathVariable String dice, HttpServletResponse response_equals) throws IOException {
System .out .println ("마지막 : email_injeung : " + email_injeung);
System .out .println ("마지막 : dice : " + dice);
//페이지이동과 자료를 동시에 하기위해 ModelAndView를 사용해서 이동할 페이지와 자료를 담음
ModelAndView mv = new ModelAndView();
mv.setViewName("/member/join.do" );
mv.addObject("e_mail" ,email_injeung);
if (email_injeung.equals (dice)) {
//인증번호가 일치할 경우 인증번호가 맞다는 창을 출력하고 회원가입창으로 이동함
mv.setViewName("member/join" );
mv.addObject("e_mail" ,email_injeung);
//만약 인증번호가 같다면 이메일을 회원가입 페이지로 같이 넘겨서 이메일을
//한번더 입력할 필요가 없게 한다.
response_equals.setContentType("text/html; charset=UTF-8" );
PrintWriter out_equals = response_equals.getWriter();
out_equals.println ("<script>alert('인증번호가 일치하였습니다. 회원가입창으로 이동합니다.');</script>" );
out_equals.flush();
return mv;
}else if (email_injeung ! = dice) {
ModelAndView mv2 = new ModelAndView();
mv2.setViewName("member/email_injeung" );
response_equals.setContentType("text/html; charset=UTF-8" );
PrintWriter out_equals = response_equals.getWriter();
out_equals.println ("<script>alert('인증번호가 일치하지않습니다. 인증번호를 다시 입력해주세요.'); history.go(-1);</script>" );
out_equals.flush();
return mv2;
}
return mv;
}
cs
5. MailHandler.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
package com.example.hansub_project;
import java.io.UnsupportedEncodingException;
import javax.activation.DataSource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
public class MailHandler {
private JavaMailSender mailSender;
private MimeMessage message;
private MimeMessageHelper messageHelper;
public MailHandler(JavaMailSender mailSender) throws MessagingException {
this .mailSender = mailSender;
message = this .mailSender.createMimeMessage();
messageHelper = new MimeMessageHelper(message, true , "UTF-8" );
}
public void setSubject(String subject) throws MessagingException {
messageHelper.setSubject(subject);
// 이메일 타이틀
}
public void setText(String htmlContent) throws MessagingException {
messageHelper.setText(htmlContent, true );
// 이메일 TEXT 부분
}
public void setFrom(String email, String name) throws UnsupportedEncodingException, MessagingException {
messageHelper.setFrom(email, name);
// 보내는 사람 이메일
}
public void setTo(String email) throws MessagingException {
messageHelper.setTo(email);
//받는 사람 이메일
}
public void addInline(String contentId, DataSource dataSource) throws MessagingException {
messageHelper.addInline(contentId, dataSource);
}
public void send() {
try {
mailSender.send(message);
}catch (Exception e) {
e.printStackTrace();
}
}
}
cs
6. MemberDTO
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
package com.example.hansub_project.model.member.dto;
import java.util.Date;
public class MemberDTO {
private String user_id; //아이디
private String member_pass; //비밀번호
private String e_mail; //이메일
private Date join_date; //가입일자
public String getUser_id() {
return user_id;
}
public void setUser_id(String user_id) {
this .user_id = user_id;
}
public String getMember_pass() {
return member_pass;
}
public void setMember_pass(String member_pass) {
this .member_pass = member_pass;
}
public String getE_mail() {
return e_mail;
}
public void setE_mail(String e_mail) {
this .e_mail = e_mail;
}
public Date getJoin_date() {
return join_date;
}
public void setJoin_date(Date join_date) {
this .join_date = join_date;
}
@Override
public String toString () {
return "MemberDTO [user_id=" + user_id + ", member_pass=" + member_pass + ", e_mail=" + e_mail + ", join_date="
+ join_date + "]" ;
}
}
cs
7. 서비스 , dao, mapper
MemberService.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
package com.example.hansub_project.service.member;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.example.hansub_project.model.member.dto.MemberDTO;
public interface MemberService {
public void join (Map< String , Object> map,MemberDTO dto); //회원가입 관련
public boolean loginCheck(MemberDTO dto, HttpSession session); //로그인 관련
public String find_idCheck(MemberDTO dto); //아이디 찾기 관련
public String find_passCheck(MemberDTO dto); //비밀번호 찾기 관련
public void authentication(MemberDTO dto); //회원 인증관련 메소드
public void pass_change(Map< String , Object> map, MemberDTO dto)throws Exception; //비밀번호 변경
public boolean email_check(String e_mail) throws Exception; //이메일 중복확인을 하는 메소드
public boolean join_id_check(String user_id) throws Exception; //회원가입시 아이디를 체크하는 메소드
public List< MemberDTO> member_profile(String user_id) throws Exception; //회원의 프로필을 볼 수 있는 메소드
}
cs
MemberServiceImpl.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
package com.example.hansub_project.service.member;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;
import javax.inject.Inject;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.example.hansub_project.MailHandler;
import com.example.hansub_project.model.member.dao.MemberDAO;
import com.example.hansub_project.model.member.dto.MemberDTO;
@Service //서비스 빈 선언
public class MemberSerivceImpl implements MemberService {
@Inject
MemberDAO memberdao; //dao를 사용하기 위해 의존성을 주입
private JavaMailSender mailSender;
@Override //회원가입 메소드, Map과 dto를 갖이 넘김
public void join(Map< String , Object> map,MemberDTO dto) {
memberdao.join(map,dto);
}
@Override //로그인 관련 메소드 (세션에 아이디와 비밀번호를 저장)
public boolean loginCheck(MemberDTO dto, HttpSession session) {
boolean result = memberdao.loginCheck(dto);
if (result) { //로그인 성공
session.setAttribute("user_id" , dto.getUser_id());
session.setAttribute("member_pass" , dto.getMember_pass());
System .out .println (session.getAttribute("user_id" ));
System .out .println (session.getAttribute("member_pass" ));
}
return result;
}
//아이디 찾기
@Override
public String find_idCheck(MemberDTO dto) {
String id = memberdao.find_idCheck(dto);
return id;
}
//비밀번호 찾기
@Override
public String find_passCheck(MemberDTO dto) {
String pass = memberdao.find_passCheck(dto);
return pass;
}
@Override
public void authentication(MemberDTO dto) {
memberdao.authentication(dto);
}
@Override
public void pass_change(Map< String , Object> map, MemberDTO dto) throws Exception {
memberdao.pass_change(map,dto);
}
//이메일 중복 확인
@Override
public boolean email_check(String e_mail) throws Exception{
boolean result = memberdao.email_check(e_mail);
return result;
}
//아이디 중복 확인
@Override
public boolean join_id_check(String user_id) throws Exception {
boolean result = memberdao.join_id_check(user_id);
return result;
}
//자신의 프로필을 볼 수 있게 하는 메소드
@Override
public List< MemberDTO> member_profile(String user_id) throws Exception{
return memberdao.member_profile(user_id);
}
}
cs
MemberDAO.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
package com.example.hansub_project.model.member.dao;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.example.hansub_project.model.member.dto.MemberDTO;
public interface MemberDAO {
public void join(Map< String , Object> map,MemberDTO dto); //회원가입 관련
public boolean loginCheck(MemberDTO dto); //로그인 관련
public String find_idCheck(MemberDTO dto); //아이디 찾기
public String find_passCheck(MemberDTO dto); //비밀번호 찾기
public void authentication(MemberDTO dto); //소셜 로그인 회원인증 관련 메소드
public void pass_change(Map< String , Object> map, MemberDTO dto)throws Exception; //비밀번호 변경
public boolean email_check(String e_mail) throws Exception; //이메일 중복 확인
public boolean join_id_check(String user_id)throws Exception; //아이디 중복 확인
public List< MemberDTO> member_profile(String user_id) throws Exception; //회원의 프로필 정보를 확인할 수 있는 메소드
}
cs
MemberDAOImpl.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
package com.example.hansub_project.model.member.dao;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.inject.Inject;
import javax.mail.Session;
import org.apache.ibatis.session.SqlSession;
import org.springframework.stereotype.Repository;
import com.example.hansub_project.model.member.dto.MemberDTO;
@Repository
public class MemberDAOImpl implements MemberDAO {
@Inject
SqlSession sqlSession;
//회원가입 관련 메소드
@Override
public void join(Map< String , Object> map, MemberDTO dto) {
map.get("user_id" );
map.get("member_pass" );
map.get("e_mail" );
sqlSession.insert("member.insertUser" ,map);
}
//로그인관련 메소드
@Override
public boolean loginCheck(MemberDTO dto) {
String name
= sqlSession.selectOne("member.login_check" , dto);
//조건식 ? true일때의 값 : false일때의 값
return (name= = null ) ? false : true ;
}
//아이디 찾기 관련 메소드
@Override
public String find_idCheck(MemberDTO dto) {
String id = sqlSession.selectOne("member.find_id_check" , dto);
return id;
}
//비밀번호 찾기 관련 메소드
@Override
public String find_passCheck(MemberDTO dto) {
String pass = sqlSession.selectOne("member.find_pass_check" , dto);
return pass;
}
//회원 인증 관련 메소드
//버튼을 클릭한 회원의 정보를 회원 테이블에 저장해서 사용할 수 있게 함
@Override
public void authentication(MemberDTO dto) {
sqlSession.insert("member.authentication" , dto);
}
@Override
public void pass_change(Map< String , Object> map, MemberDTO dto)throws Exception{
map.get("member_pass" );
map.get("e_mail" );
sqlSession.update("member.pass_change" , map);
}
@Override
public boolean email_check(String e_mail) throws Exception {
String email
= sqlSession.selectOne("member.email_check" , e_mail);
//조건식 ? true일때의 값 : false일때의 값
return (email= = null ) ? true : false ;
}
@Override
public boolean join_id_check(String user_id) throws Exception {
String user_id1
= sqlSession.selectOne("member.join_id_check" , user_id);
//조건식 ? true일때의 값 : false일때의 값
return (user_id1= = null ) ? true : false ;
}
//회원의 프로필 정보를 리턴한다.
@Override
public List< MemberDTO> member_profile(String user_id) throws Exception {
return sqlSession.selectList("member.member_profile" , user_id);
}
}
cs
memberMapper.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
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
<?xml version ="1.0" encoding ="UTF-8" ? >
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<!-- 다른 mapper와 중복되지 않도록 네임스페이스 기재 -->
<!-- 회원가입 -->
<mapper namespace ="member" >
<!-- 회원가입 mapper -->
<insert id ="insertUser" parameterType ="hashMap" >
insert into member (USER_ID, MEMBER_PASS, E_MAIL)
values (#{user_id}, #{member_pass}, #{e_mail})
</insert >
<!-- 로그인 관련 mapper-->
<select id = "login_check" parameterType =
"com.example.hansub_project.model.member.dto.MemberDTO"
resultType ="String" >
select user_id from member
where user_id=#{user_id} and member_pass=#{member_pass}
</select >
<!-- 아이디 찾기 관련 mapper -->
<select id = "find_id_check" parameterType =
"com.example.hansub_project.model.member.dto.MemberDTO"
resultType ="String" >
select user_id from member
where e_mail=#{e_mail}
</select >
<!-- 비밀번호 찾기 관련 mapper -->
<select id = "find_pass_check" parameterType =
"com.example.hansub_project.model.member.dto.MemberDTO"
resultType ="String" >
select member_pass from member
where user_id=#{user_id} and e_mail=#{e_mail}
</select >
<!-- 소셜 로그인 관련 mapper -->
<!-- 소셜 로그인 한 후에 회원 인증 버튼을 누르면 소셜 로그인 api에서 받아온 정보를 데이터 베이스의 member테이블에 저장하도록 하는 쿼리 -->
<insert id ="authentication" parameterType ="com.example.hansub_project.model.member.dto.MemberDTO" >
insert into member (USER_ID, MEMBER_PASS, E_MAIL)
values (#{user_id}, 0, #{e_mail})
</insert >
<!-- 비밀번호 변경 관련 mapper -->
<update id = "pass_change" parameterType ="hashMap" >
update member set member_pass=#{member_pass} where e_mail=#{e_mail}
</update >
<!-- 이메일 중복확인 관련 mapper-->
<select id = "email_check" resultType ="String" >
select e_mail from member
where e_mail=#{e_mail}
</select >
<!-- 아이디 중복확인 관련 mapper-->
<select id = "join_id_check" resultType ="String" >
select user_id from member
where user_id=#{user_id}
</select >
<!-- 회원 프로필 확인 mapper -->
<select id = "member_profile" resultType ="com.example.hansub_project.model.member.dto.MemberDTO" >
select user_id, e_mail, join_date
from member
where user_id=#{user_id}
</select >
</mapper >
cs
Back-End/Spring 2019. 8. 5. 17:38
1. xml 을 이용한 등록 방법 - setter을 이용
1) applicationContext.xml
<
bean
id
=
"sqlMapClientTemplate"
class
=
"org.springframework.orm.ibatis.SqlMapClientTemplate"
>
<
property
name
=
"sqlMapClient"
ref
=
"sqlMapClient"
/>
</
bean
>
<
bean
id
=
"loginDAO"
class
=
"com.mungchung.sample.login.LoginDAOImpl"
>
<
property
name
=
"sqlMapClientTemplate"
ref
=
"sqlMapClientTemplate"
/>
</
bean
>
2) Bean
public
class
LoginDAOImpl
implements
LoginDAO {
private
SqlMapClientTemplate sqlMapClientTemplate;
public
void
setSqlMapClientTemplate(SqlMapClientTemplate sqlMapClientTemplate) {
this
.sqlMapClientTemplate = sqlMapClientTemplate;
}
}
2. xml 을 이용한 등록 방법 - 생성자 이용
1) applicationContext.xml
<
bean
id
=
"sqlMapClientTemplate"
class
=
"org.springframework.orm.ibatis.SqlMapClientTemplate"
>
<
property
name
=
"sqlMapClient"
ref
=
"sqlMapClient"
/>
</
bean
>
<
bean
id
=
"loginDAO"
class
=
"com.mungchung.sample.login.LoginDAOImpl"
>
<
constructor-arg
name
=
"sqlMapClientTemplate"
ref
=
"sqlMapClientTemplate"
/>
</
bean
>
2) Bean
public
class
LoginDAOImpl
implements
LoginDAO {
private
SqlMapClientTemplate sqlMapClientTemplate;
public
LoginDAOImpl(SqlMapClientTemplate sqlMapClientTemplate) {
this
.sqlMapClientTemplate = sqlMapClientTemplate;
}
}
3. 어노테이션 이용 - 직접 Bean 등록
1) servlet - context.xml
<
context:annotation-config
/>
<
bean
id
=
"loginDAO"
class
=
"com.mungchung.sample.login.LoginDAOImpl"
/>
2) Bean
public
class
LoginDAOImpl
implements
LoginDAO {
@Autowired
private
SqlMapClientTemplate sqlMapClientTemplate;
}
4. 어노테이션 이용 - Component - Scan 이용
1) servlet - context.xml
<
context:component-scan
base-package
=
"com.mungchung.sample.login"
/>
2) Bean
@Repository
public
class
LoginDAOImpl
implements
LoginDAO {
@Autowired
private
SqlMapClientTemplate sqlMapClientTemplate;
}
출처
https://denodo1.tistory.com/188
Back-End/Spring 2019. 7. 31. 15:03
1. https://www.coolsms.co.kr / 에서 회원가입 하기 (300포인트를 주는데 15건정도 보낼수 있음)
2. coolsms에 개발자센터 (https://www.coolsms.co.kr/developer)에 들어가서 api_key와 api_secret를 생성하고, api를 다운받는다.
* SDK -> JAVA -> JAVA SDK v2.1에 들어가서 순서대로 따라한다.
위 처럼 SDK를 다운받아도 되고, 메이븐저장소에서 다운로드 받아 추가해도 된다.
pom.xml에 라이브러리를 추가
<dependency>
<groupId>net.nurigo</groupId>
<artifactId>javaSDK</artifactId>
<version>2.2</version>
</dependency>
cs
api와 예제를 참고해서 만들어보기
(예제 관련 참고 주소 : https://www.coolsms.co.kr/JAVA_SDK_Example )
======================== === =========코드 부분===============================
view파일에 코드추가 (home.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
<!-- 문자보내는 폼 -->
<form method ="post" id ="smsForm" >
<table border = "1" align ="right" width = "300" height = "200" >
<tr >
<td >
<center >
<br >
<span style ="color: green; font-weight: bold;" >SMS 전송 (문자보내기)</span >
</center >
<ul >
<li >보낼사람 : <input type ="text" name ="from" placeholder =" 전화번호 입력 ( '-' 포함 )" / ></li ><br >
<li >내용 : <textarea name ="text" placeholder =" 보낼 내용 입력 " ></textarea > </li ><br >
<center >
<input type ="button" onclick ="sendSMS('sendSms')" value ="전송하기" / ><br >
</center >
</ul >
</td >
</tr >
</table >
</form >
<script >
function sendSMS(pageName){
console .log("문자를 전송합니다." );
$("#smsForm" ).attr("action" , pageName + ".do" ); //위에 있는 폼태그를 컨트롤러로 전송한다.
$("#smsForm" ).submit();
}
</script >
cs
컨트롤러 (MemberController.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
//문자를 보낼때 맵핑되는 메소드
@RequestMapping(value = "/sendSms.do" )
public String sendSms(HttpServletRequest request) throws Exception {
String api_key = "NCS0VWZPZQPVXEXX" ; //위에서 받은 api key를 추가
String api_secret = "DKTPX4RYWG5GEDPL6DMRRNKOJMATK24X" ; //위에서 받은 api secret를 추가
com.example.hansub_project.Coolsms coolsms = new com.example.hansub_project.Coolsms(api_key, api_secret);
//이 부분은 홈페이지에서 받은 자바파일을 추가한다음 그 클래스를 import해야 쓸 수 있는 클래스이다.
HashMap< String , String > set = new HashMap< String , String > ();
set.put("to" , "01072851455" ); // 수신번호
set.put("from" , (String )request.getParameter("from " )); // 발신번호, jsp에서 전송한 발신번호를 받아 map에 저장한다.
set.put("text" , (String )request.getParameter("text " )); // 문자내용, jsp에서 전송한 문자내용을 받아 map에 저장한다.
set.put("type" , "sms " ); // 문자 타입
System .out .println (set);
JSONObject result = coolsms.send(set); // 보내기&전송결과받기
if ((boolean )result.get("status" ) = = true ) {
// 메시지 보내기 성공 및 전송결과 출력
System .out .println ("성공" );
System .out .println (result.get("group_id" )); // 그룹아이디
System .out .println (result.get("result_code" )); // 결과코드
System .out .println (result.get("result_message" )); // 결과 메시지
System .out .println (result.get("success_count" )); // 메시지아이디
System .out .println (result.get("error_count" )); // 여러개 보낼시 오류난 메시지 수
} else {
// 메시지 보내기 실패
System .out .println ("실패" );
System .out .println (result.get("code" )); // REST API 에러코드
System .out .println (result.get("message" )); // 에러메시지
}
return "member/number" ; //문자 메시지 발송 성공했을때 number페이지로 이동함
}
cs
Https.java 파일 작성 (Https request, response를 관리하는 클래스 )
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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
package com.example.hansub_project;
import java.io.* ;
import java.net.URL;
import java.net.URLEncoder;
import javax.crypto.* ;
import javax.crypto.spec.SecretKeySpec;
import javax.net.ssl.HttpsURLConnection;
import java.util.Random ;
import java.util.HashMap;
import java.util.Map.Entry;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
/*
* Https.class
* Https request, response를 관리하는 class 입니다.
*/
public class Https
{
/*
* postRequest (POST)
* @param StringBuffer : data
* @param String : image
*/
public JSONObject postRequest(String url_string, HashMap< String , String > params) {
JSONObject obj = new JSONObject();
try {
obj.put("status" , false );
String salt = salt();
String timestamp = getTimestamp();
String signature = getSignature(params.get("api_secret" ), salt, timestamp);
String boundary = salt + timestamp;
String delimiter = "\r\n--" + boundary + "\r\n" ;
params.put("salt" , salt);
params.put("signature" , signature);
params.put("timestamp" , timestamp);
// data 생성 및 데이터 구분을 위한 delimiter 설정
StringBuffer postDataBuilder = new StringBuffer();
postDataBuilder.append(delimiter);
// params에 image가 있으면 변수에 담아 request를 다르게 보낸다
String image = null ;
String image_path = null ;
for (Entry< String , String > entry : params.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
if (key = = "image" ) {
image = value;
continue ;
}
if (key = = "image_path" ) {
image_path = value;
continue ;
}
postDataBuilder = setPostData(postDataBuilder, key, value, delimiter);
if (postDataBuilder = = null ) {
obj.put("message" , "postRequest data build fail" );
return obj;
}
}
URL url = new URL(url_string);
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); // connect
connection.setDoInput(true );
connection.setDoOutput(true );
connection.setRequestMethod("POST" );
connection.setRequestProperty("Connection" , "Keep-Alive" );
connection.setRequestProperty("Content-Type" , "multipart/form-data;boundary=" + boundary);
connection.setUseCaches(false );
DataOutputStream outputStream = new DataOutputStream(new BufferedOutputStream(connection.getOutputStream()));
// image data set
if (image ! = null ) {
// MMS Setting
if (image_path = = null ) image_path = "./" ;
// image file set
postDataBuilder.append(setFile("image" , image));
postDataBuilder.append("\r\n" );
FileInputStream fileStream = new FileInputStream(image_path + image);
outputStream.writeUTF(postDataBuilder.toString ());
// 파일전송 작업 시작
int maxBufferSize = 1024 ;
int bufferSize = Math.min(fileStream.available(), maxBufferSize);
byte [] buffer = new byte [bufferSize];
// 버퍼 크기만큼 파일로부터 바이트 데이터를 읽는다
int byteRead = fileStream.read(buffer, 0 , bufferSize);
// 전송
while (byteRead > 0 ) {
outputStream.write(buffer);
bufferSize = Math.min(fileStream.available(), maxBufferSize);
byteRead = fileStream.read(buffer, 0 , bufferSize);
}
fileStream.close();
} else {
outputStream.writeUTF(postDataBuilder.toString ());
}
outputStream.writeBytes(delimiter);
outputStream.flush();
outputStream.close();
String response = null ;
String inputLine;
int response_code = connection.getResponseCode();
BufferedReader in = null ;
// response 담기
if (response_code ! = 200 ) {
in = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
} else {
in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
}
while ((inputLine = in .readLine()) ! = null ) {
response = inputLine;
}
if (response ! = null ) {
obj = (JSONObject) JSONValue.parse(response);
obj.put("status" , true );
if (obj.get("code" ) ! = null ) {
obj.put("status" , false );
}
} else {
obj.put("status" , false );
obj.put("message" , "response is empty" );
}
} catch (Exception e) {
obj.put("status" , false );
obj.put("message" , e.toString ());
}
return obj;
}
/*
* https request (GET)
*/
public JSONObject request(String url_string, HashMap< String , String > params) {
JSONObject obj = new JSONObject();
try {
obj.put("status" , true );
String charset = "UTF8" ;
String salt = salt();
String timestamp = getTimestamp();
String signature = getSignature(params.get("api_secret" ), salt, timestamp); // getSignature
String data = url_string + "?" ;
data = data + URLEncoder.encode("api_key" , charset) + "=" + URLEncoder.encode(params.get("api_key" ), charset);
data = setGetData(data, "signature" , signature, charset);
data = setGetData(data, "salt" , salt, charset);
data = setGetData(data, "timestamp" , timestamp, charset);
params.remove("api_secret" );
for (Entry< String , String > entry : params.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
data = setGetData(data, key, value, charset);
if (data = = null ) {
obj.put("status" , false );
obj.put("message" , "request data build fail" );
return obj;
}
}
URL url = new URL(data);
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); // connect
connection.setRequestMethod("GET" );
BufferedReader in = null ;
int response_code = connection.getResponseCode();
if (response_code ! = 200 ) {
// 오류발생시
in = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
} else {
in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
}
String response = null ;
String inputLine; // 서버로 부터 받은 response를 받을 변수
while ((inputLine = in .readLine()) ! = null ) {
response = inputLine;
}
if (response ! = null ) {
// response 가 object 냐 array에 따라 parse를 다르게한다.
try {
obj = (JSONObject) JSONValue.parse(response);
} catch (Exception e) {
try {
JSONArray reponse_array = (JSONArray) JSONValue.parse(response);
obj.put("data" , reponse_array);
} catch (Exception ex) {
obj.put("status" , false );
}
}
obj.put("status" , true );
if (obj.get("code" ) ! = null ) {
obj.put("status" , false );
}
} else {
obj.put("status" , false );
obj.put("message" , "response is empty" );
}
} catch (Exception e) {
obj.put("status" , false );
obj.put("message" , e.toString ());
}
return obj;
}
/*
* 업로드할 파일에 대한 메타 데이터를 설정한다.
* @param key : 서버에서 사용할 파일 변수명
* @param fileName : 서버에서 저장될 파일명
*/
public String setFile(String key, String fileName) {
return "Content-Disposition: form-data; name=\"" + key
+ "\";filename=\"" + fileName
+ "\"\r\nContent-type: image/jpeg;\r\n" ;
}
/*
* String을 POST 형식에 맞게 Input
*/
public StringBuffer setPostData(StringBuffer builder, String key, String value, String delimiter) {
try {
builder.append(setValue(key, value));
builder.append(delimiter);
} catch (Exception e) {
return null ;
}
return builder;
}
/*
* String을 GET 방식으로 변경
*/
public String setGetData(String data, String key, String value, String charSet) {
try {
data + = "&"
+ URLEncoder.encode(key, charSet)
+ "="
+ URLEncoder.encode(value, charSet);
} catch (Exception e) {
return null ;
}
return data;
}
/*
* Get salt
*/
public String salt() {
String uniqId = "" ;
Random randomGenerator = new Random ();
// length - set the unique Id length
for (int length = 1 ; length < = 10 ; + + length ) {
int randomInt = randomGenerator.nextInt(10 ); // digit range from 0 - 9
uniqId + = randomInt + "" ;
}
return uniqId;
}
/*
* Get signature
*/
public String getSignature(String api_secret, String salt, String timestamp) {
String signature = "" ;
try {
String temp = timestamp + salt;
SecretKeySpec keySpec = new SecretKeySpec(api_secret.getBytes(), "HmacMD5" );
Mac mac = Mac.getInstance("HmacMD5" );
mac.init(keySpec);
byte [] result = mac.doFinal(temp.getBytes());
char [] hexArray = "0123456789ABCDEF" .toCharArray();
char [] hexChars = new char [result.length * 2 ];
for (int i = 0 ; i < result.length ; i+ + ) {
int positive = result[i] & 0xff ;
hexChars[i * 2 ] = hexArray[positive > > > 4 ];
hexChars[i * 2 + 1 ] = hexArray[positive & 0x0F ];
}
signature = new String (hexChars);
} catch (Exception e) {
signature = e.getMessage();
}
return signature;
}
/*
* Get timestamp
*/
public String getTimestamp() {
long timestamp_long = System .currentTimeMillis() / 1000 ;
String timestamp = Long.toString (timestamp_long);
return timestamp;
}
/*
* Map 형식으로 Key와 Value를 셋팅한다.
* @param key : 서버에서 사용할 변수명
* @param value : 변수명에 해당하는 실제 값
*/
public String setValue(String key, String value) {
return "Content-Disposition: form-data; name=\"" + key + "\"\r\n\r\n" + value;
}
}
cs
Coolsms.java (Coolsms 클래스, 문자 전송을 위한 coolsms관련 메소드를 사용하기 위한 클래스 )
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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
package com.example.hansub_project;
import java.io.* ;
import java.net.URLEncoder;
import javax.crypto.* ;
import javax.crypto.spec.SecretKeySpec;
import javax.net.ssl.HttpsURLConnection;
import java.util.Properties;
import java.util.Random ;
import java.util.HashMap;
import java.util.Map.Entry;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
/*
* Coolsms Class
* RestApi JAVA
* v1.1
* POST?GET REQUEST
*/
public class Coolsms extends Https {
final String URL = "https://api.coolsms.co.kr" ;
private String sms_url = URL + "/sms/1.5/" ;
private String senderid_url = URL + "/senderid/1.1/" ;
private String api_key;
private String api_secret;
private String timestamp;
private Https https = new Https();
Properties properties = System .getProperties();
/*
* Set api_key, api_secret
*/
public Coolsms(String api_key, String api_secret) {
this .api_key = api_key;
this .api_secret = api_secret;
}
/*
* Send messages
* @param set : HashMap<String, String>
*/
public JSONObject send(HashMap< String , String > params) {
JSONObject response = new JSONObject();
try {
// 기본정보 입력
params = setBasicInfo(params);
params.put("os_platform" , properties.getProperty("os_name" ));
params.put("dev_lang" , "JAVA " + properties.getProperty("java.version" ));
params.put("sdk_version" , "JAVA SDK 1.1" );
// Send message
response = https.postRequest(sms_url + "send" , params);
} catch (Exception e) {
response.put("status" , false );
response.put("message" , e.toString ());
}
return response;
}
/*
* Sent messages
* @param set : HashMap<String, String>
*/
public JSONObject sent(HashMap< String , String > params) {
JSONObject response = new JSONObject();
try {
// 기본정보 입력
params = setBasicInfo(params);
response = https.request(sms_url + "sent" , params); // GET방식 전송
} catch (Exception e) {
response.put("status" , false );
response.put("message" , e.toString ());
}
return response;
}
/*
* Reserve message cancel
* @param set : HashMap<String, String>
*/
public JSONObject cancel(HashMap< String , String > params) {
JSONObject response = new JSONObject();
try {
// 기본정보 입력
params = setBasicInfo(params);
// Cancel reserve message
response = https.postRequest(sms_url + "cancel" , params);
// Cancel은 response 가 empty 면 성공
if (response.get("message" ) = = "response is empty" ) {
response.put("status" , true );
response.put("message" , null );
}
} catch (Exception e) {
response.put("status" , false );
response.put("message" , e.toString ());
}
return response;
}
/*
* Balance info
*/
public JSONObject balance() {
JSONObject response = new JSONObject();
try {
// 기본정보 입력
HashMap< String , String > params = new HashMap< String , String > ();
params = setBasicInfo(params);
// GET방식 전송
response = https.request(sms_url + "balance" , params); // GET방식 전송
} catch (Exception e) {
response.put("status" , false );
response.put("message" , e.toString ());
}
return response;
}
/*
* Register sender number
* @param set : HashMap<String, String>
*/
public JSONObject register(HashMap< String , String > params) {
JSONObject response = new JSONObject();
try {
// 기본정보 입력
params = setBasicInfo(params);
// Register sender number request
response = https.postRequest(senderid_url + "register" , params);
} catch (Exception e) {
response.put("status" , false );
response.put("message" , e.toString ());
}
return response;
}
/*
* Verify sender number
* @param set : HashMap<String, String>
*/
public JSONObject verify(HashMap< String , String > params) {
JSONObject response = new JSONObject();
try {
// 기본정보 입력
params = setBasicInfo(params);
// Register verify sender number
response = https.postRequest(senderid_url + "verify" , params);
if (response.get("message" ) = = "response is empty" ) {
response.put("status" , true );
response.put("message" , null );
}
} catch (Exception e) {
response.put("status" , false );
response.put("message" , e.toString ());
}
return response;
}
/*
* Delete sender number
* @param set : HashMap<String, String>
*/
public JSONObject delete(HashMap< String , String > params) {
JSONObject response = new JSONObject();
try {
// 기본정보 입력
params = setBasicInfo(params);
// Register delete sender number
response = https.postRequest(senderid_url + "delete" , params);
if (response.get("message" ) = = "response is empty" ) {
response.put("status" , true );
response.put("message" , null );
}
} catch (Exception e) {
response.put("status" , false );
response.put("message" , e.toString ());
}
return response;
}
/*
* Set default sender number
* @param set : HashMap<String, String>
*/
public JSONObject setDefault(HashMap< String , String > params) {
JSONObject response = new JSONObject();
try {
// 기본정보 입력
params = setBasicInfo(params);
// Register set default sender number
response = https.postRequest(senderid_url + "set_default" , params);
if (response.get("message" ) = = "response is empty" ) {
response.put("status" , true );
response.put("message" , null );
}
} catch (Exception e) {
response.put("status" , false );
response.put("message" , e.toString ());
}
return response;
}
/*
* Get sender number list
* @param set : HashMap<String, String>
*/
public JSONObject list() {
JSONObject response = new JSONObject();
try {
// 기본정보 입력
HashMap< String , String > params = new HashMap< String , String > ();
params = setBasicInfo(params);
// Register sender number request
response = https.request(senderid_url + "list" , params);
} catch (Exception e) {
response.put("status" , false );
response.put("message" , e.toString ());
}
return response;
}
/*
* Get default sender number
* @param set : HashMap<String, String>
*/
public JSONObject getDefault() {
JSONObject response = new JSONObject();
try {
// 기본정보 입력
HashMap< String , String > params = new HashMap< String , String > ();
params = setBasicInfo(params);
// Get default sender number
response = https.request(senderid_url + "get_default" , params);
} catch (Exception e) {
response.put("status" , false );
response.put("message" , e.toString ());
}
return response;
}
/*
* Set api_key and api_secret.
* @param set : HashMap<String, String>
*/
private HashMap< String , String > setBasicInfo(HashMap< String , String > params) {
params.put("api_secret" , this .api_secret);
params.put("api_key" , this .api_key);
return params;
}
}
cs
출처
https://seonhyungjo.github.io/Spring-SMS/
Back-End/Spring 2019. 7. 30. 10:50
1. https://developers.facebook.com/ (페이스북 개발자센터 접속) 하고, 앱 만들기 선택
2. 앱을 등록했다면 Facebook 로그인 -> 시작하기 버튼 선택, 플랫폼을 웹으로 선택
============================== 코드 부분=========================================
1. 로그인 페이지 (login.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
<!-- 페이스북 아이디를 연동해서 로그인 -->
<center >
<button type ="button" id ="loginBtn" ><img src ="file:///C:/Users/user/git/hs_project/hansub_project/src/main/webapp/WEB-INF/views/images/facelogin.jpg" / >페이스북으로 로그인</button >
</center >
<div id ="access_token" ></div >
<div id ="user_id" ></div >
<div id ="name" ></div >
<div id ="email" ></div >
<div id ="gender" ></div >
<div id ="birthday" ></div >
<div id ="id" ></div >
<script >
function getUserData() {
/* FB.api('/me', function(response) {
document.getElementById('response').innerHTML = 'Hello ' + response.name;
console.log(response);
}); */
FB.api('/me' , {fields: 'name,email' }, function (response) {
var facebookname = response. name ;
window . location .replace( "http://" + window . location .hostname + ( ( location .port = = "" | | location .port = = undefined)? "" : ":" + location .port) + "/hansub_project/home?facebookname=" + facebookname);
});
}
window .fbAsyncInit = function () {
//SDK loaded, initialize it
FB.init({
appId : '488986078336253' , //페이스북 개발자 홈페이지에서 앱 id를 확인해서 복사, 붙여넣기 해야한다.
cookie : true , // enable cookies to allow the server to access
// the session
xfbml : true , // parse social plugins on this page
version : 'v3.3' // use graph api version 2.8 //페이스북 개발자 홈페이지에서 버전을 확인해서 작성해야 한다.
});
//check user session and refresh it
FB.getLoginStatus(function (response) {
if (response.status = = = 'connected' ) {
//user is authorized
//document.getElementById('loginBtn').style.display = 'none';
getUserData();
} else {
//user is not authorized
}
});
};
//load the JavaScript SDK
(function (d, s, id){
var js, fjs = d.getElementsByTagName(s)[0 ];
if (d.getElementById (id)) {return ;}
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.com/ko_KR/sdk.js" ;
fjs.parentNode.insertBefore(js, fjs);
}(document , 'script' , 'facebook-jssdk' ));
//add event listener to login button, //버튼을 클릭하면 실행되는 함수
document .getElementById ('loginBtn' ).addEventListener ('click' , function () {
//do the login
FB.login(function (response) {
if (response.authResponse) {
access_token = response.authResponse.accessToken; //get access token
user_id = response.authResponse.userID; //get FB UID
console .log('access_token = ' + access_token);
console .log('user_id = ' + user_id);
//user just authorized your app
//document.getElementById('loginBtn').style.display = 'none';
getUserData();
}
}, {scope: 'email,public_profile,user_birthday' ,
return_scopes: true });
}, false );
</script >
cs
2. 메인 페이지 (home.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
<!-- url 파라미터로 받은 로그인한 아이디 값이 있을시에는 "name+방문을 환영한다"고 출력이 되고, null값일 때에는 "guest님 방문을 환영합니다" 메시지가 출력되도록 한다.-->
<%
String navername = request.getParameter("navername" );
String kakaonickname = request.getParameter("kakaonickname" );
String facebookname = request.getParameter( "facebookname" ); //url로 넘긴 name를 파라미터로 받는다.
session.setAttribute("navername" , navername);
session.setAttribute("kakaonickname" , kakaonickname);
session.setAttribute( "facebookname" , facebookname); //그리고 그 값을 세션에 저장한다.
if (navername = = null & & kakaonickname = = null & & facebookname = = null ) {
%>
guest님 방문을 환영합니다.
<% @ include file= "member/login.jsp" %>
<%
} else if (navername ! = null ){
%>
<% = " (네이버) " + session.getAttribute("navername" )%> 님 방문을 환영합니다.
<form action ="naver_logout.do" method = "post" >
<button type = "submit" name = "submit" >로그아웃</button >
</form >
<%
} else if (kakaonickname ! = null ){
%>
<% = " (카카오톡) " + session.getAttribute("kakaonickname" )%> 님 방문을 환영합니다.
<form action = "kakao_logout.do" method = "post" >
<button type = "submit" name = "submit" >로그아웃</button ></form >
<%
} else if (facebookname ! = null ){ //name값이 null값이 아닐때 실행되는 부분.
%>
<% = " (페이스북) " + session.getAttribute( "facebookname" ) %> 님 방문을 환영합니다.
< form action = "facebook_logout.do" method = "post" >
< button type = "submit" name = "submit" > 로그아웃 < / button > < / form >
<%
};
%>
cs
3. 컨트롤러 (MemberController.java) 로그아웃시 맵핑되는 부분
//페이스북 관련 로그아웃 메소드
@RequestMapping("facebook_logout.do" )
public String facebook_logout(HttpSession session, HttpServletRequest request) {
//세션에 담긴값 초기화
session.invalidate();
return "home" ;
}
cs
출처
http://blog.naver.com/PostView.nhn?blogId=daeng2c&logNo=220946788245&parentCategoryNo=&categoryNo=13&viewDate=&isShowPopularPosts=true&from=search