교육 58일차

권재현·2021년 6월 11일
0

교육

목록 보기
43/49

비동기 방식 게시판 시작

새로운 패키지 생성

기본세팅

기존방식과 ajax 방식 차이

ajax방식은 로그인 성공, 실패 시 logins를 안 거치고 바로 보낸다.

ajax 구동 순서


웹에 text/json 타입으로 전달

TESTAController

package com.spring.sample.web.testa.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

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.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.spring.sample.common.bean.PagingBean;
import com.spring.sample.common.service.IPagingService;
import com.spring.sample.web.test.service.ITestLService;
import com.spring.sample.web.test.service.ITestService;

@Controller
public class TestAController {
	
	@Autowired
	public ITestLService iTestLService;
	
	@Autowired
	public ITestService iTestService;

	@Autowired
	public IPagingService iPagingService;
	
	
	@RequestMapping(value="/testALogin")
	public ModelAndView testALogin(ModelAndView mav) {

		mav.setViewName("testa/testALogin");

		return mav;
	}
	// RequestMapping : value - 주소
	//					method - 전송방식지정
	// 					produces - 돌려줄 형식
	@RequestMapping(value="/testALogins",
					method = RequestMethod.POST,
					produces = "text/json;charset=UTF-8")
	@ResponseBody // Spring에 view임을 제시, 오늘의 제일 중요한점 바로 웹으로 넘긴다. jsp 같은 역활을 한다.
	public String testALogins(
			HttpSession session,
			@RequestParam HashMap<String, String> params) throws Throwable{
		// ObjectMapper : 객체를 문자열로 전환 - Jackson 라이브러리
				ObjectMapper mapper = new ObjectMapper();
				//model은 데이터를 담고있는 것
				// 데이터 보관용 map
				// 모든 형태를 받기위해서 벨류값 형태 Object
				Map<String, Object> modelMap = new HashMap<String, Object>();

				HashMap<String, String> data = iTestLService.getM(params);

				if(data != null) { //사용자 정보가 있음
					session.setAttribute("sMNo", data.get("M_NO"));
					session.setAttribute("sMNm", data.get("M_NM"));
					System.out.println(session.getAttribute("sMNm"));

					modelMap.put("resMsg", "success");
				} else { // 사용자 정보가 없음
					modelMap.put("resMsg", "failed");

				}
				// "{"resMsg" : "success"}"
				// writeValueAsString :객체를 문자열로 변환 , 받는 인자값이 형태가 object라 다 받을 수 있음
				return mapper.writeValueAsString(modelMap);

	}
	
	 @RequestMapping(value="/testABList")
	 public ModelAndView testABList(
			 @RequestParam HashMap<String, String> params,
			 ModelAndView mav) {

		 int page = 1;

		 if(params.get("page") != null) {
			 page = Integer.parseInt(params.get("page"));
		 }

		 mav.addObject("page", page);
		 mav.setViewName("testa/testABList");

		 return mav;

	 }
	 
		@RequestMapping(value="/testABLists",
				method = RequestMethod.POST,
				produces = "text/json;charset=UTF-8")
	@ResponseBody
	public String testABLists(
			@RequestParam HashMap<String, String> params) throws Throwable{
		ObjectMapper mapper = new ObjectMapper();
		Map<String, Object> modelMap = new HashMap<String, Object>();
	
		// 현재 페이지
		int page = Integer.parseInt(params.get("page"));
	
	
		// 총 게시글 수 
		int cnt = iTestService.getBCnt(params);
	
		// 페이징 정보 취득
		PagingBean pb= iPagingService.getPagingBean(page, cnt); 
	
		//글번호 P 없으면 글번호
		//게시글 시작번호, 종료번호 할당
		params.put("startCnt", Integer.toString(pb.getStartCount()));
		params.put("endCnt", Integer.toString(pb.getEndCount()));
	
		// 목록 취득
		List<HashMap<String, String>>list= iTestService.getBList(params);
	
		modelMap.put("list", list);
		modelMap.put("pb", pb);
	
		return mapper.writeValueAsString(modelMap);
	}
		
		@RequestMapping(value="/testALogout")
		public ModelAndView testALogout(HttpSession session,
				ModelAndView mav) {
			session.invalidate();

			mav.setViewName("redirect:testALogin");
			return mav;
		}
	
}

testALogin

<%@ 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>
<script type="text/javascript"
		src="resources/script/jquery/jquery-1.12.4.min.js">
</script>	
<script type="text/javascript">
$(document).ready(function(){
	$("#loginBtn").on("click",function(){
		if($.trim($("#mId").val()) ==""){
			alert("아이디를 입력해주세요.");
			$("#mId").focus();
		} else if($.trim($("#mPw").val()) == ""){
			alert("비밀번호를 입력해주세요.");
			$("#mPw").focus();
		} else {
			//formdml data를 문자열로 전환
			var params = $("#loginForm").serialize();
		}
		
			//ajax
			$.ajax({
				url: "testALogins", //접속 주소
				type: "post", // 전송방식 : get, post
				dataType: "json", // 받아 올 데이터 형식
				data : params, // 보낼 데이터 (문자열 형태)
				success : function(res) { //성공 시 다음 함수 실행
					if(res.resMsg == "success"){
						location.href = "testABList";
					} else{
						alert("아이디 또는 비밀번호가 일치하지 않습니다.")
						$("#sp_msg").html("자바스크립트형식신기신기");
					}
					console.log(res);
				},
				error: function(request, status, error){ //실패 시 다음 함수 실행
					console.log(error);
				}
			
			});
	});// loginBtn end
			
});
</script>	
</head>
<body>
<form action="#" id="loginForm" method="post">
아이디<input type="text" id="mId" name="mId"/><br/>
비밀번호<input type="password" id="mPw" name="mPw"/><br/>
<input type="button" value="로그인" id="loginBtn"/>
<span id="sp_msg"></span>
</form>
</body>
</html> 

