Notice
Recent Posts
Recent Comments
Link
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
Archives
Today
Total
관리 메뉴

Mintaka's log

[Spring boot] ajax로 json 데이터 받기 (html, jsp 사용) 본문

etc...

[Spring boot] ajax로 json 데이터 받기 (html, jsp 사용)

_해랑 2022. 12. 1. 19:23

jquery에서 이런식으로 하면 json 변수를 만들고 원하는 값을 출력 할 수 있다.

console.log("json 시험 중");
var person = {name : "abc", gender : "male"};
console.log(person);
console.log(person.name);

 

즉, json타입으로 값을 받아오면 jquery에서 원하는 값 조정이 가능함.

그러니까 컨트롤러에서 json 타입 만들어 가져오면 되겠지.

 

그럼 먼저.

1. ajax에서 받아올 데이터타입을 지정해주어야 함!

$.ajax({
		type : 'GET',
		url : '/HospitalMainDatePlus',
		data : {hiddendate : value},
		dataType : 'json',
		success : function(data){
			console.log("성공");
			console.log(data);
		},
		error : function(){
			console.log("실패..");
		},
		complete : function(){
			console.log("완료");
		},
		beforeSend : function(){
			console.log("이제 보낼거다..")
		}
	});

 

컨트롤러에서는 json형태로 리턴하기 위해 @ResponseBody를 써주어야 함!

	@RequestMapping("/HospitalMainDatePlus")
	@ResponseBody
	public String datePlus(HttpServletResponse response, @RequestParam int hiddendate) {

		LocalDate dateadded = LocalDate.now().plusDays(hiddendate);

		//MakeJson mj = new MakeJson();

		String jsonResult = "{" + "\"a\":\"b\"" + "}";
		System.out.println(jsonResult);
		
		return jsonResult;
	}

이렇게 했을 때 임의로 만들어낸 json 데이터가 console에서 출력되는걸 확인했음!

그럼 이제 보내고 싶은 json을 만들어주기.

 

2. json 만들기

ajax에서 컨트롤러로 보낼 값은 날짜 증가분이고, 해당하는 날짜에 대한 dto들을 json으로 만들어 리턴해 줄 계획.

MakeJson이라는 클래스를 @Service로 만들어서 따로 처리해주기로 했다.

@Service
public class MakeJson {
	
	@Autowired
	HosAdminDAO dao;
	
	public JSONObject dateAndListPrint(LocalDate date) {
		//xxxx-xx-xx형태로 날짜를 받아옴.
		
		//일단 출력할 날짜를 x월 x일 형태로 만들어줌.
		DateTimeFormatter df = DateTimeFormatter.ofPattern("M월 d일");
		String nowString = date.format(df);
	
		//그리고 json 데이터 만들어주기
		JSONObject jobj = new JSONObject();
		jobj.put("caldate", nowString);
		
		JSONArray jarray = new JSONArray();
		
		//날짜에 해당하는 list를 가져오기.
		List<ReservationDTO> dateList =  dao.selectDate(date.toString());
		
		for(ReservationDTO a : dateList) {
			JSONObject jobj2 = new JSONObject();
			jobj2.put("rno", a.getRno());
			jobj2.put("rdate", a.getRdate());
			jobj2.put("rtime", a.getRtime());
			jobj2.put("rname", a.getRname());
			jobj2.put("rtel", a.getRtel());
			jobj2.put("rremark", a.getRremark());
			jobj2.put("rstatus", a.getRstatus());
			jobj2.put("uno", a.getUno());
			jobj2.put("hno", a.getHno());
			jarray.add(jobj2);
		}
		jobj.put("callist", jarray);
		
		
		return jobj;
	}
}

그리고 컨트롤러에서는 이 json을 이런식으로 받아서 ajax에게 전해준다.

	@RequestMapping("/HospitalMainDatePlus")
	@ResponseBody
	public JSONObject datePlus(HttpServletResponse response, @RequestParam int hiddendate) {

		LocalDate dateadded = LocalDate.now().plusDays(hiddendate);
		
		JSONObject result = makejson.dateAndListPrint(dateadded);
	
		return result;
	}

jquery는 다음과 같이.

$.ajax({
		type : 'GET',
		url : '/HospitalMainDatePlus',
		data : {hiddendate : value},
		dataType : 'json',
		success : function(data){
			console.log("성공");
			console.log(data);
			
			//화면에 표시되는 날짜 변경
			console.log(data.caldate);
			$('#ddate').text(data.caldate);
			
			console.log(data.callist);
			
			//hidden 값 변경
			$('#datehidden').val(value);
		},
		error : function(){
			console.log("실패..");
		},
		complete : function(){
			console.log("완료");
		},
		beforeSend : function(){
			console.log("이제 보낼거다..")
		}
	});

받아온 값 html로 넣기

그렇지만 받아온 데이터는 jstl로 사용이 불가능하다...

서버의 작업 순서가 java -> jstl -> html -> javascript이기 때문.... 그런데 ajax는 javascript 부분이니까...

그래서 그냥 json 데이터를 처리해서 ajax의 success 내에서 html 코드로 넣어버리기로 했다.

