페이지 내 에서 발생되는 XHR Response를 모니터링 하는 방법

두가지 방법을 소개하고자한다.

XHRHttpRequest 선언시 EventHandler에 등록하는 방법

const xhr = new XMLHttpRequest(),
    method = "GET",
    url = "https://developer.mozilla.org/";

xhr.open(method, url, true);
xhr.onreadystatechange = function () {
  // In local files, status is 0 upon success in Mozilla Firefox
  if(xhr.readyState === XMLHttpRequest.DONE) {
    var status = xhr.status;
    if (status === 0 || (status >= 200 && status < 400)) {
      // The request has been completed successfully
      console.log(xhr.responseText);
    } else {
      // Oh no! There has been an error with the request!
    }
  }
};
xhr.send();
//출처
//https://wiki.developer.mozilla.org/ko/docs/Web/API/XMLHttpRequest/onreadystatechange

이 방법은 XHR을 선언하면서 이벤트 등록을 통해 해당 xhr의 이벤트롤 콘솔로 감시할수 있습니다.

XHRHttpRequest 를 재정의 하는 방법

let oldXHROpen = window.XMLHttpRequest.prototype.open;
window.XMLHttpRequest.prototype.open = function(method, url, async, user, password) {
    this.addEventListener('load', function() {
        console.log(this.response);
    });
    return oldXHROpen.apply(this, arguments);
}

 

'WEB > JS' 카테고리의 다른 글

XMLHttpRequest(XHR) 란 무엇인가.  (0) 2020.10.06

XHR은 무엇일까?

XHR은 XMLHttpRequest의 약자로 말 그대로 http 프로토콜을 통해 서버에 자원을 요청하기 위해 사용한다.

페이지 전체를 새로고침 할 필요 없이 원하는 데이터를 url에서 제공받을 수 있다.

대표적인 예로 Ajax가 있다.

Methods

  • abort이미 전송된 request를 중단
  • getAllResponseHeaders모든 ResponseHeader를 문자열로 반환합니다. response가 없는경우는 null 을 반환합니다.
  • getResponseHeader(headerName)header의 값들 중 해당하는 입력으로 들어온 이름과 일치하는 값을 반환합니다.
  • open(method, url[, async[, user[, password]]])request를 초기화 합니다
    url, 요청방법, 비동기 여부, 인증목적의 user, password 등을 포함합니다
  • send(body)
    request를 서버에 보냅니다.
    Document, Blob, BufferSource, FormData, URLSerchParams, USVString 등이 포함될 수 있습니다.
  • setRequestHeader(header, value)
    request header의 값을 지정합니다.
    open 과 send 사이에 call해야하며, 여러번 call할시에는 기존의 header's content에 더해지게 됩니다.

Example

 

5) Spring - 회원가입(ajax를 이용한 id 중복체크)

json을 이용하기 위한 lib 추가 pom.xml에 아래 코드를 추가해 줍니다. com.googlecode.json-simple json-simple 1.1 org.codehaus.jackson jackson-mapper-asl 1.9.13 Register.jsp 수정 ajax를 이용하기위해 jqu..

migusdn.tistory.com

에서 Jquery를 이용한 ajax를 XMLHttpRequest로 바꿔보겠다.

//Jquery

id = $("#user_id").val();
	
$.ajax({
    url: 'ID_Check',
    type: 'POST',
    dataType: 'text', //서버로부터 내가 받는 데이터의 타입
    contentType : 'text/plain; charset=utf-8;',//내가 서버로 보내는 데이터의 타입
    data: id ,
    success: function(data){
         if(data == 0){
         console.log("아이디 없음");
         alert("사용하실 수 있는 아이디입니다.");
         }else{
         	console.log("아이디 있음");
         	alert("중복된 아이디가 존재합니다.");
         }
    },
 });
 
//XMLHttpRequest

const id = document.getElementById("user_id").val();

var checkRequest = new XMLHttpRequest();

