반응형

fetch 사용하다가...

 fetch("http://localhost:8081/startDown",{
                method : 'POST',
                 mode : 'cors',
                 cache : 'no-cache',
                 headers: {'Content-Type': 'application/json'},
                 credentials : 'same-origin',
                 redirect : 'follow',
                 referrer : 'no-referrer',
                 body: JSON.stringify(this.obj)
            }).then(response => response.text())	// 첫번째 then
              .then(res=>{ console.log(res); })	// 두번째 then

왜 위처럼 첫번째 단계에서 response.text() 한 것을 바로 사용하지 않고 .then을 한 번 더 쓰는건지 궁금했다.

왜 아래처럼 첫번째 then에서 파싱한걸 바로 사용하지 않는건지...

 fetch("url",{option}).then(response => {
            	let res = response.text();              
            
            })

이래저래 내린 결론

  • 첫 번째 then 단계에서는 response의 status 결과를 보고 어떻게 처리할지 결정할 수 있게 한다.
  • 첫 번째 단계에서는 body가 load되길 기다린다. 즉. body가 다 안 왔을 수 있다는 것. 그래서 promise를 반환한다.
  • response.text()로 파싱하는 경우 promise를 반환한다. 이 promise에 담긴 값을 사용하려면 두 번째 .then으로 받아서 promise 내부의 PromiseResult 를 사용해야 한다.

 

 

우선 promise와 .then은 이렇게 이해했다.

  • promise : 비동기 코드가 끝나면 반환된다. 비동기 처리의 상태와 데이터를 담게 되어 있다.
  • .then : 비동기 처리가 끝난 다음에 처리할 일을 정의할 수 있다.

1) fetch의 결과 출력해보기

let res = fetch("http://localhost:8081/startDown",{
                method : 'POST',
                 mode : 'cors',
                 cache : 'no-cache',
                 headers: {'Content-Type': 'application/json'},
                 credentials : 'same-origin',
                 redirect : 'follow',
                 referrer : 'no-referrer',
                 body: JSON.stringify(this.obj)
            })
console.log(res)

fetch의 결과로 Promise가 반환되었다.

pending 상태의 Promise가 찍힌것이 보이고, 화살표를 눌러 펼쳐보면 fulfilled(이행)상태가 된 것을 알 수 있다.

이행(완료)된 Promise의 Result엔 http 통신 결과로 응답 정보를 담고있는 Response Object 가 보임..

Response의 header를 보고 요청이 성공했는지 아닌지 확인 가능.

 

 

2) fetch의 결과를 .then으로 출력해보기

 fetch("",{}) //fetch url과 옵션은 생략
 	.then(console.log)

 

.then이 promise를 까서 Result인 Response object를 보여준다.

이 Response의 body를 읽으려면 response.text()나 json()같은 메소드를 사용한다.

  • status – HTTP 상태 코드(예: 200)
  • ok – 불린 값. HTTP 상태 코드가 200과 299 사이일 경우 true

 

 

3. 첫번째 then 안에서 response.text()를 한 뒤 결과물 출력해 보기

 fetch("",{ })
 	.then(response => {
                let pr = response.text();
                console.log(pr);
            })

Promise가 반환되는데, <pending>상태이지만 눌러보면 fulfilled라고 나온다. 

[i]에 이런 메세지가 보인다.

"This value was evaluated upon first expanding. It may have changed since then."

console.log가 비동기로 실행되기 때문에 console.log를 찍을 시점에는 promise가 pending 상태였으나 이후에 fulfilled 상태가 된 것을 보여준다.

 

response.text() 를 한 후 3초를 기다려서 출력해보았다

}).then(response => {
                let pr = response.text();
                setTimeout(function(){console.log(pr)},3000);
            })

아까랑 다르게 찍는 시점에서 이미 fulfilled 상태이다. 

 

 

4. 두 번째 then에서 값 출력해보기

첫 번째 .then에서 반환해준  Promise를 두 번째 .then에서 받아 PromiseResult에 담긴 값을 사용한다.

response.text() 후에 .then에서 값을 출력해보면

PromiseResult의 값이 출력되었다

fetch("",{})
	.then(response => response.text())
	.then(console.log)


참고 

 

fetch

 

ko.javascript.info

 

 

프라미스(Promise)

