▶ 스프링 MVC 기반의 컨트롤러(Controller) 클래스를 정의한 것입니다.
이 컨트롤러 클래스는 웹 애플리케이션에서 사용자 요청에 따라 다양한 화면을 보여주기 위한 역할을 합니다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
package com.gdu.app07.Controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
public class MvcController {
@RequestMapping(value="/", method=RequestMethod.GET)
public String index() {
return "index";
}
@RequestMapping(value="/ajax1.do", method=RequestMethod.GET)
public String ajax1() {
return "ajax1";
}
@RequestMapping(value="/ajax2.do", method=RequestMethod.GET)
public String ajax2() {
return "ajax2";
}
@RequestMapping(value="/ajax3.do", method=RequestMethod.GET)
public String ajax3() {
return "ajax3";
}
}
|
cs |
▶ AjaxDto
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
package com.gdu.app07.Dto;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@NoArgsConstructor
@AllArgsConstructor
@Data
public class AjaxDto {
private String name;
private int age;
}
|
cs |
▶ DAO 클래스는 데이터베이스에서 데이터를 가져오거나 저장하는 역할을 수행합니다.
AjaxDto 객체: 이 DAO 클래스 내에서 사용할 데이터 객체 AjaxDto인 a, b, c를 멤버 변수로 선언했습니다.
setBean 메서드: @Autowired 어노테이션이 부여된 setBean 메서드를 통해 AjaxDto 객체들을 주입받습니다. 이 메서드는 스프링 컨테이너가 관리하는 AjaxDto 빈들을 주입받아서 클래스 내의 a, b, c 멤버 변수에 할당합니다.
getDtoList 메서드: DAO에서 관리하는 AjaxDto 객체들을 리스트로 반환합니다. 이 메서드는 주입받은 AjaxDto 객체들을 배열로 만들어서 리스트로 변환한 후 반환합니다.
getDto 메서드: 지정된 번호에 해당하는 AjaxDto 객체를 반환합니다. 번호에 따라 a, b, c 중 하나의 AjaxDto 객체를 반환합니다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
|
package com.gdu.app07.Dao;
import java.util.Arrays;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.gdu.app07.Dto.AjaxDto;
@Repository
public class AjaxDao {
private AjaxDto a;
private AjaxDto b;
private AjaxDto c;
@Autowired
public void setBean(AjaxDto a, AjaxDto b, AjaxDto c) {
this.a = a;
this.b = b;
this.c = c;
}
public List<AjaxDto> getDtoList() {
return Arrays.asList(a, b, c);
}
public AjaxDto getDto(int no) {
AjaxDto dto = null;
if(no == 1) {
dto = a;
} else if (no == 2) {
dto = b;
} else if (no == 3) {
dto = c;
}
return dto;
}
}
|
cs |
▶ XML 구성 파일은 스프링 프레임워크에서 사용하는 빈(Bean) 설정 파일입니다.
빈 설정 파일은 스프링 애플리케이션에서 사용되는 객체들을 정의하고 구성하는데 사용됩니다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- Root Context: defines shared resources visible to all other web components -->
<bean class="com.gdu.app07.Dto.AjaxDto" id="a">
<property name="name" value="뽀로로"/>
<property name="age" value="20"/>
</bean>
<bean class="com.gdu.app07.Dto.AjaxDto" id="b">
<property name="name" value="루피"/>
<property name="age" value="22"/>
</bean>
<bean class="com.gdu.app07.Dto.AjaxDto" id="c">
<property name="name" value="크롱"/>
<property name="age" value="10"/>
</bean>
</beans>
|
cs |
▶ AjaxService 인터페이스
getDtoList( ) : AjaxDto 객체들의 목록을 반환하는 메서드입니다.
getDto(String name) : 이름을 기준으로 특정 AjaxDto 객체를 반환하는 메서드입니다.
1
2
3
4
5
6
7
8
9
10
11
|
package com.gdu.app07.Service;
import java.util.List;
import com.gdu.app07.Dto.AjaxDto;
public interface AjaxService {
public List<AjaxDto> getDtoList();
public AjaxDto getDto(String name);
}
|
cs |
▶ AjaxServiceImpl 클래스
private final AjaxDao ajaxDao : AjaxDao 객체를 주입받습니다.
구현된 메서드들은 주로 AjaxDao에게 데이터 접근을 위임하는 역할을 합니다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
|
package com.gdu.app07.Service;
import java.util.List;
import org.springframework.stereotype.Service;
import com.gdu.app07.Dao.AjaxDao;
import com.gdu.app07.Dto.AjaxDto;
import lombok.RequiredArgsConstructor;
@Service
@RequiredArgsConstructor
public class AjaxServiceImpl implements AjaxService {
private final AjaxDao ajaxDao;
@Override
public List<AjaxDto> getDtoList() {
return ajaxDao.getDtoList();
}
@Override
public AjaxDto getDto(String name) {
int no = 0;
if(name.equals("뽀로로")) {
no = 1;
} else if(name.equals("루피")) {
no = 2;
} else if(name.equals("크롱")) {
no = 3;
}
return ajaxDao.getDto(no);
}
}
|
cs |
▶ AjaxController1 클래스
RequestMapping: 해당 메서드를 특정 HTTP 요청과 매핑하고, 응답 데이터 타입을 설정합니다. /list.do는 Ajax로 데이터를 가져오는 엔드포인트, /detail.do는 특정 데이터의 상세 정보를 가져오는 엔드포인트를 나타냅니다.
list() 메서드:
ajaxService.getDtoList(): 서비스 레이어의 ajaxService를 통해 데이터를 가져와서 JSON 형태로 반환합니다. 이 데이터는 클라이언트에게 응답으로 전달됩니다.
detail() 메서드:
@RequestParam(value="name") String name: 요청 파라미터로부터 name 값을 받아옵니다.
ajaxService.getDto(name): 서비스 레이어의 ajaxService를 통해 특정 데이터를 가져와서 JSON 형태로 반환합니다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
|
package com.gdu.app07.Controller;
import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.gdu.app07.Dto.AjaxDto;
import com.gdu.app07.Service.AjaxService;
import lombok.RequiredArgsConstructor;
@RequestMapping("/ajax1")
@RequiredArgsConstructor
@Controller
public class AjaxController1 {
private final AjaxService ajaxService;
@ResponseBody // 메서드의 반환 값이 데이터이다.
@RequestMapping(value="/list.do", method=RequestMethod.GET, produces = "application/json; charset=UTF-8") // produces : 응답 데이터 타입
public List<AjaxDto> list() {
return ajaxService.getDtoList(); // jackson 라이브러리가 List<Dto1>를 json 데이터로 자동 변환한다.
}
@ResponseBody
@RequestMapping(value="/detail.do", method=RequestMethod.GET, produces= "application/json; charset=UTF-8")
public AjaxDto detail(@RequestParam(value="name") String name) {
System.out.println(name);
return ajaxService.getDto(name);
}
}
|
cs |
▶ Ajax.jsp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
|
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<c:set var="contextPath" value="${pageContext.request.contextPath}" />
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://code.jquery.com/jquery-3.7.1.min.js" integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo=" crossorigin="anonymous"></script>
<script>
$(function(){
fnList();
fnDetail();
})
function fnList() {
$('#btn_list').click(function(){
$.ajax({
// 요청
type: 'get',
url: '${contextPath}/ajax1/list.do',
// 응답
dataType: 'json',
success: function(resData) {
$('#list').empty();
$.each(resData, function(i, elem){
$('#list').append( '<div class="row"><span>' + elem.name + '</span>,' + elem.age + '</div>');
})
}
})
})
}
function fnDetail() {
$(document).on('click', '.row', function(){
$.ajax({
//요청
type: 'get',
url : '${contextPath}/ajax1/detail.do',
data: 'name=' + $(this).find('span').text(),
//응답
dataType: 'json',
success: function(resData){
alert(resData.name + ',' + resData.age);
}
})
})
}
</script>
</head>
<body>
<div>
<button id="btn_list">목록보기</button>
</div>
<hr>
<div id="list"></div>
</body>
</html>
|
cs |
'코딩기록 저장소 🐕 > spring(JPA)🌱' 카테고리의 다른 글
jdbcJunitTest (0) | 2023.10.10 |
---|---|
Spring ajax2 (0) | 2023.10.06 |
Spring DI 2 (0) | 2023.10.05 |
Spring DI (0) | 2023.10.04 |
Spring Mvc 복습, Mvc Redirect (0) | 2023.10.04 |