checkRequest.onload = function(){
	if(checkRequest.status === 200 || checkRequest.status === 201) {
		if(checkRequest.responseText == 0){
			console.log("아이디 없음");
			alert("사용하실 수 있는 아이디입니다.");
		} else {
			console.log("아이디 있음");
			alert("중복된 아이디가 존재합니다.");
		} 
	} else {
		console.log("error");
	}
};

checkRequest.open("POST", "ID_Check");
checkRequest.setRequestHeader("Content-Type", "text/plain; charset=utf-8;");
checkRequest.setRequestHeader("dataType", "text");
checkRequest.send(id);

출처: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest, https://xhr.spec.whatwg.org/

'WEB > JS' 카테고리의 다른 글

XHR response Monitering  (0) 2020.11.07

기존에 작성한 bbs_detail 페이지의 삭제 버튼에 대한 기능구현을 하려합니다.

먼저 삭제를 위해 BDao, BbsDao에 삭제관련된 인터페이스를 추가해주고 mapper/BDao.xml 에서는 삭제 쿼리문 작성 이들을 이용해 컨트롤로에서 삭제 수행 메소드를 작성하는 순서로 쓰겠습니다.


Dao/BDao.java 와 BbsDao.java의 수정


BDao.java

아래 메소드를 추가해줍니다.

public void Delete(String bbs_id);

BbsDao.java

	@Override
	public void Delete(String bbs_id) {
	}

mapper/BDao.xml의 수정


BDao.xml에 아래 쿼리문을 등록해줍니다.

	<delete id="Delete">
	DELETE
	FROM bbs
	WHERE bbs_id = #{bbs_id}
	</delete>

BbsController 의 수정


BbsController 의 하단에 아래 메소드를 추가해줍니다

	@ResponseBody
	@RequestMapping("/Delete")
	public String bbs_delete(HttpServletRequest request, Model model) {
		BDao dao = sqlSession.getMapper(BDao.class);
		dao.Delete(request.getParameter("bbs_id"));
		String str="<script>";
		str+="location.href='/app/bbs/';";
		str+="</script>";
		return str;
	}

위와 같이 작성하면 삭제가 잘 수행되는 것을 볼 수있다

'WEB > Spring' 카테고리의 다른 글

11) Spring - 게시글 수정  (0) 2019.11.18
10) Spring - 게시글 보기 구현  (0) 2019.11.01
9) Spring - 게시글 목록 구현  (0) 2019.11.01
8) Spring - 게시판 글쓰기 구현  (0) 2019.10.12
7) Spring - 로그아웃  (0) 2019.10.12

bbs_detail.jsp 수정


게시글 수정을 위해 게시글 상세 페이지에 버튼을 추가합니다.

기존 테이블 하단에 새로운 행을 생성하고 버튼을 추가해줍니다

<table width=80% height=500px border=1 align=center>
	<tr height=30px>
	<td align="center" colspan="1">제목</td>
	<td align="center" colspan="3"><c:out value="${detail.bbs_title}"/></td>
	</tr>
	<tr>
	<td align="center" width=25%>작성자</td>
	<td align="center" width=25%><c:out value="${detail.author}"/></td>
	<td align="center" width=25%>작성일</td>
	<td align="center" width=25%><c:out value="${detail.date}"/></td>
	</tr>
	<tr>
	<td align="center" colspan="4">내 용</td>
	</tr>
	<tr height = 500px>
	<td colspan="4"><c:out value="${detail.bbs_content}"/></td>
	</tr>
	<tr>
	<td colspan="2">
	<button onclick="location.href='/app/bbs/edit/${detail.bbs_id}';">수정</button>
	</td>
	<td colspan="2">
	<button>삭제</button>
	</td>
	</tr>
</table>

수정을 위한 bbs_edit.jsp 작성


