SPRING email 전송

https://mvnrepository.com/ - spring context support 검색 - 첫번째 클릭 

- 아무버전 클릭 - maven 내용 복사 - pom.xml 붙여넣기(${org.springframework-version})

 

https://mvnrepository.com/ - javax 검색 - 첫번째 클릭 

- 1.5.4 버전 클릭 - maven 내용 복사 - pom.xml 붙여넣기

 

https://mvnrepository.com/ - javax 검색 - 세번째 클릭 

- 1.5.3 버전 클릭 - maven 내용 복사 - pom.xml 붙여넣기

 

* google 로그인 - 계정 관리 - 보안 - 2단계 인증 완료  

 

config관련 mail클래스 생성 - 

 

mailController 생성 - 

 

mail Service 생성 - 

 

https://myaccount.google.com/apppasswords - 계정 입력 - 받은 비밀번호 복사 

- config 파일의 .setPassword("붙여넣기")

 

* StringBuffer : 해당 객체는 지우고 새롭게 만드는 것이 아니라, 계속 유지된다.

 

* .setText(body, true) : 텍스트 형식 말고 html형식으로 보내는 방법

 

실행 결과

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

SPRING email 인증

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

	<c:if test="${ userId == null }">
		<form action="auth">
			<input type="text" name="email"><br>
			<input type="submit" value="이메일 인증">
		</form>
	</c:if>
	<c:if test="${ userId != null }">
		<h3>${userId }님 이메일 인증되었음!!</h3>	
	</c:if>
</body>
</html>
package com.care.root.controller;

import java.io.PrintWriter;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.care.root.service.MailServiceImpl;

@Controller
public class MailController {
	@Autowired MailServiceImpl ms;
	@GetMapping("sendmail")
	public void sendMail(HttpServletRequest req,
					HttpServletResponse res) throws Exception{
		req.setCharacterEncoding("utf-8");
		res.setContentType("text/html; charset=utf-8");
		PrintWriter out = res.getWriter();
		
		ms.sendMail("xodud5080@gmail.com", "제목 : 테스트", "내용 : 안녕");
		
		out.print("메일을 보냈습니다");
	}
	
	@GetMapping("sendmail02")
	public void sendMail02(HttpServletRequest req,
			HttpServletResponse res) throws Exception{
		req.setCharacterEncoding("utf-8");
		res.setContentType("text/html; charset=utf-8");
		PrintWriter out = res.getWriter();
		
		StringBuffer body = new StringBuffer();
		body.append("<html><body>");
		body.append("<h1>제품 소개</h1>");
		body.append("<a href='https://www.naver.com/'>");
		body.append("<img alt='' src='https://search.pstatic.net/common/?src=http%3A%2F%2Fblogfiles.naver.net%2FMjAyNDAxMDRfMjMw%2FMDAxNzA0MzczODA3MTcz.SA2hQyKDRrje6lKrEnljRYPIsiByFlwzXv9fc5clJ9cg.qP2m0LDx9XqYJSJX5hrL73baolQe-8cwpsJr3fF4D40g.JPEG.uiuiui2200%2FIMG_9283.jpg&type=a340'>");
		body.append("</a>");
		body.append("</body></html>");
		
		ms.sendMail02("xodud5080@gmail.com", "제목 : 푸바오", body.toString());
		
		out.print("메일을 보냈습니다");
	}
	
	@GetMapping("auth_form")
	public String authForm() {
		return "auth";
	}
	
	@GetMapping("auth")
	public String auth(HttpServletRequest req) {
		ms.auth(req);
		return "redirect:http://www.google.com";
	}
	@GetMapping("auth_check")
	public String authCheck(@RequestParam String userId, 
					HttpSession session) {
		String userKey = (String)session.getAttribute("xodud5080@gmail.com");
		if (userKey.equals(userId)) {
			session.setAttribute("userId", "xodud5080");
			System.out.println("userId : " + session.getAttribute("userId"));
		}
		return "redirect:auth_form";
	}
}
package com.care.root.service;

import java.util.Random;

import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

@Service
public class MailServiceImpl {

