티스토리 뷰

처음 하는 스프링(Spring), mybatis와 Dao에 이어서.

천천히 뜯어보기, 두 번째

1. Service
Service의 역할은 Dao가 DB에서 받아온 데이터를 전달받아 가공하는 것이다.
다양한 예시가 있겠지만, 아주 간단한 예시를 통해서 느낌 정도만 알아보도록 하자.

가령, DB에서 가져온 데이터에, 프로그램의 용도에 따라 특정한 문자열을 추가하는 기능이 필요하다고 가정해보자. 예시로 "가공된(SampleServiceImpl을 거친) "이라는 문자열을 추가해보겠다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

package com.first.begin.sample.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.first.begin.sample.dao.SampleDao;
@Service("sampleService")
public class SampleServiceImpl implements SampleService {
@Autowired
protected SampleDao sampleDao;
@Override
public String selectSampleData() throws Exception {
String serviceTest = sampleDao.selectSampleData();
// Business Logic
serviceTest = "가공된(SampleServiceImpl을 거친) " + serviceTest;
return serviceTest;
}
}
cs

8번째 줄을 통해 Service 역할을 하는 빈이라고 선언해주었다.
11~12번째 줄은 Dao와 마찬가지로 인터페이스를 통해 추후의 확장성을 고려한 느슨한 연결을 해주었다.
14~22번째 줄에서 Dao가 가져온 데이터에 특정 문자열을 추가하는, 이번 Service의 핵심 로직을 만들어주었다.

2. Controller
다음은 우리의 시스템으로 들어오는 요청과 응답을 담당할 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

package com.first.begin.sample.controller;
import javax.annotation.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.first.begin.sample.service.SampleService;
@Controller
public class SampleController {
@Resource(name="sampleService")
private SampleService sampleService;
@RequestMapping("/sample.bgn")
public ModelAndView sampleView(ModelAndView mv) throws Exception {
mv.addObject("sampleAttribute", sampleService.selectSampleData());
mv.setViewName("sample");
return mv;
}
}
cs

11~15번째 줄까지는 앞서 봐왔던 것처럼 비슷한 의미의 내용이다.
17번째 줄을 풀어서 말해보자면, 루트 URL(로컬을 기준으로 하면 localhost:8080)의 하위에 "/sample.bgn"이라는 요청이 들어오면 아래 메소드로 매핑(담당) 시켜주겠다는 말이다.
18번째 줄에서는 ModelAndView 타입으로 메소드를 선언해주었는데, 데이터(Model)와(And) 보여줄 화면(View)을 함께 처리할 수 있는 타입이다.
이제 Dao, Service를 거쳐온 데이터를 화면에 전달하는 일만 남았다.
19번째 줄에서 전달할 데이터의 이름(key)와 값(value)을, 20번째 줄에서 화면의 이름을 각각 ModelAndView에 담아서 리턴해주면 Controller의 역할이 끝난다.

3. JSP
이제 마지막으로 결과 화면을 보도록 하자.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>
Begin Project!
</h1>
<P> "처음 만든 버튼"을 누르셨습니다! </P>
<p> DB 조회 결과 : ${sampleAttribute} </p>
</body>
</html>
cs

Controller에서 정해준 데이터의 이름(key)을 통해 값을 화면으로 불러와서 데이터가 잘 가공됐는지 확인하자.

결과

(끝)

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/10   »
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
글 보관함