<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
	
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<form method="post" action="/app/EditAct">
		<table>
			<tr>
				<td>
					<table width="100%" cellpadding="0" cellspacing="0" border="0">
						<tr>
							<td>글쓰기</td>
						</tr>
					</table>
					<table>
						<tr>
							<td>&nbsp;</td>
							<td align="center">제목</td>
							<td><input name="bbs_title" size="50" maxlength="100" value="<c:out value="${detail.bbs_title}"/>"></td>
							<td>&nbsp;</td>
						</tr>
						<tr height="1">
							<td colspan="4"></td>
						</tr>
						<tr>
							<td>&nbsp;</td>
							<td align="center">내용</td>
							<td><textarea name="bbs_content" cols="50" rows="13"><c:out value="${detail.bbs_content}"/></textarea></td>
							<td>&nbsp;</td>
						</tr>
						<tr height="1">
							<td colspan="4"></td>
						</tr>
						<tr height="1">
							<td colspan="4"></td>
						</tr>
						<tr align="center">
							<td>&nbsp;</td>
							<td colspan="2"><input type="submit" value="수정">
							<td>&nbsp;</td>
						</tr>
						<input type="hidden" name="bbs_id" value="<c:out value="${detail.bbs_id}"/>">
					</table>
				</td>
			</tr>
		</table>
	</form>
</body>
</html>

위 코드는 게시글 보기 페이지 구현을 할때 사용한 jstl을 이용하여 구성하였습니다.

컨트롤러에서 model Attribute로 심어준 데이터를 html상에서 뿌려주는 역할을 합니다.


Dao/BbsDao.java 와 BDao.java 수정


BbsDao와 BDao에 수정을 위한 메소드 Edit을 추가해줍니다.

BDao

public interface BDao {
	public void Write(Map map);
	public ArrayList<BbsDto> list();
	public BbsDto detail(String bbs_id);
	public void Edit(Map map);
}

BbsDao

	public void Edit(Map map) {
		// TODO Auto-generated method stub
		
	}

mapper/BDao.xml 수정


BDao.xml에 UPDATE 쿼리를 등록합니다.

	<update id="Edit">
	UPDATE bbs
	SET
		bbs_title = #{bbs_title},
		bbs_content = #{bbs_content}
	WHERE bbs_id = #{bbs_id}
	</update>

 

BbsController 수정


bbsController에 이전 포스트에서 사용했던 PathVariable을 이용하여 수정 페이지에 접속하는 매핑 메소드를 생성해줍니다.

	@RequestMapping("/bbs/edit/{bbs_id}")
	public String bbs_edit(@PathVariable String bbs_id, Model model) {
		BDao dao = sqlSession.getMapper(BDao.class);
		BbsDto detail = dao.detail(bbs_id);
		model.addAttribute("detail", detail);
		return "bbs_edit";
	}

게시글의 수정이 이루어지는 메소드 입니다

	@ResponseBody
	@RequestMapping("/EditAct")
	public String EditAct(HttpSession session, HttpServletRequest request) throws UnsupportedEncodingException {
		request.setCharacterEncoding("utf-8");
		Map map = new HashMap();
		map.put("bbs_title", request.getParameter("bbs_title"));
		map.put("bbs_content", request.getParameter("bbs_content"));
		map.put("bbs_id", request.getParameter("bbs_id"));
		BDao dao = sqlSession.getMapper(BDao.class);
		dao.Edit(map);
		String str="<script>";
		str+="location.href='/app/bbs/';";
		str+="</script>";
		return str;
	}

위와 같이 작성하고 직접 접속하여 확인해보면 잘 수정되는 것을 볼 수 있습니다.

'WEB > Spring' 카테고리의 다른 글

12) Spring - 게시글 삭제  (0) 2019.11.19
10) Spring - 게시글 보기 구현  (0) 2019.11.01
9) Spring - 게시글 목록 구현  (0) 2019.11.01
8) Spring - 게시판 글쓰기 구현  (0) 2019.10.12
7) Spring - 로그아웃  (0) 2019.10.12

