SpringBoot/day52 / 23.11.17(금) / (핀테크) Spring 및 Ai 기반 핀테크 프로젝트 구축

허니몬·2023년 11월 18일
0
post-thumbnail

P13_file


pom.xml 추가

<!-- commons-fileupload -->
<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.3.3</version>
</dependency>
   
<!-- commons-io -->
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.4</version>
</dependency>

com.web.root...


FileConfig

package com.web.root.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

// 파일관리
@Configuration
public class FileConfig {
	@Bean
	public CommonsMultipartResolver multipartResolver() {
		CommonsMultipartResolver cmr = new CommonsMultipartResolver();
		cmr.setMaxUploadSize(52428800); // 50MB
		cmr.setDefaultEncoding("utf-8");
		return cmr;
	}
}

FileDownloadController

package com.web.root.controller;

import java.io.File;
import java.io.FileInputStream;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.web.root.service.FileService;

@Controller
public class FileDownloadController {
	@GetMapping("download")
	public void download(@RequestParam("file") String fileName, HttpServletResponse response) throws Exception {
		response.addHeader("Content-dispoostion", "attachment; fileName="+URLEncoder.encode(fileName, "utf-8"));
		File file = new File(FileService.IMAGE_REPO+"\\"+fileName);
		FileInputStream fis = new FileInputStream(file);
		FileCopyUtils.copy(fis, response.getOutputStream());
		fis.close();
	}
	
}

FileUploadController

package com.web.root.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
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.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.web.root.service.FileService;

@Controller
public class FileUploadController {
	@Autowired
	private FileService fs;
	
	@RequestMapping("form")
	public String form() {
		return "uploadForm";
	}
	
	@PostMapping("upload")
	public String upload(MultipartHttpServletRequest mul) {
		String id = mul.getParameter("id");
		String name = mul.getParameter("name");
		MultipartFile file = mul.getFile("file");
		String originalFileName = file.getOriginalFilename();
		System.out.println("id : " + id);
		System.out.println("name : " + name);
		System.out.println("fileName : " + originalFileName);
		fs.fileProcess(mul);
		return "redirect:form";
	}
	
	@GetMapping("views")
	public String views(Model model) {
		fs.getShowImage(model);
		return "result"; 
	}
}

ShoesDTO

package com.web.root.dto;
/*
CREATE TABLE shoes(
id VARCHAR2(20) PRIMARY KEY,
name VARCHAR2(20),
img_name VARCHAR2(100)
);

DESC SHOES;

SELECT * FROM SHOES;
 */
public class ShoesDTO {
	private String id;
	private String name;
	private String img_name;
	
	public ShoesDTO() {
		super();
	}
	public ShoesDTO(String id, String name, String img_name) {
		super();
		this.id = id;
		this.name = name;
		this.img_name = img_name;
	}
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getImg_name() {
		return img_name;
	}
	public void setImg_name(String img_name) {
		this.img_name = img_name;
	}
	@Override
	public String toString() {
		return "[id = " + id + ", name = " + name + ", img_name = " + img_name + "]";
	}
	
	
}

FileService

package com.web.root.service;

import org.springframework.ui.Model;
import org.springframework.web.multipart.MultipartHttpServletRequest;

public interface FileService {
	public static final String IMAGE_REPO = "D:\\resource\\Spring_Fin\\uploadFolder"; 
	public void fileProcess(MultipartHttpServletRequest mul);
	public void getShowImage(Model model);
	
}

FileServiceImpl

package com.web.root.service;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.web.root.dto.ShoesDTO;
import com.web.root.mybatis.FIleMapper;

@Service
public class FileServiceImpl implements FileService{
	
	@Autowired
	private FIleMapper mapper;
	