즉, ajax의 경우에는

$.ajax({
		type : 'GET',
		url : '/HospitalMainDatePlus',
		data : {hiddendate : value},
		dataType : 'json',
		success : function(data){
			console.log("성공");
			console.log(data);
			
			//화면에 표시되는 날짜 변경
			console.log(data.caldate);
			$('#ddate').text(data.caldate);
			
			console.log(data.callist);
			var callist = data.callist;
			console.log(callist.length);
			var listcontent = "<table class= \"table\">"+
								"<tr>"+
									"<th>예약번호</th>"+
									"<th>시간</th>"+
									"<th>날짜</th>"+
									"<th>이름</th>"+
									"<th>연락처</th>"+
									"<th>특이사항</th>"+
								"</tr>";
			
			for(var i = 0; i < callist.length; i++){
				listcontent += "<tr>";
				listcontent += "<td>"+callist[i]['rno']+"</td>";
				listcontent += "<td>"+callist[i]['rtime']+"</td>";
				listcontent += "<td>"+callist[i]['rdate']+"</td>";
				listcontent += "<td>"+callist[i]['rname']+"</td>";
				listcontent += "<td>"+callist[i]['rtel']+"</td>";
				listcontent += "<td>"+callist[i]['rremark']+"</td>";
				listcontent += "</tr>";
			}
			listcontent += "</table>"
			console.log(listcontent);
			$('#ajaxresult').html(listcontent);
			
			//hidden 값 변경
			$('#datehidden').val(value);
		},
		error : function(){
			console.log("실패..");
		},
		complete : function(){
			console.log("완료");
		},
		beforeSend : function(){
			console.log("이제 보낼거다..")
		}
	});

 

html 부분에서는

<div id = "ajaxresult">
    <table class="table">
        <tr>
            <th>예약번호</th>
            <th>시간</th>
            <th>날짜</th>
            <th>이름</th>
            <th>연락처</th>
            <th>특이사항</th>
        </tr>

            <c:forEach var="dto" items="${dateResvRecord }">
                <tr>
                    <td>${dto.rno}</td>
                    <td>${dto.rtime}</td>
                    <td>${dto.rdate}</td>
                    <td>${dto.rname}</td>
                    <td>${dto.rtel}</td>
                    <td>${dto.rremark}</td>
                </tr>
            </c:forEach>

    </table>
</div>

이런식.


ajax 데이터 jsp로 뿌린 후에 해당 jsp채로 가져오기

굳이 위처럼 html로 일일이 만들어주지 않아도 된다!

ajax에서 받은 데이터를 다른 jsp에 그리고, 그 그려진 jsp를 뿌려주는 방식으로 사용이 가능하다고 한다!

 

일단 ajax에서 type은 post, dataType은 쓰지 말 것.

 

ajax 코드의 경우엔

$.ajax({
    type: 'post',
    url : '/HospitalMainDatePlus',
    data : {hiddendate : value},
    success : function(data){

        console.log("성공");
        console.log(data);
        $('#ajaxresult').html(data);
        $('#datehidden').val(value);
    },
    error : function(){
        console.log("실패..");
    },
    complete : function(){
        console.log("완료");
    },
    beforeSend : function(){
        console.log("이제 보낼거다..")
    }
});

 

그리고 위의 요청을 받는 컨트롤러는

@RequestMapping("/HospitalMainDatePlus")
@ResponseBody
public ModelAndView datePlus(HttpServletResponse response, @RequestParam int hiddendate, ModelAndView mav) {


    // hidden 값만큼 증가시킨 날짜->출력형식으로 바꿔서 model에 저장
    LocalDate dateadded = LocalDate.now().plusDays(hiddendate);
    DateTimeFormatter df = DateTimeFormatter.ofPattern("M월 d일");
    String dateresult = dateadded.format(df);
    mav.addObject("dateresult", dateresult);


    // 날짜에 해당하는 리스트를 model에 저장
    List<ReservationDTO> dateList = makejson.dateAndListPrint(dateadded);
    mav.addObject("dateList", dateList);

    mav.setViewName("hosAdmin/hopMainAjax");

    return mav;
}

 

컨트롤러에서 호출하는 view인 hopMainAjax의 코드는

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<div id = "ddate">${dateresult }</div>

<table class="table">
	<tr>
		<th>예약번호</th>
		<th>시간</th>
		<th>날짜</th>
		<th>이름</th>
		<th>연락처</th>
		<th>특이사항</th>
	</tr>

	<c:forEach items="${dateList }" var="data">
		<tr>
			<td>${data.rno}</td>
			<td>${data.rtime}</td>
			<td>${data.rdate}</td>
			<td>${data.rname}</td>
			<td>${data.rtel}</td>
			<td>${data.rremark}</td>
		</tr>
	</c:forEach>

</table>

이 때 한글 깨지므로 이 hopMainAjax.jsp에 UTF-8 넣어주어야 하고, jstl 태그도 여기에 넣어주어야 문제없이 ajax에 전송된다!

그러면 이 view 형태로 ajax가 반환을 받아서 html 형태로 해당 id 영역에 그대로 뿌려줌!