0px Promise는 무엇인가? Promise의 state와 result Promise chaining return Promise Error handling Promise API async, await Promise는 무엇인가? 단어 그대로 약속(promise)입니다. 어떤 약속이냐면 어떠한..

snowboolean.tistory.com

 

 

fetch() 함수 사용법 - Blog by Yeri

백앤드로부터 데이터를 받아오려면 api를 호출하고 데이터를 응답받습니다. 이 때 자바스크립트 Web API fetch() 함수를 쓰거나 axios 라이브러리를 사용할 수 있습니다. 참고로 Web API는 클라이언트

yeri-kim.github.io

 

 

 

Why is the response object from JavaScript fetch API a promise?

When requesting from a server with JavaScript fetch API, you have to do something like fetch(API) .then(response => response.json()) .catch(err => console.log(err)) Here, response.json(...

stackoverflow.com

 

반응형
반응형

터미널에서 다음 명령어 입력하여 라이브러리 설치

npm install [라이브러리이름]

node_modules 밑에 설치한 라이브러리가 추가된다

script 부분에서 import XLSX from 'xlsx' 입력하면 됨

<script>
import XLSX from 'xlsx'
  export default{
    data() {
      return {
       year : ["2020","2021"],
       month : 12,
       day : 31
    }
   }
</script>
반응형
반응형

상단 메뉴바 File > New > Project

 

Gradle, Java 선택, Next

 

프로젝트 이름이랑 경로 지정

프로젝트에서 

build.gradle에서 의존성 설정

plugins {
    id 'org.springframework.boot' version '2.5.0'
    id 'io.spring.dependency-management' version '1.0.11.RELEASE'
    id 'java'
}

group 'org.example'
version '1.0-SNAPSHOT'

repositories {
    mavenCentral()
}

dependencies {

    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'

    testImplementation 'org.junit.jupiter:junit-jupiter-api:5.7.0'
    testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.7.0'
}

test {
    useJUnitPlatform()
}

 

java 디렉토리 밑에 패키지랑 controller 등 이것저것 뚝딱뚝딱

 

RunApplication 내용

package com.export;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class RunApplication {
    public static void main(String[] args){
        SpringApplication.run(RunApplication.class,args);
    }
}

 

기본적인 실행을 위한 Controller 내용

package com.export.controller;

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

@Controller
public class MainController {
    @RequestMapping(value = "/home")
    public String main() throws Exception {
        return "index";

    }
}

 


참고

 

Building an Application with Spring Boot

this guide is designed to get you productive as quickly as possible and using the latest Spring project releases and techniques as recommended by the Spring team

spring.io

 

반응형
반응형

** WARNING ** : Your ApplicationContext is unlikely to start due to a @ComponentScan of the default package.

SpringBoot 프로젝트 생성 후 실행하려 하니 위와 같은 에러가 났다..

 

실행용 RunApplication은 java 바로 밑에 있음.

자바 class파일은 java > com > export 패키지에 있음

=> 위치가 달라서 ComponentScan하는데에 문제가 생긴 것 같음..

 

해결방안 : 위치를 통일시켜 준다.

RunApplication 파일의 위치를 com.export 밑으로 이동시킨다.

package com.export에 포함되었다.

package com.export;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class RunApplication {
    public static void main(String[] args){
        SpringApplication.run(RunApplication.class,args);
    }
}

 

아니면 자바 class 파일들을 java 폴더 바로 밑으로 옮기든지...

반응형
반응형

BigDecimal 객체를 이용한다. 

BigDecimal test1 = new BigDecimal(2021061523295E11);
System.out.println(test1); ////202106152329500000518144

///// String -> double 파싱 후 BigDecimal 객체 생성
BigDecimal test2 = new BigDecimal(Double.parseDouble("2021061523295E11"));
System.out.println(test2); ////202106152329500000518144


///// BigDecimal 객체 -> String 객체
String str = test2.toString();

 

반응형
반응형

build.gradle에서 의존성 추가

implementation 'org.apache.commons:commons-lang3:3.0'

 

길이가 3인 두개의 배열이 있다

String[] strs1 = {"a","b","c"};
String[] strs2 = {"d","e","f"};



여기에 배열 길이를 초과해서 인덱스3에 "g"라는 요소를 대입하면

될리가 없다. Exception 나버림.

strs2[3] = "g";

-> java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3


 

해결방법 : ArrayUtils를 사용해서 붙여준다.

ArrayUtils.add(기존배열,붙일요소);

String[] strs3 = ArrayUtils.add(strs2,"g");


/////잘 붙었는지 출력해보자
for(int i=0; i< strs3.length;i++){
     System.out.println(strs3[i]);
}

d
e
f
g
/////잘 붙었다





배열 + 배열도 가능하다

ArrayUtils.addAll(기존배열,붙일배열);

strs3 = ArrayUtils.addAll(strs1,strs3);


/////잘 붙었는지 출력해보자
for(int i=0; i< strs3.length;i++){
	System.out.println(strs3[i]);
}

a
b
c
d
e
f
g
/////잘 붙었다
반응형
반응형

Date 객체로 오늘 날짜 가져오기

1) Date 객체 생성, date객체를 직접 찍어봄

2) getTime()메소드 사용(1970년 1/1 부터 주어진 날짜 사이의 경과시간이 반환됨)