	@Override
	public void fileProcess(MultipartHttpServletRequest mul) {
		ShoesDTO dto = new ShoesDTO();
		dto.setId(mul.getParameter("id"));
		dto.setName(mul.getParameter("name"));
		
		// TODO Auto-generated method stub
		MultipartFile file = mul.getFile("file");
		if(file.getSize() !=0) {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss-");
			Calendar calendar = Calendar.getInstance();
			String sysFileName = sdf.format(calendar.getTime());
			sysFileName += file.getOriginalFilename();
			File saveFile = new File(IMAGE_REPO + "/" + sysFileName); 
			dto.setImg_name(sysFileName);
			try {
				file.transferTo(saveFile);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}else {
			dto.setImg_name("nan");
		}
		mapper.saveData(dto);
	}

	@Override
	public void getShowImage(Model model) {
		// TODO Auto-generated method stub
		
		model.addAttribute("list", mapper.getShowImage());
	}
	
	
}

FIleMapper

package com.web.root.mybatis;

import java.util.List;

import com.web.root.dto.ShoesDTO;

public interface FIleMapper {
	public void saveData(ShoesDTO dto); 
	public List<ShoesDTO> getShowImage(); 
	
}

fileMapper.xml : resources/file/...

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- mapeprs/file/FileMapper.xml -->
<mapper namespace="com.web.root.mybatis.FIleMapper">
	<resultMap type="com.web.root.dto.ShoesDTO" id="shoes">
		<id property="id" column="id" />
		<result property="name" column="name" />
		<result property="img_name" column="img_name" />
	</resultMap>
	<insert id="saveData">
		INSERT INTO shoes VALUES(#{id},#{name},#{img_name})
	</insert>
	<select id="getShowImage" resultMap="shoes">
		SELECT * FROM shoes
 	</select>

</mapper>

uploadForm.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<c:set var="contextPath" value="${pageContext.request.contextPath }"/>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>uploadForm.jsp</title>
</head>
<body>
	<h1>파일 업로드</h1>
	<br>
	<form action="${contextPath }/upload" enctype="multipart/form-data" method="post">
		<input type="text" name="id" placeholder="id"/> <br><br>
		<input type="text" name="name" placeholder="name"/> <br><br>
		<input type="file" name="file"/> <br><br>
		<input type="submit" value="업로드" />
	</form>
	<br>
	<a href="${contextPath }/views">파일보기</a>
</body>
</html>

result.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<c:set var="contextPath" value="${pageContext.request.contextPath }"/>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>result.jsp</title>
<style type="text/css">
table{
	margin: 0 auto;
}
td {
	text-align: center;
}
</style>
<script type="text/javascript">
function imgDownload() {
	location.href="${contextPath}"+"/imgDownload";
}
</script>
</head>
<body>
	<h1>파일 확인</h1>
	
	<table border="1">
		<tr>
			<td>id</td><td>name</td><td>imgName</td>
		</tr>
		<c:forEach var="dto" items="${list }">
			<tr>
				<td>${dto.id }</td><td>${dto.name }</td><td>${dto.img_name }</td>
			</tr>
			<tr>
				<td colspan="3"> <img src="${contextPath }/download?file=${dto.img_name}" style="width: 100px; height:auto;"> </td>
			</tr>
		</c:forEach>
	</table>
	<a href="${contextPath }/form">업로드</a>
</body>
</html>



P14_ajax



# Ajax ( Asynchronous JavaScript and XML )
- 웹페이지에서 서버와 데이터 교환을 비동기적으로 처리하여 웹페이지의 일부분을 업데이트 하는
  웹 개발 기술

<!-- JSON.stringify(문자열 json타입 변경)  -->
<dependency>
   <groupId>com.fasterxml.jackson.core</groupId>
   <artifactId>jackson-databind</artifactId>
   <version>2.9.5</version>
</dependency>

<dependency>
   <groupId>net.sf.json-lib</groupId>
   <artifactId>json-lib</artifactId>
   <version>2.4</version>
   <classifier>jdk15</classifier>
</dependency>


# RESTful API ( Representational State Transfer )
- 웹 서비스를 위한 아키텍처 스타일 중 하나
  HTTP 요청을 통해 통신함으로써 리소스 내에서 레코드 CRUD 등의 표준 데이터베이스 기능 수행
- CRUD operation
  메서드	역할
  POST		리소스 생성(create)
  GET		리소스 조회(read)
  PUT		리소스 수정(update)
  DELETE	리소스 삭제(delete)

com.web.root


InfoDTO

package com.web.root;

public class InfoDTO {
	private String name;
	private int age;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	
	
}

HomeController

package com.web.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.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.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * 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";
	}
	// ---------------------------------------------------------------------------------------------------
	@RequestMapping("non_ajax")
	public String test() {
		System.out.println("- nonAjax -");
		return "non_ajax";
	}
	// ---------------------------------------------------------------------------------------------------
	/*
	 * 비동기 통신을 하기 위해서는 클라이언트에서 서버로 요청을 보낼 때,
	 * 본문에 데이터를 담아서 보내야 하고, 서버에서 클라이언트로 응답을 보낼 때에도
	 * 본문에 데이터를 담아서 보낸다
	 * - 요청 본문 : @RequestBody
	 * - 응답 본문 : @ResponseBody
	 */
	static int cnt = 0;
	@RequestMapping("ajax")
	public String ajax() {
		System.out.println("- Ajax -");
		cnt=0;
		return "ajax";
	}
	
