dev.Log
Servlet, Spring, Springboot에서 view단에 json보내주는법 본문
1.Servlet에서는 GSON사용
2.Spring에서는 @ResponseBody Map객체활용
JSON->MAP
@Controller
public class MainController {
// home.jsp
@RequestMapping(value = "/", method = RequestMethod.GET)
public String home() {
return "home";
}
@ResponseBody
@RequestMapping(value = "/test", method = RequestMethod.POST)
public void init(@RequestBody HashMap<String, Object> map) {
System.out.println(map);
// {name=kim, age=30} 출력
}
}
JSON -> 객체
@Controller
public class MainController {
// home.jsp
@RequestMapping(value = "/", method = RequestMethod.GET)
public String home() {
return "home";
}
@ResponseBody
@RequestMapping(value = "/test", method = RequestMethod.POST)
public void init(@RequestBody UserVO userVO) {
userVO.getName(); // "kim"
userVO.getAge(); // 30
}
}
*물론 Spring에서도 GSON사용가능하다 (https://webcoding.tistory.com/entry/Spring-%EC%8A%A4%ED%94%84%EB%A7%81%EC%97%90%EC%84%9C-Gson%EC%9D%84-%EC%9D%B4%EC%9A%A9%ED%95%98%EC%97%AC-ajax-%ED%86%B5%EC%8B%A0%ED%95%98%EA%B8%B0)
3.SpringBoot @RestController로 바로해결 (@RestController == Spring의 @Controller + @ResponseBody 역할)
@RestController
public class HelloController {
@GetMapping(path = "/hello-world-bean")
public HelloBean helloWorldBean(){
return new HelloBean("Hello World"); //json형식으로 반환
}
}
{
"message": "Hello World"
}
'BACKEND.*' 카테고리의 다른 글
Spring Boot (API)- ResponseEntity (0) | 2020.07.14 |
---|---|
mysql workbench - table data import wizard 오류해결 (0) | 2020.07.13 |
Servlet에서 로그확인하기 (0) | 2020.07.09 |
Mybatis (0) | 2020.07.09 |
Redis (0) | 2020.07.09 |
Comments