이전 글에서 게시글 목록까지 구현하였고, 이제 게시글 목록에서 게시글을 클릭하여 내용을 볼 수 있는 페이지를 만드려고한다.

먼저 게시글을 보기위한 jsp 부터 작성해주도록 한다.


bbs_detail.jsp 작성


<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>bbs_detail</title>
</head>
<body>

<table width=80% height=500px border=1 align=center>
	<tr height=30px>
	<td align="center" colspan="1">제목</td>
	<td align="center" colspan="3"><c:out value="${detail.bbs_title}"/></td>
	</tr>
	<tr>
	<td align="center" width=25%>작성자</td>
	<td align="center" width=25%><c:out value="${detail.author}"/></td>
	<td align="center" width=25%>작성일</td>
	<td align="center" width=25%><c:out value="${detail.date}"/></td>
	</tr>
	<tr>
	<td align="center" colspan="4">내 용</td>
	</tr>
	<tr height = 500px>
	<td colspan="4"><c:out value="${detail.bbs_content}"/></td>
	</tr>
</table>
</body>
</html>

BbsDao, BDao 수정


BbsDao와 BDao에 아래 메소드를 추가해준다.

public BbsDto detail(String bbs_id);

mapper/BDao.xml 수정


아래 쿼리문을 추가해준다.

<select id="detail" resultType="com.app.app.Dto.BbsDto">
	SELECT *
		FROM bbs
		WHERE bbs_id = #{bbs_id}
</select>

위 쿼리문은 BbsController가 넘겨운 bbs_id를 통해 DB의 bbs테이블에서 해당 아이디를 가진 게시글을 BbsDto로 리턴해준다.


BbsController - bbs_detail 메소드 추가


	@RequestMapping("/bbs/{bbs_id}")
	public String bbs_detail(@PathVariable String bbs_id, Model model) {
		BDao dao = sqlSession.getMapper(BDao.class);
		BbsDto detail = dao.detail(bbs_id);
		model.addAttribute("detail", detail);
		return "bbs_detail";
	}

위의 코드에서

	@RequestMapping("/bbs/{bbs_id}")
	public String bbs_detail(@PathVariable String bbs_id, Model model) {

위 부분은 url /bbs/뒤에 들어오는 게시글 번호를 변수로 사용할 수 있게 해준다.

ex) http://~/app/bbs/5 -> 게시글 번호가 5번인 게시글 조회

PathVariable로 지정된 {bbs_id}는 DB에서 게시글 조회를 위한 키 넘버로 쓰인다.


 위와 같이 다 작성한 후 게시글 조회를 시도해보자.

위와 같이 나온다면 제대로 한 것이다.

'WEB > Spring' 카테고리의 다른 글

12) Spring - 게시글 삭제  (0) 2019.11.19
11) Spring - 게시글 수정  (0) 2019.11.18
9) Spring - 게시글 목록 구현  (0) 2019.11.01
8) Spring - 게시판 글쓰기 구현  (0) 2019.10.12
7) Spring - 로그아웃  (0) 2019.10.12

이전 글에서 글쓰기 까지 구현 하였고, 이번 게시글에서는 글 목록 구현을 하겠습니다.

먼저 목록에 접근하기위한 링크를 메인화면에 삽입하겠습니다


index.jsp의 수정


<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">

<title>Index</title>
</head>
<body>
Login ID:
<c:out value="${sessionScope.user_id }" default="null"/>
<table border="1" align="center" width="500" height="400">
	<tr>
		<td colspan="4" height="100" align="center">Main page</td>
	</tr>
	<tr>
		<td colspan="4" height="100" align="center"><a href="write">글 쓰기</a></td>
	</tr>
	<tr>
		<td colspan="4" height="100" align="center"><a href="bbs">글 목록</a></td>
	</tr>
	<tr>
	<c:if test="${empty sessionScope.user_id}">
		<td colspan="2" align="center" width="250"><a href="Login">로그인</a></td>
	</c:if>
	
	<c:if test="${!empty sessionScope.user_id}">
		<td colspan="2" align="center" width="250"><a href="Logout">로그아웃</a></td>
	</c:if>
		<td colspan="2" align="center" width="250"><a href="Register">회원가입</a></td>
	</tr>