	@RequestMapping("ajax_result")
	@ResponseBody
	public String ajaxResult() {
		System.out.println("- Ajax'+' -");
		return ++cnt + "";
	}
	@RequestMapping("ajax_result2")
	@ResponseBody
	public String ajaxResult2() {
		System.out.println("- Ajax'-' -");
		return --cnt + "";
	}
	
	// ---------------------------------------------------------------------------------------------------
	@RequestMapping("ajax2")
	public String ajax2() {
		return "ajax2";
	} 
	// ---------------------------------------------------------------------------------------------------
	@PostMapping(value = "ajax_result3", produces = "application/json; charset=utf-8")
	@ResponseBody
	public InfoDTO ajaxResult3(@RequestBody InfoDTO dto) {
		System.out.println("name : " + dto.getName());
		System.out.println("age : " + dto.getAge());
		dto.setName("서버에서 수정됨");
		dto.setAge(dto.getAge());
		return dto;
	}
	// ---------------------------------------------------------------------------------------------------
	@RequestMapping("ajax3")
	public String ajax3() {
		return "ajax3";
	} 
	
	// ---------------------------------------------------------------------------------------------------
	@RequestMapping(value = "ajax_result4", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> ajaxResult4(@RequestBody HashMap<String, Object> map) {
		Map<String, Object> map2 = map; 
		return map2;
	}
	
	@RequestMapping(value = "test2", method = RequestMethod.GET)
	@ResponseBody
	public Map<String, Object> test2(){
		Map<String, Object> map = new HashMap<String, Object>();
		
		return map;
	}
	@RequestMapping("rest")
	public String rest() {
		return "rest";
	}
	@GetMapping("getuser")
	public String getUser() {
		return "getuser";
	}
}

ajax.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>ajax.jsp</title>
<script src="https://code.jquery.com/jquery-3.7.1.min.js" integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo=" crossorigin="anonymous"></script>
<script type="text/javascript">
	function ajax() {
		$.ajax({			//property 설정을 위하여 Json형태로 작성
			  url: "ajax", // controller 에서 RequestMapping 값
			  type: "GET",
			  success: function(){
				  console.log("성공!");
			  },
			  error: function(){
				  console.log("실패");
			  }
		});
	}
	function ajax2() {
		$.ajax({			//property 설정을 위하여 Json형태로 작성
			  url: "ajax_result", // controller 에서 RequestMapping 값
			  type: "GET",
			  success: function(data){
				  $("#count").text(data);
				  console.log("성공!");
				  console.log(data);
			  },
			  error: function(){
				  console.log("실패");
			  }
		});
	}
	function ajax3() {
		$.ajax({			//property 설정을 위하여 Json형태로 작성
			  url: "ajax_result2", // controller 에서 RequestMapping 값
			  type: "GET",
			  success: function(data){
				  $("#count").text(data);
				  console.log("성공!");
				  console.log(data);
			  },
			  error: function(){
				  console.log("실패");
			  }
		});
	}
</script>
</head>
<body>
	<h1>1</h1> <h1>2</h1> <h1>3</h1> 
	<h1>4</h1> <h1>4</h1>
	<button onclick="ajax()">0</button> &nbsp;
	<label id="count">0</label> &nbsp;
	<button onclick="ajax2()">+1</button>
	<button onclick="ajax3()">-1</button>
</body>
</html>

ajax2.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>ajax2.jsp</title>
<script src="https://code.jquery.com/jquery-3.7.1.min.js" integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo=" crossorigin="anonymous"></script>
<script type="text/javascript">
	function ajax() {
		var n = document.getElementById("name").value;
		var a = $("#age").val();
		var form = {age:a, name:n};
		
		/*
			# JSON 
			- 브라우저와 서버사이에서 값을 주고 받는 데이터 형식 
			
			# JSON.stringify()
			- JavaScript 객체나 값을 JSON 문자열로 변환
		*/ 
		
		$.ajax({			
			  url: "ajax_result3", // controller / mapping 값
			  type: "POST",
			  data: JSON.stringify(form), // 서버로 전송하는 데이터
			  contentType: "application/json; charset=utf-8", // 서버로 전송하는 데이터 타입 지정
			  dataType: "json", // return type
			  success: function(data){
				  console.log("성공!");
				  $("#res_1").text(data.name);
				  $("#res_2").text(data.age);
			  },
			  error: function(){
				  console.log("실패");
			  }
		});
	}
</script>
</head>
<body>
	<h1>ajax2.jsp</h1>
	<br>
	name : <input type="text" id="name"/> <br><br>
	age : <input type="text" id="age"/><br><br>
	<input type="button" value="클릭" onclick="ajax()">
	<br>
	<h2>결과 1 : <label id="res_1"></label></h2>
	<h2>결과 2 : <label id="res_2"></label></h2>
</body>
</html>

ajax3.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>ajax3.jsp</title>
<script src="https://code.jquery.com/jquery-3.7.1.min.js" integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo=" crossorigin="anonymous"></script>
<script type="text/javascript">
	function ajax() {
		// <form> 의 값을 한번에 JSON 타입으로 변경 */
		var form = $("#frm").serializeArray();
		var formR = JSON.stringify(form);
		console.log(formR);
		$.ajax({			
			url: "ajax_result4", // controller / mapping 값
			type: "POST",
			data: formR, // 서버로 전송하는 데이터
			contentType: "application/json; charset=utf-8;", // 서버로 전송하는 데이터 타입 지정
			dataType: "json", // return type
			success: function(){
				console.log("성공");
				console.log(form);
			},
			error: function(){
				console.log("실패");
				console.log(form);
			}
		});
	}

</script>
</head>
<body>
	<h1>ajax2.jsp</h1>
	<br>
	<form id="frm" method="post">
		name : <input type="text" name="name"/> <br><br>
		age : <input type="text" name="age"/><br><br>
		addr : <input type="text" name="addr"/><br><br>
	</form>
	<input type="button" value="클릭" onclick="ajax()"/>
</body>
</html>

getuser.jsp

<%@ 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>getuser.jsp</title>
<script src="https://code.jquery.com/jquery-3.7.1.min.js" integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo=" crossorigin="anonymous"></script>
<script type="text/javascript">
	function getUsers(){
		$.ajax({
			url: "users",
			type: "GET",
			dataType: "json",
			success: function(list){
				console.log(list);
				//$("#users").text(list);
				let h = "";
				/*
				for(i=0; i<list.length; i++){
					h+="<b>이름 : </b>" + list[i].name + " &nbsp; "
					h+="<b>나이 : </b>" + list[i].age + " <br>"
				}
				$("#users").html(h);
				*/
				$.each(list, function(index,data){
					h+="<b>이름 : </b>" + data.name + " &nbsp; "
					h+="<b>나이 : </b>" + data.age + " <br>"
				});
				$("#users").html(h);
			}
		});
	}
	function userInfoOne() {
		$.ajax({
			url: "user?userId="+$("#userId").val(), 
			type: "GET",
			dataType: "json",
			success: function(data){
				h = "";
				h+="<b>이름 : </b>" + data.name + " &nbsp; "
				h+="<b>나이 : </b>" + data.age + " <br>"
				$("#userInfo").append(h);
			}
		});
	}
	function userInfoOne2() { // uri 방식 전송
		$.ajax({
			url: "user/"+$("#userId").val(), 
			type: "GET",
			dataType: "json",
			success: function(data){
				h = "";
				h+="<b>이름 : </b>" + data.name + " &nbsp; "
				h+="<b>나이 : </b>" + data.age + " <br>"
				$("#userInfo2").append(h);
			}
		});
	}
	function modify() {
		name = $("#name").val();
		age = $("#age").val();
		form = {name:name, age:age};
		$.ajax({
			url: "modify", 
			type: "PUT",
			dataType: "json",
			data: JSON.stringify(form),
			contentType: "application/json; charset=utf-8",
			success: function(data){
				let h = "";
				h+="<b>이름 : </b>" + data.name + " &nbsp; "
				h+="<b>나이 : </b>" + data.age + " <br>"
				$("#res").append(h);
			}
		});
	}
	function save() {
		let form = {};
		let arr = $("#frm").serializeArray();
		for(i=0; i<arr.length; i++){
			form[arr[i].name] = arr[i].value;
		}
		$.ajax({
			url: "save", 
			type: "POST",
			dataType: "json",
			data: JSON.stringify(form),
			contentType: "application/json; charset=utf-8",
			success: function(data){
				if(data.result == true)
					alert("회원 정보 추가 성공!");
				else 
					alert("회원 정보 추가 실패!")
			}
		});
	}
</script>
</head>
<body>
	<h1>getuser.jsp</h1>
	<span id="users"></span>	 
	<hr>
	<button type="button" onclick="getUsers()">사용자 목록</button>
	<br>
	<hr>