///// 1) Date 객체 생성해서 찍어보기
Date myDate = new Date();
System.out.println(myDate); //Fri Sep 03 11:34:26 KST 2021

///// 2) getTime() 
//1970 년 1 월 1 일 00:00:00 UTC와 주어진 날짜 사이의 경과 시간 (밀리 초)을 나타냄
System.out.println(myDate.getTime()); //1630635552571

 


Date 객체에 원하는 날짜 설정하기

1) setTime() 메소드 사용 (1970년 1/1과 세팅하려는 날짜 사이의 경과시간으로 세팅해야됨)

2) SimpleDateFormat을 이용한 세팅

Date myDate = new Date();

///// 1) setTime()
//1970 년 1 월 1 일 00:00:00 UTC와 설정하려는 날짜 사이의 밀리초로 세팅해야됨
myDate.setTime(1609426800000L);
System.out.println(myDate.getTime()); //1609426800000


///// 2) simpleDateFormat으로 String타입 날짜를 date로 변환하여 넣는다.
String myString = "20210101";
SimpleDateFormat dtFormat = new SimpleDateFormat("yyyyMMdd");
Date mydate = dtFormat.parse(myString);

System.out.println(mydate); //Fri Jan 01 00:00:00 KST 2021

 


Calendar 객체로 오늘 날짜 가져오기

1) setTime 으로 오늘날짜 지정 -> getTime으로 날짜 가져오기

2) cal.get(Calendar.YEAR)

* MONTH 는 0부터 시작이므로 0이 1월임. 즉 9월은 8이 출력됨.

//Calendar 객체 생성
Calendar cal = Calendar.getInstance();

///// 오늘 날짜 설정
cal.setTime(new Date());
System.out.println(cal.getTime()); //Fri Sep 03 11:23:48 KST 2021


System.out.println(cal.get(Calendar.YEAR)); /// 년도 2021
System.out.println(cal.get(Calendar.MONTH)); /// 달 8
System.out.println(cal.get(Calendar.DATE)); /// 날짜 3
System.out.println(cal.get(Calendar.HOUR));  /// 시간 
System.out.println(cal.get(Calendar.MINUTE)); /// 분 
System.out.println(cal.get(Calendar.SECOND)); /// 초

Calendar 객체에 원하는 날짜 설정하기

1) set 메소드 사용. 년, 월, 일 값으로 설정

2) setTime 메소드 사용. Date 객체로 설정

Calendar cal = Calendar.getInstance();

///// 1) set 메소드(년,월,일)
cal.set(2021,8,1);
System.out.println(cal.getTime()); //Wed Sep 01 11:23:48 KST 2021


///// 2) setTime 메소드(Date객체)
cal.setTime(mydate);
System.out.println(cal.getTime()); //Fri Jan 01 00:00:00 KST 2021

 


날짜 계산하기

1) 1일 뒤 날짜 구하기 : cal.add(Calendar.Date, 1)

2) 1달 뒤 날짜 구하기 : cal.cadd(Calendar.Month, 1);

3) 두 날짜 사이이의 간격 구하기

Calendar cal = Calendar.getInstance();
cal.setTime(new Date());

///// 오늘날짜 +1 => 내일
cal.add(Calendar.DATE,1);
System.out.println(cal.getTime()); //Thu Sep 02 11:23:48 KST 2021

///// 오늘날짜 -7 => 7일 전(일주일 전)
cal.add(Calendar.DATE,-7);