testABList

<%@ 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>
<style type="text/css">
.list_wrap table{
	border-collapse: collapse;
}
.list_wrap thead tr {
	border-top: 1px solid #000;
	border-bottom: 1px solid #000;
	background-color: orange;
	height: 30px;
}
.list_wrap tbody tr{
	border-bottom: 1px solid #000;
	height: 25px;
	text-align: center;
	cursor: pointer;
}
.list_wrap tbody tr td:nth-child(2){
	text-align: left;
}
.list_wrap tbody tr:nth-child(2n){
	background-color: #FFCCAA;
}
.list_wrap tbody tr:hover, .lsit wrap tbody tr:nth-child(2n):hover{
	background-color: blue;
	color: white;
}
.paing_wrap{
	margin-top: 10px;
}
.paging_wrap div{
	display:inline-block;
	padding: 5px;
	margin-left: 3px;
	margin-right: 3px;
	border: 1px solid #444;
	border-radius: 3px;
	width: 60px;
	cursor: pointer;
	text-align: center;
}
.paging_wrap div:active, #searchBtn:hover,#writeBtn:active{
	background-color: aqua;
}
.paging_wrap .on{
	background-color: red;
}	
</style>
<script type="text/javascript"
		src="resources/script/jquery/jquery-1.12.4.min.js">
</script>
<script type="text/javascript">
$(document).ready(function(){
	if("${param.searchGbn}" != ""){
		$("#searchGbn").val("${param.searchGbn}");
	}
	
	reloadList();
	
	$("#loginBtn").on("click",function(){
		location.href = "testALogin";
	});
	$("#logoutBtn").on("click",function(){
		location.href = "testALogout";
	});
	
	$("#searchBtn").on("click", function(){
		$("#page").val(1);
		reloadList();
	});
	
	$(".paging_wrap").on("click","div",function(){
		$("#page").val($(this).attr("page"));
		reloadList();
	});
	
}); //ready end
 
function reloadList() {
	var params = $("#actionForm").serialize();
	
	//ajax
	$.ajax({
		url: "testABLists", 
		type: "post", 
		dataType: "json",
		data : params, 
		success : function(res) {
			console.log(res);
			drawList(res.list);
			drawPaging(res.pb);
		},
		error: function(request, status, error){ 
			console.log(error);
		}
	
	});
}
// 목록 그리기
function drawList(list){
	var html = "";
	//" +  + " : 문자열 넣는 꿀팁
	for(var d of list){
		html += "<tr bno=\"" + d.B_NO + "\">";
		html += "<td>" +  d.B_NO + "</td> ";
		html += "<td>" +  d.B_TITLE + "</td> ";
		html += "<td>" +  d.B_WRITER + "</td> ";
		html += "<td>" +  d.B_DT + "</td> ";
		html += "</tr>";
	}
	
	$(".list_wrap tbody").html(html);
}
// 페이징 그리기
function drawPaging(pb){
	var html = "";
//	" + + "
	html += "<div page=\"1\">처음</div>";
	
	if($("#page").val() =="1") {
		html += "<div page=\"1\">이전</div>";
	} else{
		html += "<div page=\"" + ($("#page").val() - 1)  + "\">이전</div>";
	}
	for(var i = pb.startPcount ; i <= pb.endPcount ; i++){
		if($("#page").val() == i){
			html +="<div class=\"on\" page=\"" + i + "\">" + i + "</div>";
		}else{
			html +=	"<div page=\"" + i + "\">" + i + "</div>";
		}
	}
	
	if($("#page").val() == pb.maxPcount){
		html += "<div page=\"" + pb.maxPcount + "\">다음</div>";
	} else{
		html += "<div page=\"" + ($("#page").val() * 1 + 1)+ "\">다음</div>";
		
	}
	html += "<div page=\"" + pb.maxPcount + "\">마지막</div>";
	
	$(".paging_wrap").html(html);
}
</script>
</head>
<body>
<c:choose>
	<c:when test="${empty  sMNo}">
		<input type="button" value="로그인" id="loginBtn"/> 
	</c:when>
	<c:otherwise>
		${sMNm}님 어서오세요.<input type="button" value="로그아웃" id="logoutBtn"/>	
	</c:otherwise>
</c:choose>
<div class="search_area">
	<form action="#" id="actionForm" method="post">
		<input type="hidden" id="page" name="page" value="${page}"/>
		<select id="searchGbn" name="searchGbn">
			<option value="0">제목</option>
			<option value="1">작성자</option>
		</select>
		<input type="text" name="searchTxt" value="${param.searchTxt}"/>
		<input type="button" value="검색" id="searchBtn"/>
		<input type="button" value="작성" id="writeBtn"/>
	</form>
</div>
<div class="list_wrap">
	<table>
		<colgroup>
			<col width="100px" />
			<col width="400px" />
			<col width="200px" />
			<col width="100px" />
		</colgroup>
		<thead>
			<tr>
				<th>번호</th>
				<th>제목</th>
				<th>작성자</th>
				<th>작성일</th>
			</tr>
		</thead>
		<tbody></tbody>
	</table>
</div>

<div class="paging_wrap"></div> 
</body>
</html> 

출력결과

profile
호텔리어 출신 비전공자

0개의 댓글