	<input type="text" id="userId">
	<br>
	<span id="userInfo"></span>
	<button type="button" onclick="userInfoOne()">사용자 목록</button>
	<br>
	<span id="userInfo2"></span>
	<button type="button" onclick="userInfoOne2()">사용자 목록</button>
	<br>
	<hr>
	
	<br>
	<h3>수 정</h3>
	이 름 : <input type="text" id="name" name="name"><br><br>	
	나 이 : <input type="text" id="age" name="age"><br><br>
	<span id="res"></span> <br>
	<button type="button" onclick="modify()">정보 수정</button>
	<br>
	<hr>
	
	<h3>회원 가입</h3>
	<form id="frm">
		id : <input type="text" id="uId" name="uId"/> <br><br>
		name : <input type="text" id="uName" name="uName"/> <br><br>
		age : <input type="text" id="uAge" name="uAge"/> <br><br>
		addr : <input type="text" id="uAddr" name="uAddr"/> <br><br>
		phone : <input type="text" id="uPhone" name="uPhone"/> <br><br>
	</form>
	<input type="button" value="회원가입" onclick="save()"/>
	<br>
	<hr>
	
</body>
</html>

rest.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>rest.jsp</title>
<script src="https://code.jquery.com/jquery-3.7.1.min.js" integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo=" crossorigin="anonymous"></script>
<script type="text/javascript">
	function restGet(){
		$.ajax({
			url: "rest",
			type: "GET",
			dataType: "json",
			success: function(data){
				$("#label").text(data.execute);
			}
		});
	}
	function restPost(){
		$.ajax({
			url: "rest",
			type: "POST",
			dataType: "json",
			success: function(data){
				$("#label").text(data.execute);
			}
		});
	}
	function restPut(){
		$.ajax({
			url: "rest",
			type: "PUT",
			dataType: "json",
			success: function(data){
				$("#label").text(data.execute);
			}
		});
	}
	function restDelete(){
		$.ajax({
			url: "rest",
			type: "DELETE",
			dataType: "json",
			success: function(data){
				$("#label").text(data.execute);
			}
		});
	}
</script>
</head>
<body>
	<h1>rest.jsp</h1>
	<label id="label"></label>
	<br>
	<a href="getuser">getuser</a>
	<button onclick="restGet()">GET</button> &nbsp;
	<button onclick="restPost()">POST</button> &nbsp;
	<button onclick="restPut()">PUT</button> &nbsp;
	<button onclick="restDelete()">DELETE</button> &nbsp;
</body>
</html>

RESTController

package com.web.root;

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

import org.apache.commons.collections.map.HashedMap;
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;

@RestController
public class RESTController {
	
