본문 바로가기
☁︎KOSTA/☂KOSTA-SPRING

4[KOSTA] Spring 기반 Cloud 서비스 구현 개발자 양성 (Day 87) - SpringBoot(Cont.) - Ajax, Final Project 준비

by 하_센세 2022. 12. 6.

2022.12.06 [TUE]

- Day 87- 

 

수업 주요 목차

  • SpringBoot(Cont.) - Ajax
  • Final Project 준비

 

🔎 Eclipse 실습 내용

 

1. Ajax basic

  • index.html 에 추가된 코드
<a href="ajaxTestView">Ajax Test</a>
  • MyAjaxTestController.java
package org.kosta.myproject.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class MyAjaxTestController {
	@RequestMapping("ajaxTestView")
	public String ajaxTestView(Model model) {
		model.addAttribute("message", "Spring Ajax Test");
		return "ajax-test"; //view name 리턴
	}
	
	@RequestMapping("testAjax1")
	@ResponseBody
	public String testAjax1(String id) {
		System.out.println("ajax 요청에 대한 응답: id="+id);
		return "ajax 응답 "+ id;
	}
		
}

@ResponseBody : ajax 응답을 위한 spring mvc 어노테이션 : view name에 의한 페이지 응답이 아니라 필요한 데이터로 응답

(return은 view name이 아니라 응답할 데이터를 return한다.)

  • ajax-test.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
  <title>spring boot project</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css">
  <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.slim.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/js/bootstrap.bundle.min.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
<div class="container pt-3">
<h4>Spring Ajax Test</h4>
<br><br>
<h4 th:text="${mesage}">메세지</h4>
<br><br>
<button type="button" id="ajaxTestBtn1">Ajax Test 1</button>
</div>
<script type="text/javascript">
	$(function(){
		$("#ajaxTestBtn1").click(function() {
			//alert("클릭크!");
			$.ajax({
				type:"get",
				url:"testAjax1",
				data:"id=javaking",
				success:function(result){
					alert(result);
				}//success
			});//ajax
		});//click
	});//ready
</script>
</body>
</html>


 

 

2. 

  • ajax-test.html 에 추가된 코드
<!-- ajax 방식으로 통신: Customer 정보를 JSON객체로 응답 jackson data bind 기술-->
<button type="button" id="ajaxTestBtn2">Ajax Test 2</button><br><br>
<!-- ajax 방식으로 통신: Customer List 를 JSON Array로 응답 jackson data bind 기술-->
<button type="button" id="ajaxTestBtn3">Ajax Test 3</button><br><br>
<script type="text/javascript">
	$(function(){
		$("#ajaxTestBtn2").click(function() {
			//spring controller부터 JSON Object(customer정보)를 결과로 응답받는다.
			$.ajax({
				type:"get",
				url:"testAjax2",
				data:"id=love",
				success:function(customer){
					alert(customer.id);
					alert(customer.name);
					alert(customer.address);
				}//success
			});//ajax
		});//click
		//spring controller로부터 json array(customer list 정보)를 결과로 응답받는다.
		$("#ajaxTestBtn3").click(function() {
			$.ajax({
				type:"get",
				url:"testAjax3",
				data:"address=도하",
				success:function(list){
					for(let i=0;i<list.length;i++){
						alert("아이디: "+list[i].id+" 이름: "+list[i].name);
					}//방법1
					
					Object.keys(list).forEach(function(i){
						alert('아이디: '+list[i].id+' 이름: '+list[i].name);
					})//방법2
					
					for(var i in list){
						alert('아이디: '+list[i].id+' 이름: '+list[i].name);
					}//방법3
					
				}//success
			});//ajax
		});//click
	});//ready
</script>
  • MyAjaxTestController.java에 추가된 코드
@RequestMapping("testAjax2")
@ResponseBody // spring controller가 ajax응답을 위해 사용: 응답할 데이터를 반환(페이지가 아님)
public CustomerVO testAjax2(String id) {
	System.out.println("ajax 요청에 대한 응답: id="+id);
	CustomerVO customerVO=customerMapper.findCustomerById(id);
	System.out.println(customerVO);
	return customerVO; //JSONObject로 만들지 않아도 SpringBoot Jackson dependency이 자동적으로 data bind 기술에 의해 JSONObject로 응답한다.
}
	
@RequestMapping("testAjax3")
@ResponseBody
public ArrayList<CustomerVO> testAjax3(String address){
	ArrayList<CustomerVO> list=customerMapper.findCustomerListByAddress(address);
	System.out.println(list.size());
	return list;		
}


3. Session

  • index.html 에 추가된 코드
<!--/*
	MyAjaxTestController에서 테스트
	컨트롤러에서 매개변수로 session만 전달
 */-->
 <a href="sessionTest0">Login 관련 session Test</a>
  <br><br>