</table>
</body>
</html>

Controller/BbsController - bbs 메소드 작성


게시글 목록 조회에 대한 처리를 해주는 메소드 bbs를 작성합니다.

	@RequestMapping("/bbs")
	public String bbs(Model model) {
		
		BDao dao = sqlSession.getMapper(BDao.class);
		ArrayList<BbsDto> list = dao.list();
		model.addAttribute("list",list);
		return "bbs";
	}

model.addAttribute("list", list) 는 DB조회를 통해 생성된 list 객체 배열을 jsp에서 쓰기위해 속성으로 추가해주는 과정입니다.


Dao/BDao, BbsDao - DB 조회를 위한 list 메소드 추가


BDao에 list 메소드를 추가합니다.

package com.app.app.Dao;

import java.util.ArrayList;
import com.app.app.Dto.BbsDto;
import java.util.Map;
import com.app.app.Dto.UserDto;

public interface BDao {
	public void Write(Map map);
	public ArrayList<BbsDto> list();
}

mapper/Bdao.xml 수정


게시글 조회를 위한 쿼리를 추가해줍니다.

	<select id="list" resultType="com.app.app.Dto.BbsDto">
	SELECT *
		FROM bbs
	</select>
	

JSTL 을 이용한 bbs.jsp 작성


<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

<table width=80% height=70% border=1 align=center>
	<tr>
	<th width=10% align="">글 번호</th>
	<th width=20%>작성자</th>
	<th width=40%>글 제목</th>
	<th width=30%>작성일</th>
	</tr>
	<c:forEach var="bbs" items="${list }">
	<tr align="center">
	<td> <c:out value="${bbs.bbs_id }"/></td>
	<td> <c:out value="${bbs.author }"/></td>
	<td align="left"><a href='bbs/<c:out value="${bbs.bbs_id }"/>'> <c:out value="${bbs.bbs_title }"/></a></td>
	<td> <c:out value="${bbs.date }"/></td>
	</tr>
	</c:forEach>
	<tr>
	</tr>
</table>
</body>
</html>

 

위의 <c:forEach var="bbs" items="${list}"> ~ 의 코드는 JSTL tag로서 forEach는 for 문이라고 생각하면 된다.

bbsController에서 게시글 목록조회하여 속성으로 심어준 ArrayList<BbsDto> list 객체를 화면에 순서대로 뿌려주는 역할을 한다.

JSTL을 잘 이용하면 코드 가독성이 높아지고 간결화된다.

예를 들면 위의 코드를 스크립트릿을 이용하여 작성하면 이렇게 된다.

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page import="com.app.app.Dto.BbsDto" %>
<%@ page import="java.util.ArrayList" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

<table width=80% height=70% border=1 align=center>
	<tr>
	<th width=10% align="">글 번호</th>
	<th width=20%>작성자</th>
	<th width=40%>글 제목</th>
	<th width=30%>작성일</th>
	</tr>
	<%
	ArrayList<BbsDto> bbs = new ArrayList<BbsDto>();
	bbs = (ArrayList<BbsDto>)request.getAttribute("list");
	for(int i=0; i<bbs.size(); i++){
	%>
	<tr align="center">
	<td> <%=bbs.get(i).getBbs_id() %>
	<td> <%=bbs.get(i).getAuthor() %>
	<td align="left"><a href='bbs/<%=bbs.get(i).getBbs_id()%>'> <%=bbs.get(i).getBbs_title() %></a></td>
	<td> <%=bbs.get(i).getDate() %></td>
	</tr>
	<%
	}
	%>
    <tr>
	</tr>
</table>
</body>
</html>

java.util.ArrayList 와 com.app.app.Dto.BbsDto를 따로 import 해주어야 하고 같은 기능을 하는 코드인데 더 많은 코드를 요구로한다.


