java->json

최고고·2022년 3월 17일
0
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
	title : <input type="text" name="title"><br>
	start : <input type="date" name="start"><br>
	end : <input type="date" name="end"><br>
	<button onclick="input()">input</button>
	<button onclick="save()">저장하기</button>
	
	<hr>
	
	<script type="text/javascript" src="js/jquery-3.6.0.min.js"></script>
	<script type="text/javascript">
	
	//값을 list 담아서 사용할거임
	let putData = [];
	function input(){
		putData.push({
			'title' : $('input[name=title]').val(),
			'start' : $('input[name=start]').val(),
			'end' : $('input[name=end]').val()
		});
		console.log(putData);
	}
	
	
	
	function save(){
		$.ajax({
				url : "ex03sendJson",
				//같은 프로젝트 내에서 url mapping, 파일명
				type : "post",
				data : {
					'json' : JSON.stringify(putData) 	//json데이터를 string타입으로 보내겠다는뜻
				},	//json으로 바꿔서 보내줘야하기때문
				//dataType : "json",
				//dataType 가져올 데이터타입
				//res - 서버에 요청된 결과가 담기게 됨
				success : function(res){
					//alert("성공");
					console.log(res);
					$('hr').after(res);
				},
				error : function(){
					alert("실패");
				}
				
			
		});
	}
	
	
	
	</script>
	
</body>
</html>

--

package Controller;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;

import Model.CalendarDTO;

@WebServlet("/ex03sendJson")
public class ex03sendJson extends HttpServlet {
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//json 쉽게 쓸 수 있도록 DTO 생성
		String json = request.getParameter("json"); 	//jsp에서 받아온 'json'
		
		//Gson객체생성 gson라이브러리 이용 
		Gson gson = new Gson();
		//String -> 객체형태로--> 제이슨으로 만들어주는 함수 .fromJson(데이터, 저장할 변수의 클래스정보)-데이터, 비교해서 정보를 넣어줄 클래스
		CalendarDTO[] list = gson.fromJson(json, CalendarDTO[].class); 	//putData를 배열로만들었기 때문
		
		//리스트를 보내주기 위해 리스트변수에 담아줌
		
		for(int i = 0; i < list.length; i++) {
			System.out.println(list[i].getTitle());
			System.out.println(list[i].getStart());
			System.out.println(list[i].getEnd());
			System.out.println("=====구분선=====");
		}
	}

}

--

package Model;

public class CalendarDTO {
	private String title;
	private String start;
	private String end;
	
	public CalendarDTO(String title, String start, String end) {
		super();
		this.title = title;
		this.start = start;
		this.end = end;
	}
	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title;
	}
	public String getStart() {
		return start;
	}
	public void setStart(String start) {
		this.start = start;
	}
	public String getEnd() {
		return end;
	}
	public void setEnd(String end) {
		this.end = end;
	}
	
}

0개의 댓글