	@GetMapping(value = "rest", produces = "application/json; charset=utf-8")
	public String get() {
		return "{\"execute\" : \"get.데이터 요청시\"}";
	}
	@PostMapping(value = "rest", produces = "application/json; charset=utf-8")
	public String post() {
		return "{\"execute\" : \"post.데이터 요청시\"}";
	}
	@PutMapping(value = "rest", produces = "application/json; charset=utf-8")
	public String put() {
		return "{\"execute\" : \"put.데이터 요청시\"}";
	}
	@DeleteMapping(value = "rest", produces = "application/json; charset=utf-8")
	public String delete() {
		return "{\"execute\" : \"delete.데이터 요청시\"}"; 
	}

	static int cnt = 0;
	static Map<String, InfoDTO> DB = new HashMap<>();
	
	
	ArrayList<InfoDTO> list = new ArrayList<InfoDTO>();
	@GetMapping(value = "users", produces = "application/json; charset=utf-8")
	public ArrayList<InfoDTO> getusers() {
		for(int i=cnt; i<cnt+10; i++) {
			InfoDTO dto = new InfoDTO();
			dto.setName("test"+i);
			dto.setAge(10+i);
			list.add(dto);
			DB.put("test"+i, dto);
		}
		cnt+=10; 
		return list;
	}
	