///// 오늘 달 +1 => 다음 달
cal.add(Calendar.MONTH,1);
System.out.println(cal.getTime()); //Sat Oct 02 11:23:48 KST 2021

///// 오늘 달 -1 => 저번 달
cal.add(Calendar.Month,-1);


///// 두 날짜 사이의 간격 구하기 (일 수)
SimpleDateFormat dtFormat = new SimpleDateFormat("yyyy/MM/dd");
Date sTime = dtFormat.parse("20210801");
Date eTime = dtFormat.parse("20210901");
long diffDays = (eTime.getTime() - sTime.getTime()) / 1000 / (24*60*60);

 


String -> Date

String myString = "20210101";
SimpleDateFormat dtFormat = new SimpleDateFormat("yyyyMMdd");
Date myDate = dtFormat.parse(myString);

System.out.println(myDate);
//Fri Sep 03 00:00:00 KST 2021

 

Date -> String

Date myDate = new Date();
SimpleDateFormat dtFormat = new SimpleDateFormat("yyyyMMdd");
String myString = dtFormat.format(myDate);

 

Calendar -> String

Calendar cal = Calendar.getInstance();
cal.set(2021,0,1);

SimpleDateFormat dtFormat = new SimpleDateFormat("yyyyMMdd");
String myString = dtFormat.format(cal.getTime());

System.out.println(myString); //20210101

 

String -> Calendar

String myString = "20210101";
SimpleDateFormat dtFormat = new SimpleDateFormat("yyyyMMdd");
Date myDate = dtFormat.parse(myString);
cal.setTime(mydate);

System.out.println(cal.getTime());

 

Timestamp -> String

Date st = new Date(Integer.parseInt(timestamp)*1000L);
SimpleDateFormat dtFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String result = dtFormat.format(st);
반응형
반응형

AJAX 코드 

  • success : url 호출에 대한 응답 코드가 2xx인 경우

기본적으datastatusText, jqXHR 세 개의 파라미터가 있다.

 

  • error : url 호출에 대한 응답 코드가 2xx가 아닌 경우

error의 경우도 jqXHR, textStatus, errorThrown 세 개의 파라미터를 가진다.

jqXHR : 서버에서 responseEntity에 담아서 보낸 응답 메시지로, 데이터 내부에서 응답 텍스트와 응답 코드를 확인할 수 있다.

errorThrown :  응답코드의 텍스트 이름이라고 한다.(근데 나는 안 뜸)

 $.ajax({
 	type: "post",
	url : "http://localhost:8080/donwnload",
	headers: {'Content-Type': 'application/json'},
	data : JSON.stringify(obj),
                    
	success : function (data, statusText, jqXHR){
		console.log(data); //응답 body부 데이터
		console.log(statusText); //"succes"로 고정인듯함
		console.log(jqXHR);
	},
                    
	error : function (jqXHR, textStatus, errorThrown){
		console.log(jqXHR);  //응답 메시지
		console.log(textStatus); //"error"로 고정인듯함
		console.log(errorThrown);
	}
})

 

error function의 jqXHR

  • responseText : ResponseEntity 응답 메시지로 보낸 텍스트 ( jquery 1.4.x 버전은 XMLHttpRequest로 표시)
  • status : 응답코드

 


참고

 

jQuery.ajax() | jQuery API Documentation

Description: Perform an asynchronous HTTP (Ajax) request. The $.ajax() function underlies all Ajax requests sent by jQuery. It is often unnecessary to directly call this function, as several higher-level alternatives like $.get() and .load() are available

api.jquery.com

 

반응형
반응형

의존성 추가

compile "org.apache.commons:commons-csv:1.8"

 

java 메소드

