본문 바로가기
study/Ajax

[Ajax] 26. 시,군,도 출력하기2 [(RestController) kiclayout.jsp, AjaxController.java]

by 금이패런츠 2022. 5. 19.
728x90
반응형

kiclayout.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:set var="path" value="${pageContext.request.contextPath }" />               
<!DOCTYPE html>
<html>
<head>
<title><sitemesh:write property='title'/>
</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Raleway">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="${path}/css/main.css">
<style>
html,body,h1,h2,h3,h4,h5 {font-family: "Raleway", sans-serif}
#footer {position: fixed; bottom: 50px;}
</style>
<script type="text/javascript"
	src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
	
<%-- 글작성시 다양한 형태 사용 가능 --%>
<script type="text/javascript" 
   src="http://cdn.ckeditor.com/4.5.7/standard/ckeditor.js"></script>
	
<sitemesh:write property='head'/>
</head>
<body class="w3-light-grey">

<!-- Top container -->
<div class="w3-bar w3-top w3-black w3-large" style="z-index:4">
  <button class="w3-bar-item w3-button w3-hide-large w3-hover-none w3-hover-text-light-grey" onclick="w3_open();"><i class="fa fa-bars"></i> &nbsp;Menu</button>
  <span class="w3-bar-item w3-right">
    <c:if test="${empty sessionScope.loginUser}">
       <a href="${path}/user/login">로그인</a>
       <a href="${path}/user/userEntry">회원가입</a>
	</c:if>  
    <c:if test="${!empty sessionScope.loginUser}">
        ${sessionScope.loginUser.username}님이 로그인 하셨습니다. &nbsp;&nbsp;
       <a href="${path}/user/logout">로그아웃</a>
	</c:if>  
  </span>
</div>

<!-- Sidebar/menu -->
<nav class="w3-sidebar w3-collapse w3-white w3-animate-left" style="z-index:3;width:200px;" id="mySidebar"><br>
  <div class="w3-container w3-row">
  <img src="${path}/image/logo.png"
      class="w3-circle w3-margin-right" 
      style="width:100px;">
  <div class="w3-row">&nbsp;</div>
  <div class="w3-row">
      <c:if test="${!empty sessionScope.loginUser}">
      <span>반갑습니다. <strong>${sessionScope.loginUser.username }님</strong></span>
      </c:if>
      <c:if test="${empty sessionScope.loginUser}">
      <span><strong>로그인하세요</strong></span>
      </c:if>
      <br>
    </div>
  </div>
  <hr>
  <div class="w3-bar-block">
    <a href="#" class="w3-bar-item w3-button w3-padding-16 w3-hide-large w3-dark-grey w3-hover-black" onclick="w3_close()" title="close menu"><i class="fa fa-remove fa-fw"></i>&nbsp; Close Menu</a>
    <a href="${path}/user/mypage?id=${loginUser.userid}" class="w3-bar-item w3-button w3-padding"><i class="fa fa-eye fa-fw"></i>&nbsp; 회원관리</a>
    <a href="${path}/item/list" class="w3-bar-item w3-button w3-padding"><i class="fa fa-eye fa-fw"></i>&nbsp; 상품관리</a>
    <hr>
    <a href="${path}/board/list?boardid=1" class="w3-bar-item w3-button w3-padding"><i class="fa fa-users fa-fw"></i>&nbsp;공지사항</a>
    <a href="${path}/board/list?boardid=2" class="w3-bar-item w3-button w3-padding"><i class="fa fa-users fa-fw"></i>&nbsp;자유게시판</a>
    <a href="${path}/board/list?boardid=3" class="w3-bar-item w3-button w3-padding"><i class="fa fa-users fa-fw"></i>&nbsp;QNA</a>
  </div>
</nav>
<div class="w3-overlay w3-hide-large w3-animate-opacity" onclick="w3_close()" style="cursor:pointer" title="close side menu" id="myOverlay"></div>
<!-- !PAGE CONTENT! -->
<div class="w3-main" 
  style="margin-left:200px;margin-top:43px; margin-right: 20px;">
  <div class="w3-row-padding w3-margin-bottom">
  <div class="w3-container w3-light-grey w3-padding-32">
    <div class="w3-row">
      <div class="w3-container w3-col" style="width:95%;">
        <sitemesh:write property='body'/>
      </div>
      <div class="w3-container w3-col" style="width:5%;">
        <p>&nbsp;</p>
      </div>
    </div>
  </div>
  </div>
  <!-- End page content -->
</div>
<br>

<%-- 시군구 선택 --%>
<div style="margin-left:200px;">
	<span id="si">
		<select name="si" onchange="getText('si')">
			<option value="">시도를 선택하세요.</option>
		</select>
	</span>
	<span id="gu">
		<select name="gu" onchange="getText('gu')">
			<option value="">구군를 선택하세요.</option>
		</select>
	</span>
	<span id="dong">
		<select name="dong" onchange="getText('dong')">
			<option value="">동리를 선택하세요.</option>
		</select>
	</span>