	@GetMapping(value = "user" ,produces = "application/json; charset=utf-8")
	public InfoDTO user1(@RequestParam String userId) {
		return DB.get(userId);
	}
	
	@GetMapping(value = "user/{id}" ,produces = "application/json; charset=utf-8")
	public InfoDTO user2(@PathVariable("id") String userId) { //해당 uri 값에 넘어온 id 를 매개변수에서 사용하기 위한 @
		return DB.get(userId);
	}
	@PutMapping(value = "modify", produces = "application/json; charset=utf-8")
	public InfoDTO modify(@RequestBody InfoDTO dto) {
		/*
		 * service -> mapper ->
		 * update table ser age=age where name=name ->
		 * dto = select * from table were name=name
		 */
		DB.replace(dto.getName(), dto);
		return DB.get(dto.getName());
	} 
	
	@PostMapping(value = "save", produces = "application/json; charset=utf-8")
	public String save(@RequestBody Map<String, Object> map) {
		System.out.println("id : " + map.get("uId"));
		System.out.println("name : " + map.get("uName"));
		System.out.println("age : " + map.get("uAge"));
		System.out.println("addr : " + map.get("uAddr"));
		System.out.println("phone : " + map.get("uPhone"));
		InfoDTO dto = new InfoDTO();
		dto.setName(map.get("uName").toString());
		dto.setAge(Integer.parseInt(map.get("uAge").toString()));
		list.add(dto);
		DB.put(dto.getName(), dto);
		return "{ \"result\" : true}";
		
	}
}

profile
Fintech

0개의 댓글