@GetMapping(value = "/returnCSV", produces = "text/csv")
public ResponseEntity<Resource> exportCSV() {

	///////csv 컬럼명
	String[] csvHeader = { "번호", "이름", "나이" };

	//////csv 데이터
	List<List<String>> csvBody = new ArrayList<>();
	csvBody.add(Arrays.asList("1", "Williams", "25"));
	csvBody.add(Arrays.asList("2", "Smith", "44"));
	csvBody.add(Arrays.asList("3", "Brown", "31"));

	ByteArrayInputStream byteArrayOutputStream;

	try (
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		CSVPrinter csvPrinter = new CSVPrinter(new PrintWriter(out),CSVFormat.DEFAULT.withHeader(csvHeader));
	){
		for (List<String> record : csvBody){
			csvPrinter.printRecord(record); 
		}
		csvPrinter.flush();
		byteArrayOutputStream = new ByteArrayInputStream(out.toByteArray());
    	
	} catch (IOException e) {
		throw new RuntimeException(e.getMessage());
	}

	InputStreamResource fileInputStream = new InputStreamResource(byteArrayOutputStream);

	String csvFileName = "people.csv";

	//////Http 헤더설정
	HttpHeaders headers = new HttpHeaders();
	headers.set(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + csvFileName);
		
	//////Content Type 설정(text/csv)
	headers.set(HttpHeaders.CONTENT_TYPE, "text/csv");

	return new ResponseEntity<Resource>(fileInputStream,headers,HttpStatus.OK);
}

 

전달되는 데이터는 이렇게 생김

번호,이름,나이
1,Williams,25
2,Smith,44
3,Brown,31

 

웹에서 csv 전달받는 javascript 코드

전달받은 csv 을 웹에서 파일로 다운로드 

fetch("http://localhost:8080/test",{
                    method : 'POST',
                    mode : 'cors',
                    cache : 'no-cache',
                    headers: {'Content-Type': 'application/json'},
                    credentials : 'same-origin',
                    redirect : 'follow',
                    referrer : 'no-referrer',
                    body: JSON.stringify(obj),
}).then(response => response.text())
  .then(function(res){
  	let csv=[];
	csv.push(res);
    
	////////한글 처리를 해주기 위해 BOM 추가
	csv = "\uFEFF" + csv;

	let csvFile = new Blob([csv], { type: "text/csv" });
	let downloadLink = document.createElement("a");
	downloadLink.download = "filename.csv";
	downloadLink.href = window.URL.createObjectURL(csvFile);
	downloadLink.style.display = "none";
	document.body.appendChild(downloadLink);
 	downloadLink.click();
})

 

 


Javascript에서 csv 생성 및 다운로드

 

[JavaScript] CSV 생성 및 다운로드

1. 다운로드 버튼 클릭 이벤트 $("#excelDownload").click(function () { let filename = "testFile.csv"; getCSV(filename); }); 2. CSV 생성 함수 function getCSV(filename) { var csv = []; var row = []; //1..

mchch.tistory.com

 

fetch 사용

 

[JavaScript] fetch 사용법, fetch 응답 사용, fetch 변수 사용

ajax 대신 사용하는 api 호출 방법 fetch() 기본 //fetch를 호출하면 브라우저는 네트워크 요청을 보내고 promise를 반환한다. let promise = fetch(url, {options}) fetch(url, options) //api호출 성공 시 응답(..

mchch.tistory.com

 

csv return 방법 참고

 

Returning CSV Content From an API in Spring Boot

Avoiding conversion overhead by returning CSV data directly

codeburst.io

 

반응형
반응형

JavaScript에서 AJAX 나 Fetch로 JSON 데이터 전송, SpringBoot의 Controller에서 데이터 받기


 

AJAX로 데이터 전송하기  : Content -Type  지정하지 않은 경우

 

1) javascript 

Content Type을 명시하지 않으면 기본 타입은 application/x-www-form-urlencoded 으로 전송된다. 

let obj={
	"fromYear" : $('#fromYear').val(),
	"fromMonth" : $('#fromMonth').val(),
	"fromDay" : $('#fromDay').val(),
	"toYear" : $('#toYear').val(),
	"toMonth" : $('#toMonth').val(),
	"toDay" : $('#toDay').val()
};


$.ajax({
        type: "post",
        url : "http://localhost:8080/test2",
        data : obj,
        success : function (data){
        },
})

 

2) 전송되는 데이터 확인

요청 헤더의 Content-Type 은 application/x-www-form-urlencoded; charset=UTF-8 이며

body의 데이터가 FormData로 표시된다. 

 

3) 데이터 수신 Controller 

파라미터는 변수명이나 VO로 받는다.

@RequestMapping(value = "/test2", method = RequestMethod.POST)
@ResponseBody
public void test2(String fromYear, String fromMonth, String fromDay,String toYear, String toMonth, String toDay){
	System.out.println(fromYear+fromMonth+fromDay);
	//2021825
}

 

혹은 HttpServletRequest로 받는다.

