포스코DX X 비트교육센터 6기 - AJAX


실습

  • RestAPiTestController.java
package ch08.controller.test;

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

@Controller
public class RestApiTestController {

	@RequestMapping("/test/rest")
	public String test() {
		return "rest-test";
	}
}

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

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

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

<%@ 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 src="${pageContext.request.contextPath }/jquery/jquery-3.7.1.js"></script>

<script>
	$(function() {

		$('#create').click(function() {

			var vo = {
				name : '둘리',
				email : 'dooly@gmail.com',
				password : '1234',
				gender : 'male'
			}
			$.ajax({

				url : '${pageContext.request.contextPath }/api/user',

				type : 'post',

				dataType : 'json',

				contentType : 'application/json',

				data : JSON.stringify(vo),

				success : function(response) {

					console.log(response);
				},

			});

		});
		$('#read').click(function() {

			$.ajax({

				url : '${pageContext.request.contextPath }/api/user',

				type : 'get',

				dataType : 'json',

				success : function(response) {

					console.log(response);
				},

			});

		});
		$('#update').click(function() {
	         var vo = {
	            name : '둘리',
	            passwrod : '123456789',
	            gender : 'male'
	         }
	         $.ajax({
	            url : '${pageContext.request.contextPath}/api/user/10',
	            type : 'put',
	            dataType : 'json',
	            contentType: 'application/json',
	            data: JSON.stringify(vo),
	            success : function(response) {
	               console.log(response);
	            }
	         });
	      });
		$('#delete').click(function() {

			$.ajax({

				url : '${pageContext.request.contextPath }/api/user/10',

				type : 'delete',

				dataType : 'json',

				contentType : 'application/x-www-form-urlencoded',

				data: "password=12345",

				success : function(response) {

					console.log(response);
				},

			});

		});

	});
</script>

</head>

<body>

	<h1>AJAX Test: Restful API</h1>

	<button id='create'>[C]reate(post)</button>
	<br>
	<br>
	<button id='read'>[R]ead(get)</button>
	<br>
	<br>
	<button id='update'>[U]pdate(put)</button>
	<br>
	<br>
	<button id='delete'>[D]elete(delete)</button>
	<br>
	<br>

</body>

</html>
  • ApiRestController.java
package ch08.controller.api;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import ch08.dto.JsonResult;
import ch08.vo.UserVo;

@RestController
@RequestMapping("/api/user")
public class ApiRestController {

	@PostMapping
	public JsonResult create(@RequestBody UserVo vo) {
		vo.setNo(1L);
		vo.setPassword("");

		return JsonResult.success(vo);
	}
	
	@GetMapping
	public JsonResult read() {
		List<UserVo> list = new ArrayList<>();
		
		UserVo vo1 = new UserVo();
		vo1.setNo(1L);
		vo1.setName("둘리");
		vo1.setEmail("dooly@gmail.com");
		list.add(vo1);

		UserVo vo2 = new UserVo();
		vo2.setNo(2L);
		vo2.setName("마이콜");
		vo2.setEmail("michol@gmail.com");
		list.add(vo2);
		
		return JsonResult.success(list);
	}
	
	@PutMapping("{no}")
	public JsonResult update(@PathVariable("no") Long no, @RequestBody UserVo vo) {
		vo.setNo(no);
		vo.setPassword("");
		
		return JsonResult.success(vo);
	}
	
	@DeleteMapping("{no}")
	public JsonResult delete(@PathVariable("no") Long no, @RequestParam(value="password", required=true, defaultValue="") String password) {
		System.out.println("password: "+password);
		return JsonResult.success(no);
		
		
	}
}

image

server.xml : delete시, body 전송이 안될 때

image

  • parseBodyMethods 추가
<Connector connectionTimeout="20000" maxParameterCount="1000" port="8080" protocol="HTTP/1.1" parseBodyMethods="POST, PUT, DELETE" redirectPort="8443"/>
  

password: 이렇게 나왔었는데, body의 내용이 붙어 나오게 됨.

image


mysite06 실습

image

  • 데이터가 없는 경우, data : null 로 나옴.

image