화면의 전환없이 데이터를 가져올 때 ajax 비동기 통신이 필요하다.
적용순서
Application.java 파일에 jsonView 설정 >Controller 단에서 비동기 거래 메소드 작성 > 화면에서 호출
1. Application.java 파일에 jsonView 설정
1) ajax 통신을 통해서 데이터를 전달받을 때
별도의 json 파싱 작업 없이 json 으로 받을 수 있도록 하는 설정을 해준다.
@Bean
MappingJackson2JsonView jsonView() {
return new MappingJackson2JsonView();
}
2. Controller 단에서 비동기 호출
1) 1 번에서 설정을 jsonView 를 활용하여 비동기 거래를 하는 컨트롤러를 작성한다.
2) @ResponseBody : http 요청에 대한 응답 body 를 자바 객체로 전달받을 수 있다.
ModelAndView 에 추가한 오브젝트 그대로 클라이언트 단 까지 전달해 준다.
// ajax 호출 테스트
@RequestMapping(value = "/sample/ajaxTest", method = {RequestMethod.GET, RequestMethod.POST})
@ResponseBody
public ModelAndView ajaxTest() {
ModelAndView mv = new ModelAndView();
mv.addObject("testJson", "ajaxTest");
mv.setViewName("jsonView");
return mv;
}
3. 화면 단에서 ajax 호출 스크립트 추가
1) 화면에서 호출할 수 있는 테스트 코드를 작성한다.
2) ajaxTest 버튼에 ajax 통신 함수를 호출한다.
3) $.ajax 에서 success (성공시 호출) 에서 console.log 를 찍어 컨트롤러 단에서 값을 제대로 받아왔는지 확인한다.
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<body>
<!-- Header -->
<div class="container-fluid">
<div class="row">
<!-- side.jsp -->
<div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main">
<h2 class="sub-header">Section title</h2>
<div class="table-responsive">
<table class="table table-striped">
<thead>
<tr>
<th>#</th>
<th>Header</th>
<th>Header</th>
<th>Header</th>
<th>Header</th>
</tr>
</thead>
<tbody>
<tr>
<td>1,001</td>
<td>Lorem</td>
<td>ipsum</td>
<td>dolor</td>
<td>sit</td>
</tr>
<tr>
<td>1,014</td>
<td>per</td>
<td>inceptos</td>
<td>himenaeos</td>
<td>Curabitur</td>
</tr>
<tr>
<td>1,015</td>
<td>sodales</td>
<td>ligula</td>
<td>in</td>
<td>libero</td>
</tr>
</tbody>
</table>
</div>
<!-- ajax 통신 함수를 호출하는 버튼 추가 -->
<div class="pull-right">
<button type="button" class="btn btn-sm btn-primary" onclick="ajaxTest();">ajax테스트</button>
</div>
<!--// ajax 통신 함수를 호출하는 버튼 추가 -->
</div>
</div>
</div>
</body>
<script type="text/javascript">
// ajax 통신 함수
function ajaxTest() {
$.ajax({
url: '/sample/ajaxTest',
type: 'post',
dataType: 'json',
data: {},
success: function(res){
// ajax 통신 성공시 호출
console.log(res);
}
});
}
</script>
4. 테스트
1) http://localhost:8080/sample/dashboard
2) ajax테스트 버튼을 클릭해서 콘솔 화면에 컨트롤러에서 설정한 오브젝트를 정상적으로 불러오는 지 확인한다.
'스프링부트+gradle+JSP+STS(Eclipse)' 카테고리의 다른 글
스프링부트 스프링시큐리티 비동기(ajax) 로그인 (4) | 2022.07.17 |
---|---|
스프링부트 부트스트랩(bootstrap) 적용하기 (0) | 2022.05.20 |
스프링부트 인터셉터(Interceptor) 설정 (0) | 2022.05.09 |
스프링부트 tiles(타일즈) 설정 (2) | 2022.05.09 |
Mysql 사용자 계정 생성 (0) | 2022.05.06 |
댓글