<!--/*
	MyAjaxTestController에서 테스트
	컨트롤러에서 매개변수로 session을 전달 받고 session에 customerVO할 처리
 */-->
 <a href="sessionTest">Login 관련 session, VO Test</a>
 <br><br>
<!--/*
	MyAjaxTestController에서 테스트
	컨트롤러에서 매개변수로 request를 전달받아 세션 존재 유무와 인증정보를 확인(request.getSession(false)를 이용해 확인)
 */-->
 <a href="sessionTest2">Login 여부 확인관련 session Test</a>
  • Controller에 추가된 코드
@RequestMapping("sessionTest0")
//HandlerAdapter가 Session이 존재하지 않으면 새로 생성해서 전달, 기존 session이 있으면 기존 session 전달
public String sessionTest0(HttpSession session) {
	System.out.println("session 객체를 전달받을 수 있다 ->" + session);
	return "result9"; //view name
}
	
@RequestMapping("sessionTest")
//HandlerAdapter가 Session이 존재하지 않으면 새로 생성해서 전달, 기존 session이 있으면 기존 session 전달하고 VO 할당
public String sessionTest(HttpSession session) {
	System.out.println("session 객체를 전달받을 수 있다 ->" + session);
	session.setAttribute("customerVO", new CustomerVO("java","아이유","오리"));
	return "result9"; //view name
}
	
@RequestMapping("sessionTest2")
public String sessionTest2(HttpServletRequest request, Model model) {
	HttpSession session=request.getSession(false); // 기존 세션이 없으면 null을 반환
	String checkMessage=null;
	if(session==null) {
		checkMessage="session이 존재하지 않습니다";
	} else if(session.getAttribute("customerVO")==null) {
		checkMessage="인증정보가 존재하지 않습니다";
	} else if(session!=null&&session.getAttribute("customerVO")!=null) {
		checkMessage="로그인 상태입니다";
	}
	model.addAttribute("checkMessage",checkMessage);
	return "result9-2";//view name
}
  • result9.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
  <title>spring boot project</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css">
  <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.slim.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/js/bootstrap.bundle.min.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
<div class="container pt-3">
<!-- html 주석 -->
<!--/*   
          thymeleaf 주석
          Spring Boot에서 추천하는 템플릿 엔진 타임리프는 
          src/main/resources/templates 아래에 html 확장자로 개발한다 
          th:block th:if =? thymeleaf 조건문: 다음 프로젝트에서 공부 예정
*/-->
result9 Sesssion Test<br><br>
<th:block th:if="${session.customerVO!=null}">
<span th:text="${session.customerVO.name}">고객명</span>님 로그인
</th:block>
</div>
</body>
</html>

 

  • result9-2.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
  <title>spring boot project</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css">
  <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.slim.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/js/bootstrap.bundle.min.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
<div class="container pt-3">
<!-- html 주석 -->
<!--/*   
          thymeleaf 주석
          Spring Boot에서 추천하는 템플릿 엔진 타임리프는 
          src/main/resources/templates 아래에 html 확장자로 개발한다 
*/-->
<span th:text="${checkMessage}">message</span>
</div>
</body>
</html>

 


Login 여부 확인관련 링크 클릭시

Login 여부 확인관련 링크 클릭시

Login 여부 확인관련 링크 클릭시

Login 여부 확인관련 링크 클릭시

 

 

4. SpringBoot Thymeleaf layout - Dialect

  • index.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<title>Thymeleaf study home</title>
</head>
<body>
<!-- html 주석 -->
<!--/*   thymeleaf 주석     */-->
Hello <span th:text="${message}">타임리프</span> 
<br><br>
<img src="../static/images/thymeleaf.png" th:src="@{/images/}+${logo}"><br>
</body>
</html>

🧚‍♂️ 정적 자원 ( image , css , js 등 ) 은 src/main/resources/static 에 배치한다.
🧚‍♂️ img src 상에서 컨트롤러가 공유한 이미지 정보 변수를 이용해 화면에 이미지를 제공하는데 이 때 th:src="@{}" 을 이용해야 한다 

  • HomeController
package org.kosta.myproject.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class HomeController {
	@RequestMapping("/")
	public String home(Model model) {
		model.addAttribute("message","안녕 백리향");
		model.addAttribute("logo", "thymeleaf.png"); // 공적으로 변화될 수 있는 이미지 정보
		return "index";
	}
}

  • application.properties
#Context Path 웹어플리케이션 경로 설정
server.servlet.context-path=/kokoabank

http://localhost:7777/ 로 접근시 아래와 같은 404 에러가 뜬다. 경로 설정을 /kokoabank로 해주었기 때문!

http://localhost:7777/kokoabank/ 로 접근하면 아래와 같이 뜬다!

 

 

//오늘의 숙제

복습