이제 게시글을 작성하고 확인해보자.

위와 같이 나온다면 제대로 한것이다.

 

'WEB > Spring' 카테고리의 다른 글

11) Spring - 게시글 수정  (0) 2019.11.18
10) Spring - 게시글 보기 구현  (0) 2019.11.01
8) Spring - 게시판 글쓰기 구현  (0) 2019.10.12
7) Spring - 로그아웃  (0) 2019.10.12
6) Spring - 로그인(Session 이용)  (0) 2019.10.08

게시판 Table 생성


mysql command를 키고 아래 코드를 입력합니다.

USE BBS;
 
CREATE TABLE IF NOT EXISTS bbs(
    bbs_id INT(10) NOT NULL AUTO_INCREMENT PRIMARY KEY,
    bbs_title VARCHAR(32) NOT NULL,
    bbs_content VARCHAR(1000) NOT NULL,
    author VARCHAR(32) NOT NULL,
    date DATETIME DEFAULT CURRENT_TIMESTAMP
    );


BbsDto 생성


Dto 패키지 아래에 BbsDto를 생성해줍니다.

package com.app.app.Dto;

public class BbsDto {
	private String bbs_id;
	private String bbs_title;
	private String bbs_content;
	private String author;
	private String date;
	public String getBbs_id() {
		return bbs_id;
	}
	public void setBbs_id(String bbs_id) {
		this.bbs_id = bbs_id;
	}
	public String getBbs_title() {
		return bbs_title;
	}
	public void setBbs_title(String bbs_title) {
		this.bbs_title = bbs_title;
	}
	public String getBbs_content() {
		return bbs_content;
	}
	public void setBbs_content(String bbs_content) {
		this.bbs_content = bbs_content;
	}
	public String getAuthor() {
		return author;
	}
	public void setAuthor(String author) {
		this.author = author;
	}
	public String getDate() {
		return date;
	}
	public void setDate(String date) {
		this.date = date;
	}
}

index.jsp 수정


<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">

<title>Index</title>
</head>
<body>
Login ID:
<c:out value="${sessionScope.user_id }" default="null"/>
<table border="1" align="center" width="500" height="300">
	<tr>
		<td colspan="4" height="100" align="center">Main page</td>
	</tr>
	<tr>
		<td colspan="4" height="100" align="center"><a href="write">글 쓰기</a></td>
	</tr>
	<tr>
	<c:if test="${empty sessionScope.user_id}">
		<td colspan="2" align="center" width="250"><a href="Login">로그인</a></td>
	</c:if>
	
	<c:if test="${!empty sessionScope.user_id}">
		<td colspan="2" align="center" width="250"><a href="Logout">로그아웃</a></td>
	</c:if>
		<td colspan="2" align="center" width="250"><a href="Register">회원가입</a></td>
	</tr>
</table>
</body>
</html>


wirte.jsp 작성


<%@ 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>
	<form method="post" action="WriteAct">
		<table>
			<tr>
				<td>
					<table width="100%" cellpadding="0" cellspacing="0" border="0">
						<tr>
							<td>글쓰기</td>
						</tr>
					</table>
					<table>
						<tr>
							<td>&nbsp;</td>
							<td align="center">제목</td>
							<td><input name="bbs_title" size="50" maxlength="100"></td>
							<td>&nbsp;</td>
						</tr>
						<tr height="1">
							<td colspan="4"></td>
						</tr>
						<tr>
							<td>&nbsp;</td>
							<td align="center">내용</td>
							<td><textarea name="bbs_content" cols="50" rows="13"></textarea></td>
							<td>&nbsp;</td>
						</tr>
						<tr height="1">
							<td colspan="4"></td>
						</tr>
						<tr height="1">
							<td colspan="4"></td>
						</tr>
						<tr align="center">
							<td>&nbsp;</td>
							<td colspan="2"><input type=button value="등록">
							<td>&nbsp;</td>
						</tr>
					</table>
				</td>
			</tr>
		</table>
	</form>
