스프링 ajax 사용법 (응답데이터 하나/다수일경우)
2022. 1. 25. 20:19ㆍFramework
반응형
ajax로 값 전달하고 응답 결과 받기
** 응답데이터가 하나일 경우
@jsp
이름 : <input type="text" id="name"> <br>
나이 : <input type="number" id="age"> <br>
<button onclick="test1();">전송</button>
<div id="result1"></div>
<script>
/*
$("#btn").click(function(){
})
*/
function test1(){
$.ajax({
url:"ajax1.do",
data:{
name:$("#name").val(),
age:$("#age").val()
},success:function(result){
console.log(result);
$("#result1").text(result);
},error:function(){
console.log("ajax통신 실패");
}
});
}
@ajaxController
@Controller
public class AjaxController {
/*
* 1. HttpServletResponse 객체로 응답데이터 응답하기
* (기존의 jsp/servlet때 했던 Stream을 이용)
*/
@RequestMapping("ajax1.do")
public void ajaxMethod1(String name, int age, HttpServletResponse response) throws IOException {
System.out.println(name);
System.out.println(age);
String responseData = "응답데이터 : " + name + "은(는) " + age + "살";
response.setContentType("text/html; charset=UTF-8");
response.getWriter().print(responseData);
}
/*
* 2. 응답할 데이터를 문자열로 리턴
* => HttpServletResponse를 사용하지 않아도 됨
* 단, 문자열 리턴하면 포워딩 방식으로 응답뷰를 찾으려고 하는데
* 응답뷰가 아니라 단순한 응답데이터라고 선언해주는 어노테이션 @ResponseBody을 이용
*/
@ResponseBody
@RequestMapping(value="ajax1.do", produces="text/html; charset=UTF-8")
public String ajaxMethod1(String name, int age) {
String responseData = "응답데이터 : " + name + "은(는) " + age + "살";
return responseData;
}
** 응답데이터가 다수일 경우
@jsp
이름 : <input type="text" id="name"> <br>
나이 : <input type="number" id="age"> <br>
<button onclick="test1();">전송</button>
<div id="result1"></div>
<script>
function test1(){
$.ajax({
url:"ajax1.do",
data:{
name:$("#name").val(),
age:$("#age").val()
},success:function(result){
console.log(result);
// 방법1. JSONArray로 담아서 응답
// 응답데이터가 배열의 형태일 경우 => 인덱스에 접근 가능 => [인덱스]
/*
let value = "이름: " + result[0] + "<br>나이: " + result[1];
$("#result1").html(value);
*/
// 방법2. JSONObject로 담아서 응답
// 응답데이터가 단순 객체 형태일 경우 => 속성에 접근 가능 => .속성명
let value = "이름: " + result.name + "<br>나이: " + result.age;
$("#result1").html(value);
},error:function(){
console.log("ajax통신 실패");
}
});
}
</script>
@Controller
@RequestMapping("ajax1.do")
public void ajaxMethod1(String name, int age, HttpServletResponse response) throws IOException {
// 요청처리가 다 됐다는 가정하에 데이터 응답
/*
response.setContentType("text/html; charset=UTF-8");
response.getWriter().print(name);
response.getWriter().print(age);
// 다수의 출력데이터가 하나의 문자열로 연이어져 출력 != 다수의 데이터 따로 출력
*/
// JSON(JavaScript Object Notation)형태로 담아서 응답
// JSONArray => [값, 값, 값, ..] => 자바에서의 ArrayList와 유사
// JSONObject => {키:값, 키:값, ..} => 자바에서의 HashMap과 유사
// 방법1. JSONArray로 담아서 응답
/*
JSONArray jArr = new JSONArray();
jArr.add(name); // ["이훈이"]
jArr.add(age); // ["이훈이", 5]
response.setContentType("application/json; charset=UTF-8");
response.getWriter().print(jArr);
*/
// 방법2. JSONObject로 담아서 응답
JSONObject jObj = new JSONObject(); // {}
jObj.put("name", name); // {name: '이훈이'}
jObj.put("age", age); // {name: '이훈이', age: 5}
response.setContentType("application/json; charset=UTF-8");
response.getWriter().print(jObj);
}
// 위 메소드처럼 HttpServletResponse 사용 시 => void
// HttpServletResponse 사용하지 않는 메소드 => String 반환 & @ResponseBody
@ResponseBody
@RequestMapping(value="ajax1.do", produces="application/json; charset=UTF-8")
public String ajaxMethod1(String name, int age) {
JSONObject jObj = new JSONObject(); // {}
jObj.put("name", name); // {name: '이훈이'}
jObj.put("age", age); // {name: '이훈이', age: 5}
return jObj.toJSONString();
// jObj는 object객체타입이라 String타입으로 변환하기 위해 toJSONString()메소드 이용
}
json 이용하기 위해서 mvn리포지토리에서
json 검색 후 pom.xml에 디펜던시 복붙
반응형
'Framework' 카테고리의 다른 글
스프링 인터셉터로 권한체크 (0) | 2022.01.27 |
---|---|
ajax vo객체 한 행/여러 행 조회, json을 gson으로 (0) | 2022.01.25 |
스프링 첨부파일 업로드 (0) | 2022.01.24 |
비밀번호 암호화(Bcrypt방식)로 회원가입, 로그인 작업 (0) | 2022.01.17 |
Lombok 롬복 설치 (0) | 2022.01.15 |