AJAX 란
- XMLHttpRequest 기술을 사용하여 동적인 웹페이지 구성하는 프로그래밍 방식
- 전체 페이지를 다시 로드하지 않고 페이지 일부 DOM만 업데이트
- 페이지 일부가 로드되는 동안에도 코드가 계속 실행되어 비동기식으로 작업 가능
- (mdn)[https://developer.mozilla.org/ko/docs/Glossary/AJAX]
JSON 라이브러리
JSON
let obj = { name:'scott', age:20 }
let str = JSON.stringfy(obj);
let emp = JSON.parse(str);
Jackson
ObjectMapper
ObjectMapper objectMapper = new ObjectMapper();
String empAsString objectMapper.writeValueAsString(empVO);
EmpVO vo = objectMapper.readValue(str, EmpVO.class);
Jackson annotation
- @RequestBody, @ResponseBody
public @ResponseBody List<EmpVO> findEmp( @RequestBody EmpVO empVO) {}
- @JsonProperty, @JsonFormat, @JsonIgnore, @JsonIgnoreProperties, @JsonPropertyOrder
import java.util.Date;
import com.fasterxml.jackson.annotation.*;
import lombok.*;
@Data @Builder @AllArgsConstructor @NoArgsConstructor
@JsonPropertyOrder({ "lastName", "firstName", "salary" })
@JsonIgnoreProperties({"salary","dept"})
public class EmpVO {
private String firstName;
@JsonProperty("lname")
private String lastName;
private String dept;
private int salary;
@JsonFormat(
shape = JsonFormat.Shape.STRING,
pattern = "dd-MM-yyyy hh:mm:ss")
private Date hireDate;
@JsonIgnore
private int commission;
}
public class JacksonTest {
@Test
public void test() throws JsonProcessingException {
EmpVO vo = EmpVO.builder().firstName("scott")
.lastName("king")
.dept("개발")
.salary(2000)
.hireDate(new Date())
.commission(100)
.build();
String str = new ObjectMapper().writeValueAsString(vo);
System.out.println(str);
}
}
{"lname":"king","firstName":"scott","hireDate":"18-11-2024 11:13:46"}
AJAX 라이브러리
- XMLHttpRequest 객체
- Javascript(web api) fetch() 함수
- jQuery $.ajax() 함수
- axios() 함수
fetch() VS $.ajax()
- get 방식
fetch(url + "?var=value").then();
$.ajax(url + "?var=value").done();
$.ajax(url, {data: "var=value"}).done();
$.ajax(url, {data: {var:"value"}).done();
- post(queryString)
fetch(url, {method:'post', body: "fv=val&sv=val" }).then()
$.ajax(url, {method:'post', data: "fv=val&sv=val" }).done()
$.ajax(url, {method:'post', data: {"fv":"val", "sv":"val" } }).done()
- post(jsonString)
let data = {"fv":"val", "sv":"val" }
fetch(url, {method: 'post',
headers: { "Content-Type": "application/json", },
body: JSON.stringify(data)
}).then()
$.ajax(url, {method: 'post',
contentType : "application/json",
data: JSON.stringify(data)
}).done()
ajax 와 spring 연동
queryStr = "firstName=scott&lastName=king"
queryStr = "emps[0].firstName=scott&emps[0].lastName=king&emps[1].firstName=scott&emps[1].lastName=king"
jsonStr = {firstName: 'scott', lastName: 'king'}
jsonArr = [{firstName:"scott", lastName:"king"},{firstName:"james", lastName:"park"}]
public String handler(EmpVO vo) {}
public String handler(ListEmpVO list) {}
public String handler(@RequestBody EmpVO vo) {}
public String handler(@RequestBody List<EmpVO> vo) {}
class ListEmpVO {
List<EmpVO> emps;
}