	@Autowired JavaMailSender sender;
	public void sendMail(String to, String subject, String body) {
		MimeMessage messasge = sender.createMimeMessage(); // 보내는 형식 지정
		try {
			MimeMessageHelper h = new MimeMessageHelper(messasge, true, "UTF-8");
			// true = multipart로 사용하겠다는 의미
			h.setSubject(subject);
			h.setTo(to);
			h.setText(body);
			sender.send(messasge); // 메일 전송
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void sendMail02(String to, String subject, String body) {
		MimeMessage messasge = sender.createMimeMessage(); // 보내는 형식 지정
		try {
			MimeMessageHelper h = new MimeMessageHelper(messasge, true, "UTF-8");
			// true = multipart로 사용하겠다는 의미
			h.setSubject(subject);
			h.setTo(to);
			h.setText(body, true); // 텍스트 형식이 아니라고 명시
			sender.send(messasge); // 메일 전송
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private String rand() {
		Random ran = new Random();
		String str = "";
		int num;
		while(str.length() != 20) {
			num = ran.nextInt(75) + 48; // (0 ~ 75) + 48 = 48 ~ 122
			if ((num >= 48 && num <= 57) || (num >= 65 && num <= 90) || (num >= 97 && num <= 122)) {
				str += (char)num;
			}
		}
		return str;
	}
	public void auth(HttpServletRequest req) {
		HttpSession session = req.getSession();
		String userId = req.getParameter("email");
		String userKey = rand();
		session.setAttribute(userId, userKey);
		System.out.println("userId1 : " + session.getAttribute(userId));
		String body = "<h3>이메일 인증</h3>"
					+ "<a href='http://localhost:8080/root/auth_check?userId="+userKey+"'>인증하기</a>";
		sendMail02(userId, "이메일 인증", body);
	}
}

 

실행 결과

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

SPRING scheduler

scheduler : 지정한 시간대가 되면 동작하게 하는 것(예약)

scheduler 관련  config  클래스 생성

* @EnableScheduling, @Scheduled(cron = "시간 설정") 작성 

 

실행 결과

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

SPRING ajax (데이터 주고 받기)

ajax를 사용 안할 때

 

ajax를 사용 할 때

ajax 쓰는 이유 : 페이지를 새로고침 하지 않아, 처리속도가 더 빠르다

* <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script> : jquery 라이브러리 가져오기

@ResponseBody : return에 값을 명시해도, jsp파일을 찾아가지 않고 데이터를 돌려준다

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

SPRING data 전송 방식(json)

https://mvnrepository.com/ - jackson databind 검색 - 첫번째 클릭 

- 2.9.5 버전 클릭 - maven 내용 복사 - pom.xml 붙여넣기

JSON.stringify("데이터") : 해당 데이터를 json형식으로 변환

보내는 방식(type) : contentType

받는 방식(type) : dataType

* json형식으로 넘어오는 값은 @RequestBody형식으로 받는다

<%@ 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="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script type="text/javascript">
	function test() {
		let n = document.getElementById("name").value;
		let a = $("#age").val();
		let form = {name : n, age : a};
		$.ajax({
			url : "result03", type : "post",
			data : JSON.stringify(form), 
			dataType : "json",
			contentType : "application/json; charset=utf-8",
			success : (result) => {
				console.log(result);
				$("#result").html("name : " + result.name+ ", age : " + result.age)
			},
			error : () => {
				console.log("문제 발생!!!");
			}
		})
	}
</script>
</head>
<body>
	<input type="text" id="name"><br>
	<input type="text" id="age"><br>
	<input type="button" value="click" onclick="test()"><br>
	결과 : <span id="result"></span>
</body>
</html>
package com.care.root;

import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
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;

/**
 * Handles requests for the application home page.
 */
@Controller
public class HomeController {
	
	private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
	
	/**
	 * Simply selects the home view to render by returning its name.
	 */
	@RequestMapping(value = "/", method = RequestMethod.GET)
	public String home(Locale locale, Model model) {
		logger.info("Welcome home! The client locale is {}.", locale);
		
		Date date = new Date();
		DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
		
		String formattedDate = dateFormat.format(date);
		
		model.addAttribute("serverTime", formattedDate );
		
		return "home";
	}
	
	@GetMapping("ajax03")
	public String ajax03() {
		System.out.println("ajax03");
		return "ajax03";
	}
	
	@PostMapping(value = "result03", produces = "application/json; charset=utf-8")
	@ResponseBody
	public InfoDTO result03(@RequestBody InfoDTO dto) {
		System.out.println("result03");
		System.out.println("dto.name" + dto.getName());
		System.out.println("dto.age" + dto.getAge());
//		System.out.println("map.name" + map.get("name"));
//		System.out.println("map.age" + map.get("age"));
		
		return dto;
	}
}

 

실행 결과

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

SPRING RestController

@RestController : jsp페이지 대신, data를 return으로 돌려주는 controller이다

* @ResponseBody를 쓸 필요가 없어진다.

<%@ 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="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script type="text/javascript">
	function getFunc() {
		$.ajax({
			url : "rest", type : "get", dataType : "json", 
			success : function (result) {
				$("#span").html(result.result);
			}, error : function () {
				alert("문제 발생!!!");
			}
		})
	}
	
	function postFunc() {
		$.ajax({
			url : "rest", type : "post", dataType : "json", 
			success : function (result) {
				$("#span").html(result.result);
			}, error : function () {
				alert("문제 발생!!!");
			}
		})
	}
	
	function putFunc() {
		$.ajax({
			url : "rest", type : "put", dataType : "json", 
			success : function (result) {
				$("#span").html(result.result);
			}, error : function () {
				alert("문제 발생!!!");
			}
		})
	}
	
	function deleteFunc() {
		$.ajax({
			url : "rest", type : "delete", dataType : "json", 
			success : function (result) {
				$("#span").html(result.result);
			}, error : function () {
				alert("문제 발생!!!");
			}
		})
	}
	
</script>
</head>
<body>
	<span id="span"></span><hr>
	<button type="button" onclick="getFunc()">get 요청</button>
	<button type="button" onclick="postFunc()">post 요청</button>
	<button type="button" onclick="putFunc()">put 요청</button>
	<button type="button" onclick="deleteFunc()">delete 요청</button>
</body>
</html>
package com.care.root;

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

import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController {
	
	@GetMapping(value="rest", produces = "application/json; charset=utf-8")
	public Map<String, Object> get() {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("result", "get : 데이터 요청");
		return map;
	}
	
	@PostMapping(value="rest", produces = "application/json; charset=utf-8")
	public Map<String, Object> post() {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("result", "post : 데이터 추가");
		return map;
	}
	
	@PutMapping(value="rest", produces = "application/json; charset=utf-8")
	public Map<String, Object> put() {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("result", "put : 데이터 수정");
		return map;
	}
	
	@DeleteMapping(value="rest", produces = "application/json; charset=utf-8")
	public Map<String, Object> delete() {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("result", "delete : 데이터 삭제");
		return map;
	}
}

 

실행 결과

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

SPRING SPA

SPA : 브라우저를 최초에 한번 로드하고, 이후부터는 특정 부분만 ajax를 통해 바인딩하는 방식

* 경로로 전송한 값은, controller에서 {}로 받고, 해당 클래스에서는 @ParhVariable로 받는다

<%@ 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>
	<h1>안녕 페이지</h1>
	<hr>
		<a href="index">HOME</a>
		<span style="cursor: pointer;" onclick="members()">MEMBERS</span>
	<hr>
</body>
</html>
<%@ 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="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script type="text/javascript">
	function members() {
		$.ajax({
			url : "members", type : "get", dataType : "json", 
			success : (list) => {
				console.log(list);
				console.log(list[0].id);
				let msg = "<table border='1'>";
				msg += "<tr><th>id</th><th>name</th><th>age</th></tr>"
				for(let i = 0; i < list.length; i++){
					msg += "<tr>";
					msg += "<td>" + list[i].id + "</td>";
					msg += "<td onclick='getMember(\"" + list[i].id + "\")'>" + list[i].name + "</td>";
					msg += "<td>" + list[i].age + "</td>";
					msg += "</tr>";
				}
				msg += "</table>";
				$("#content").html(msg);
			}
		});
	}
	function getMember(userId) {
		console.log(userId)
		$.ajax({
			url : "members/"+userId, type : "get", dataType : "json",
			success : (member) => {
				console.log(member);
				let msg = "id : " + member.id + "<br>";
				msg += "name : " + member.name + "<br>";
				msg += "age : " + member.age + "<br>";
				$("#content").html(msg);
			}
		});
	}
</script>
</head>
<body>	
	<%@ include file="header.jsp" %>
	<div id="content">
		<h3>기본 페이지 입니다 </h3>
	</div>
</body>
</html>
package com.care.root;

import java.util.ArrayList;

import org.springframework.stereotype.Component;

@Component
public class DBClass {
	ArrayList<InfoDTO> DB;
	public DBClass() {
		DB = new ArrayList<InfoDTO>();
		for (int i = 0; i < 3; i++) {
			InfoDTO dto = new InfoDTO();
			dto.setId("aaa" + i);
			dto.setName("홍길동" + i);
			dto.setAge(10+i);
			DB.add(dto);
		}
	}
}
package com.care.root;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
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.RestController;

@RestController
public class TestController {
	
	@Autowired DBClass db;
	
	@GetMapping(value="members", produces = "application/json; charset=utf-8")
	public ArrayList<InfoDTO> members() {
		return db.DB;
	}
	
	@GetMapping(value="members/{uId}", produces = "application/json; charset=utf-8")
	public InfoDTO getMember(@PathVariable String uId) {
		//System.out.println("Asdfasd");
		for(InfoDTO d : db.DB) {
			System.out.println(d.getId().equals(uId));
			if (d.getId().equals(uId)) {
				System.out.println(d.getId());
				System.out.println(d.getName());
				return d;
			}
		}
		return null;
	}
}

 

실행 결과

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

SPRING SPA 활용

* serializeArray() : name을 키로 만들어서, 배열 형식으로 만들어준다

<%@ 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="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script type="text/javascript">
	function members() {
		$.ajax({
			url : "members", type : "get", dataType : "json", 
			success : (list) => {
				console.log(list);
				console.log(list[0].id);
				let msg = "<table border='1'>";
				msg += "<tr><th>id</th><th>name</th><th>age</th></tr>"
				for(let i = 0; i < list.length; i++){
					msg += "<tr>";
					msg += "<td>" + list[i].id + "</td>";
					msg += "<td onclick='getMember(\"" + list[i].id + "\")'>" + list[i].name + "</td>";
					msg += "<td>" + list[i].age + "</td>";
					msg += "</tr>";
				}
				msg += "</table>";
				$("#content").html(msg);
			}
		});
	}
	function getMember(userId) {
		console.log(userId)
		$.ajax({
			url : "members/"+userId, type : "get", dataType : "json",
			success : (member) => {
				console.log(member);
				let msg = "id : " + member.id + "<br>";
				msg += "name : " + member.name + "<br>";
				msg += "age : " + member.age + "<br>";
				msg += "<span onclick='del(\"" + member.id + "\")'>삭제</span>"
				msg += "<span onclick='modify_form(\"" + member.id + "\")'>수정</span>"
				$("#content").html(msg);
			}
		});
	}
	function del(userId) {
		$.ajax({
			url : "delete?id="+userId, type : "delete", 
			dataType : "json", 
			success : function (result) {
				if (result == 1) {
					alert("삭제 성공");
					members();
				}else{
					alert("문제 발생!!!");
				}
			}
		})
	}
	function modify_form(userId) {
		$.ajax({
			url : "members/"+userId, type : "get", dataType : "json",
			success : (member) => {
				let msg = '<form id="mo">';
				msg += '<input type="text" value="'+member.id+'" name="id" ><br>';
				msg += '<input type="text" value="'+member.name+'" name="name" ><br>';
				msg += '<input type="text" value="'+member.age+'"name="age" ><br>';
				msg += '<input type="button" onclick="modify()" value="수정"><br>';
				msg += '</form>';
				$("#content").html(msg);
			}
		});
	}
	function modify() {
		let form = {}
		let arr = $("#mo").serializeArray();
		console.log(arr);
		for(let i = 0; i < arr.length; i++){
			form[arr[i].name] = arr[i].value;
		}
		console.log(form);
		$.ajax({
			url : "modify", type : "put", dataType : "json",
			data : JSON.stringify(form),
			contentType : "application/json; charset=utf-8",
			success : function (result) {
				if (result == 1) {
					alert("수정 성공");
					getMembers(form.id);
				}
			}
		});
	}
	function checkId() {
		console.log($("#id").val());
		if ($("#id").val().length < 3) {
			$("#id_chk").html("길이가 짧습니다!!!!");
			return;
		}
		$.ajax({
			url : "idChk/"+$("#id").val(), type : "get", 
			dataType : "json", 
			success : function (data) {
				if (data == 0) {
					$("#id_chk").html("사용 가능한 아이디 입니다");
				}else{
					$("#id_chk").html("존재하는 아이디입니다!!")
				}
			}
		})
	}
	function register() {
		let msg = '<form id="fo">';
		msg += '<input type="text" id="id" name="id" oninput="checkId()" placeholder="id"><br>';
		msg += '<span id="id_chk">아이디 확인</span><br>'
		msg += '<input type="text" name="name" placeholder="name"><br>';
		msg += '<input type="text" name="age" placeholder="age"><br>';
		msg += '<input type="button" onclick="reg()" value="가입"><br>';
		msg += '</form>';
		$("#content").html(msg);
	}
	function reg() {
		//alert("가입 클릭");
		let form = {}
		let arr = $("#fo").serializeArray();
		console.log(arr);
		for(let i = 0; i < arr.length; i++){
			form[arr[i].name] = arr[i].value;
		}
		console.log(form);
		$.ajax({
			url : "register", type : "post", dataType : "json",
			data : JSON.stringify(form),
			contentType : "application/json; charset=utf-8",
			success : function (result) {
				if (result.num == 1) {
					alert("저장 성공");
					members();
				}
			}
		});
	}
</script>
</head>
<body>	

	<%@ include file="header.jsp" %>
	<div id="content">
		<h3>기본 페이지 입니다 </h3>
	</div>
</body>
</html>
package com.care.root;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
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.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import oracle.jdbc.proxy.annotation.Post;

@RestController
public class TestController {
	
	@GetMapping(value="rest", produces = "application/json; charset=utf-8")
	public Map<String, Object> get() {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("result", "get : 데이터 요청");
		return map;
	}
	
	@PostMapping(value="rest", produces = "application/json; charset=utf-8")
	public Map<String, Object> post() {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("result", "post : 데이터 추가");
		return map;
	}
	
	@PutMapping(value="rest", produces = "application/json; charset=utf-8")
	public Map<String, Object> put() {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("result", "put : 데이터 수정");
		return map;
	}
	
	@DeleteMapping(value="rest", produces = "application/json; charset=utf-8")
	public Map<String, Object> delete() {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("result", "delete : 데이터 삭제");
		return map;
	}
	
	@Autowired DBClass db;
	
	@GetMapping(value="members", produces = "application/json; charset=utf-8")
	public ArrayList<InfoDTO> members() {
		return db.DB;
	}
	
	@GetMapping(value="members/{uId}", produces = "application/json; charset=utf-8")
	public InfoDTO getMember(@PathVariable String uId) {
		//System.out.println("Asdfasd");
		for(InfoDTO d : db.DB) {
			System.out.println(d.getId().equals(uId));
			if (d.getId().equals(uId)) {
				System.out.println(d.getId());
				System.out.println(d.getName());
				return d;
			}
		}
		return null;
	}
	
	@PostMapping(value="register", produces = "application/json; charset=utf-8")
	public String register(@RequestBody InfoDTO dto) {
		db.DB.add(dto);
		return "{\"num\" : 1}";
	}
	@GetMapping(value="idChk/{uId}", produces = "application/json; charset=utf-8")
	public int idChk(@PathVariable String uId) {
		for(InfoDTO d : db.DB) {
			if (d.getId().equals(uId)) {
				return 1;
			}
		}
		return 0;
	}
	@DeleteMapping(value="delete", produces = "application/json; charset=utf-8")
	public int delete(@RequestParam String id) {
		for(int i = 0; i < db.DB.size(); i++) {
			if (db.DB.get(i).getId().equals(id)) {
				db.DB.remove(i);
			}
		}
		return 1;
	}
	@PutMapping(value="modify", produces = "application/json; charset=utf-8")
	public int modify(@RequestBody InfoDTO dto) {
		for(int i = 0; i < db.DB.size(); i++) {
			if (db.DB.get(i).getId().equals(dto.getId())) {
				db.DB.set(i, dto);
			}
		}
		return 1;
	}
}

 

실행 결과

+ Recent posts