</body>
</html>

BDao , BbsDao 생성


Dao 패키지 아래에 BDao를 생성합니다.

package com.app.app.Dao;

import java.util.ArrayList;
import java.util.Map;
import com.app.app.Dto.UserDto;

public interface Bdao {
	public void Write(Map map);
}

BbsDao 도 생성해줍니다

package com.app.app.Dao;

import java.util.Map;

public class BbsDao implements BDao{

	@Override
	public void Write(Map map) {
	}

}

BDao.xml 생성


mapper 패키지 아래에 BDao.xml을 생성해줍니다.

<?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 namespace="com.app.app.Dao.BDao">

	<insert parameterType="Map" id="Write">
	INSERT INTO
		BBS (bbs_title, bbs_content, author)
		VALUES(#{bbs_title}, #{bbs_content}, #{author}) 
	</insert>
</mapper>

BbsController 수정


package com.app.app.Controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.ibatis.session.SqlSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.app.app.Dao.BDao;
import com.app.app.Dao.BbsDao;
import com.app.app.Dto.BbsDto;

import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.json.simple.JSONObject;




@Controller
public class BbsController {
	@Autowired
	private SqlSession sqlSession;
	
	private static final Logger logger = LoggerFactory.getLogger(AppController.class);
	
	
	@RequestMapping("/write")
	public String Write(Model model, HttpSession session, HttpServletResponse response) throws IOException {
		if(session.getAttribute("user_id") == null) {
			System.out.println("로그인세션 없음");
			response.setContentType("text/html; charset=UTF-8");
			PrintWriter out = response.getWriter();
			out.println("<script>alert('잘못된 접근'); history.back();</script>");
			out.flush();
		}
			
	return "write";	
	}
	@RequestMapping("/WriteAct")
	public String Write(HttpSession session, HttpServletRequest request) {
		Map map = new HashMap();
		map.put("bbs_title", request.getParameter("bbs_title"));
		map.put("bbs_content", request.getParameter("bbs_content"));
		map.put("author", session.getAttribute("user_id"));
		BDao dao = sqlSession.getMapper(BDao.class);
		dao.Write(map);
		return "index";
	}
}

이제 글쓰기를 해보자

mysql command에서 

use bbs;

select * from bbs; 를 입력하여 확인해보자

위와 같이 나오면 성공한것이다

index.jsp 수정


페이지 상단에 jstl 사용을 위한 taglib를 추가해줍니다.

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

세션을 체크하여 로그인된 상태에서는 로그아웃이 나오게 하고,

로그인이 필요한 상태에서는 로그인이 나오게 코드를 작성합니다 아래 코드는 jstl문법으로 작성된 코드입니다.

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">

<title>Index</title>
</head>
<body>
<table border="1" align="center" width="500" height="200">
	<tr>
		<td colspan="4" height="100" align="center">Main page</td>
	</tr>
	<tr>
	<c:if test="${empty sessionScope.user_id}">
		<td colspan="2" align="center" width="250"><a href="Login">로그인</a></td>
	</c:if>
	
	<c:if test="${!empty sessionScope.user_id}">
		<td colspan="2" align="center" width="250"><a href="Logout">로그아웃</a></td>
	</c:if>
		<td colspan="2" align="center" width="250"><a href="Register">회원가입</a></td>
	</tr>
</table>
Login ID:
<c:out value="${sessionScope.user_id }" default="null"/>
</body>
</html>

AppController 수정


AppController에 로그아웃을 위한 메소드 Logout을 새로 만들어줍니다.

	@ResponseBody
	@RequestMapping("/Logout")
	public String Logout(HttpSession session) {
		session.invalidate();
		String str = "<script>";
		str+="alert('Logout success');";
		str+="window.location.href = '/app';";
		str+="</script>";
		return str;
	}

+ Recent posts