HttpServletRequest로 받는 경우 데이터를 좀 가공함.

@RequestMapping(value = "/test2", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<Resource> test(HttpServletRequest req)throws IOException{
	//readBody 메소드 호출
	String body = readBody(req);
	System.out.println(readBody(req));
	//fromYear=2021&fromMonth=8&fromDay=25&toYear=2021&toMonth=8&toDay=25

	//String 으로 바꾼 body부를 JSON형태로 변환하여 사용
	org.json.simple.parser.JSONParser parser = new org.json.simple.parser.JSONParser();
	Object obj = parser.parse(body);
	JSONObject jsonObj = (JSONObject) obj;
	String fromYear = (String) jsonObj.get("fromYear");
    
	return new ResponseEntity<>("성공", HttpStatus.OK);
}


//body 읽는 메소드
public static String readBody(HttpServletRequest request) throws IOException {
        BufferedReader input = new BufferedReader(new InputStreamReader(request.getInputStream()));
        StringBuilder builder = new StringBuilder();
        String buffer;
        while ((buffer = input.readLine()) != null) {
            if (builder.length() > 0) {
                builder.append("\n");
            }
            builder.append(buffer);
        }
        return builder.toString();
}

 

 


 

반응형

 

 

AJAX로 데이터 전송하기  : Content -Type  을 JSON으로 보내는 경우

 

1) javascript 

보낼 데이터를 JSON.stringify()로 감싸주어야 한다.

$.ajax({
        type: "post",
        url : "http://localhost:8080/test2",
        headers: {'Content-Type': 'application/json'},
        ///보낼 데이터를 JSON.stringify()로 감싸주어야 함
        data : JSON.stringify(obj),
        success : function (data){
        	console.log(data);
        },
        error : function(e){
        }
})

 

2) 전송되는 데이터 확인

요청 헤더의 Content-Type은 application/json이며

body의 데이터가 Request Payload로 표시된다

 

 

3) 데이터 수신 Controller 

 파라미터를 HttpServletRequest로 받는다.

@RequestMapping(value = "/test", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<Resource> test(HttpServletRequest req)throws IOException{
	System.out.println(readBody(req));
 	//{"fromYear":"2021","fromMonth":"8","fromDay":"25","toYear":"2021","toMonth":"8","toDay":"25"}
}


public static String readBody(HttpServletRequest request) throws IOException {
        BufferedReader input = new BufferedReader(new InputStreamReader(request.getInputStream()));
        StringBuilder builder = new StringBuilder();
        String buffer;
        while ((buffer = input.readLine()) != null) {
            if (builder.length() > 0) {
                builder.append("\n");
            }
            builder.append(buffer);
        }
        return builder.toString();
}

 


 

fetch로 데이터 전송하기

 

1) javascript 

fetch("http://localhost:8080/test",{
                    method : 'POST',
                    mode : 'cors',
                    cache : 'no-cache',
                    //Content Type은 json으로 명시한다.
                    headers: {'Content-Type': 'application/json'},
                    credentials : 'same-origin',
                    redirect : 'follow',
                    referrer : 'no-referrer',
                    body: JSON.stringify(obj),
}).then(response => console.log(response));

 

2) 전송되는 데이터 확인

request payload로 전송이됨

 

 

3) 데이터 수신 Controller

파라미터는 HttpServletRequest로 받는다.

@RequestMapping(value = "/test", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<Resource> test(HttpServletRequest req)throws IOException{
	System.out.println(readBody(req));
	//{"fromYear":"2021","fromMonth":"8","fromDay":"25","toYear":"2021","toMonth":"8","toDay":"25"}
}


public static String readBody(HttpServletRequest request) throws IOException {
        BufferedReader input = new BufferedReader(new InputStreamReader(request.getInputStream()));
        StringBuilder builder = new StringBuilder();
        String buffer;
        while ((buffer = input.readLine()) != null) {
            if (builder.length() > 0) {
                builder.append("\n");
            }
            builder.append(buffer);
        }
        return builder.toString();
}

 

 

 


참고

 

What's the difference between "Request Payload" vs "Form Data" as seen in Chrome dev tools Network tab

I have an old web application I have to support (which I did not write). When I fill out a form and submit then check the "Network" tab in Chrome I see "Request Payload" where I would normally see...

stackoverflow.com

 

반응형

+ Recent posts