2021. 1. 9. 14:36
pom.xml
<!-- json bind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.5.1</version>
</dependency>
servlet-context.xml
<beans:bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"
@ResponseBody
@RequestMapping(생략...)
public Map returnJson(@RequestBody HashMap<String, String> map)
{
//@RequestBody로 JSON형식을 받을 수 있고
for(Entry<String, String> entry : map.entrySet())
{
System.out.println(String.format("key: %s, val: %s", entry.getKey(), entry.getValue()));
}
//결과를 여러개 담으려면?
List<Map<String, String>> allrst = new ArrayList<Map<String,String>>();
//첫번째 결과 생성
Map<String, String> eachrst = null;
eachrst = new HashMap<String, String>();
eachrst.put("name", "홍길동");
eachrst.put("age", "10");
//첫번째 결과를 리스트에 저장
allrst.add(eachrst);
//두번째 결과 생성
eachrst = new HashMap<String, String>();
eachrst.put("name", "김길동");
eachrst.put("age", "11");
//두번쨰 결과 리스트에 저장
allrst.add(eachrst);
//@ResponseBody로 JSON형식을 리턴해줄 수 있다.
Map<String, Object> result = new HashMap<String, Object>();
result.put("result", allrst);
return result;
}
javascript 에서 비동기통신으로 요청 예
function test()
{
fetch(url, {
method:"POST",
headers:{
"Content-Type" : "application/json;charset=utf-8"
},
body: JSON.stringify({
전달 파라미터1 : 값,
전달 파라미터2 : 값,
})
})
.then(resp => resp.json())
.then(function(res){
//요청한 응답을 res 파라미터로 리턴받음
var rst = res.result; //res의 첫 노드 이름이 result. 컨트롤러에서 arraylist 를 저장한 키
//하나씩 꺼내는 방법
rst.forEach(function(items){
console.log("이름 : " + items.name + "\n나이 : " + items.age);
})
})
.catch(err => console.log(err));
}
'Spring Framework > Spring' 카테고리의 다른 글
[Intellij] 3. Spring MVC 에 Maven 추가 (0) | 2021.02.17 |
---|---|
[Intellij] 2. Spring MVC 프로젝트 설정 (0) | 2021.02.17 |
[Spring] 컨트롤러에서 파라미터를 받는 방법 (0) | 2021.01.07 |
[spring] 2. 한글 처리 filter (web.xml) (0) | 2020.06.09 |
[Spring] 의존 주입 - 작성중 (0) | 2020.04.21 |