</div>

<script>
// Get the Sidebar
var mySidebar = document.getElementById("mySidebar");

// Get the DIV with overlay effect
var overlayBg = document.getElementById("myOverlay");

// Toggle between showing and hiding the sidebar, and add overlay effect
function w3_open() {
  if (mySidebar.style.display === 'block') {
    mySidebar.style.display = 'none';
    overlayBg.style.display = "none";
  } else {
    mySidebar.style.display = 'block';
    overlayBg.style.display = "block";
  }
}

// Close the sidebar with the close button
function w3_close() {
  mySidebar.style.display = "none";
  overlayBg.style.display = "none";
}

$(function() {
	let divid;
	let si;
	$.ajax({
		url : "${path}/ajax/select",
		success : function(data) {
//			console.log(data)
			let arr = data.substring(data.indexOf('[') + 1, data.indexOf(']')).split(",");
			$.each(arr,function(i, item) {
				$("select[name='si']").append(function() {
					return "<option>" + item + "</option>"
				})
			});
		}
	})
})

function getText(name) {
		let cityval = $("select[name='si']").val();
		let guval = $("select[name='gu']").val();
		let disname;
		let toptext="구군을 선택하세요.";
		let params = "";
		if (name =="si") {
			params = "si=" + cityval.trim();
			disname = "gu"; //결과값이 출력 될 영역
		} else if (name == "gu") {
			// si = 서울특별수 & gu = 강남구
			params = "si=" + cityval.trim() + "&gu=" + guval.trim();
			disname = "dong";
			toptext = "동리를 선택하세요."
		} else {
			return;
		}
		$.ajax({
			url : "${path}/ajax/select",
			type : "POST",
			data : params,
			success : function(data) {
				let arr = data.substring(data.indexOf('[')+1,data.indexOf(']')).split(",");
				let selhtml = "<select name='" + disname + "' onchange='getText(\"" + disname + "\")'>";
				selhtml += "<option value=''>" + toptext + "</option>"
				$.each(arr,function(i,item){
					selhtml += "<option>" + item + "</option>"
				});
				selhtml += "</select>";
				$("#" + disname).html(selhtml);
			}
		})
	}

</script>
</body></html>

AjaxController.java

package controller;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import logic.ShopService;
import logic.User;
/*
 * @Controller : @Component(객체화) + 요청을 받아주는 클래스
 * 		메서드 리턴타입 : String => 뷰의 이름 리턴
 * 		메서드 리턴타입 : ModelAndView => 뷰의 전달할 객체 + 뷰의 이름 리턴
 * 
 * @RestController : @Component(객체화) + 요청을 받아주는 클래스 + 클라이언트(브라우저)에 값을 뷰가 아닌 직접 전달
 * 		메서드 리턴타입 : String => 값 : 이전버전 @ResponseBody 기능
 * 		메서드 리턴타입 : Object => 값
 */
@RestController
@RequestMapping("ajax")
public class AjaxController {
	@Autowired
	ShopService service;
	
	@RequestMapping("idchk")
	public String idchk (String userid) {
		String chk = null;
		User user = service.userSelectOne(userid);
		if (user == null) chk = "false"; //등록된 회원이 없는 경우
		else chk = "true";
		return chk;
	}
	//produces : 클라이언트에 한글 인코딩 방식 설정
	//text/plain : 순수 문자열 (MIME 형식 : )
	@RequestMapping(value="select", produces="text/plain; charset=utf-8")
	public String select (String si, String gu, HttpServletRequest request) {
		BufferedReader fr = null;
		try {
			fr = new BufferedReader(new FileReader(request.getServletContext().getRealPath("/") + "file/sido.txt"));
		} catch (FileNotFoundException e1) {
			e1.printStackTrace();
		}
		Set<String> set = new LinkedHashSet<>(); //순서 유지 + 중복불가 가능한 Set객체
		String data = null;
		if (si == null && gu == null) {
			try {
				while ((data = fr.readLine()) != null) {
					String[] arr = data.split("\\s+");
					if(arr.length >= 3) set.add(arr[0].trim());
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		} else if (gu == null) { //si 파라미터 존재
			si = si.trim();
			try {
				while ((data = fr.readLine()) != null) {
					String[] arr = data.split("\\s+");
					if(arr.length >= 3 && arr[0].equals(si) && !arr[0].equals(arr[1])) {
						set.add(arr[1].trim());
					}
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		} else { //si 파라미터 존재, gu 파라미터 존재
			si = si.trim();
			gu = gu.trim();
			try {
				while ((data = fr.readLine()) != null) {
					String[] arr = data.split("\\s+");
					if(arr.length >= 3 && arr[0].trim().equals(si) && arr[1].trim().equals(gu) && !arr[1].equals(arr[2])) {
						if(arr.length > 3) arr[2] += " " + arr[3];
						set.add(arr[2].trim());
					}
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		List<String> list = new ArrayList(set);
		return list.toString();
	}
}

sido.txt
0.72MB

728x90
반응형