복습
https://shins99.tistory.com/104
[Spring Boot] DTO, DAO, Vo
복습 https://shins99.tistory.com/102 [Spring Boot] 스프링 부트에서 자주 사용하는 어노테이션 복습 https://shins99.tistory.com/97 [Spring Boot] 스프링 부트 시작하기( 기초 설정 방법) 복습 https://shins99.tistory.com/96 [
shins99.tistory.com
기본적으로는 어떤 패키지명을 사용하던지 상관이 없지만 dispatcher-servlet.xml에서 설정했던 고유의 명칭 방식은 따라야합니다. 저의 경우에는 com.s4c.stg로 시작하는 패키지를 만들겠다고 설정하였기 때문에 com.s4c.stg를 기반으로 db.ctr이라는 이름을 뒤에 더 붙여준 것입니다.
1. DAO 설정하기
DAO란 데이터를 조회하거나 조작하는 기능을 전담하도록 만든 오브젝트입니다. 저는 데이터베이스에 있는 사용자 데이터를 접근할 것이기에 com.s4c.stg.user.dao라는 패키지를 생성하고 그 안에 UserDAO.java를 만들어 DB에 접근하도록 하겠습니다.
[ UserDAO.java ]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
package com.s4c.stg.user.dao;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.s4c.stg.user.UserVO;
@Repository("userDAO")
public class UserDAO {
@Autowired
private SqlSession sqlSession;
private String Namespace = "com.s4c.stg.user.userMapper";
public List<UserVO> selectUser() throws Exception {
return sqlSession.selectList(Namespace+".selectUser");
}
}
|
@Repository("userDAO") 는 다른 클래스에서 이 클래스로 접근할 때 userDAO라는 이름을 사용하여 접근하겠다는 것이고, 우리가 datasource-sqlmap.xml에서 등록한 SqlSession 클래스에 접근하기 위해서 @Autowired를 적어주었습니다. 그리고 우리는 sql문을 적어둔 xml파일에 접근하여 그 Query문을 사용해 두어야 하는데, 저의 경우에는 userMapper.xml에 <mapper namespace="com.s4c.stg.user.userMapper">와 같이 적어두어서 UserDAO클래스에도 이 네임스페이스를 사용하여 selectUser라는 쿼리문을 호출하고 있습니다.
2. UserVO 설정하기
VO라는 것은 Value Object로 단순히 값을 저장하기 위한 객체를 의미합니다. 저 같은 경우에는 id, pw, money라는 데이터를 Database로 부터 가져와 출력할 것이기에 3가지 변수를 넣었고 com.s4c.stg.user라는 패키지 안에 클래스를 만들었습니다.
[ UserVO.java ]
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.s4c.stg.user;
public class UserVO {
private String id;
private String pw;
private int money;
public int getMoney() {
return money;
}
public void setMoney(int money) {
this.money = money;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getPw() {
return pw;
}
public void setPw(String pw) {
this.pw = pw;
}
}
|
우리가 userMapper.xml에 <select id="selectUser" resultType="userVO">을 명시해 두었는데, 여기서 userVO는 리가 mapper-config.xml에서 <typeAlias alias="userVO" type="com.s4c.stg.user.UserVO"/> 로 줄여말하기로 했던 UserVO.java파일이 됩니다.
3. Service 설정하기
이제 사용자의 명령을 호출하는 Service 클래스를 작성해 줄 차례입니다. 저는 com.s4c.stg.service라는 패키지 안에 java파일과 interface 파일을 추가하였습니다. 일반적으로 서비스를 위한 Java파일과 그 서비스를 구현하는 Interface파일을 독립적으로 구현합니다! UserService가 인터페이스고 UserServiceImpl이 인터페이스를 Implement하였다고 하여 UserServiceImpl이라고 이름지었습니다.
[ UserService.java ]
1
2
3
4
5
6
7
8
|
package com.s4c.stg.service;
import java.util.List;
import com.s4c.stg.user.UserVO;
public interface UserService {
public List<UserVO> selectUser() throws Exception;
}
|
[ UserServiceImpl.java ]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
package com.s4c.stg.service;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import com.s4c.stg.user.UserVO;
import com.s4c.stg.user.dao.UserDAO;
@Service("userService")
public class UserServiceImpl implements UserService {
@Resource(name="userDAO")
private UserDAO userDAO;
@Override
public List<UserVO> selectUser() throws Exception {
return userDAO.selectUser();
}
}
|
우다른 클래스에서 이 서비스를 호출할 때 이름을 userSerivce로 하겠다고 하여 @Service("userService")를 이 클래스에 적어두었고, 데이터베이스에 접근하는 역할은 DAO에서 담당하므로 DAO를 호출하여야 하는데, 우리가 참조하려는 자원의 이름을 @Resource(name="userDAO") 로 적어주었습니다.
4. Controller 설정하기
이제 뷰를 제어해줄 컨트롤러를 작성해줄 차례입니다. @RequestMapping을 통해서 어느 컨트롤러가 요청을 처리할지 알게 됩니다. 기본이 되는 컨트롤러로 HomeController를 작성해 주었으며 index.jsp에 의해 실행되도록 하고 Get 방식으로 처리하기기 위해 @RequestMapping(value="/", method = RequestMethod.GET)를 적어주었습니다.
[ HomeController.java ]
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
|
package com.s4c.stg.db.ctr;
import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
* Handles requests for the application home page.
*/
@Controller
public class HomeController {
private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
/**
* Simply selects the home view to render by returning its name.
*/
@RequestMapping(value = "/", method = RequestMethod.GET)
public String home(Locale locale, Model model) {
logger.info("Welcome home! The client locale is {}.", locale);
Date date = new Date();
DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
String formattedDate = dateFormat.format(date);
model.addAttribute("serverTime", formattedDate );
return "home";
}
}
|
[ DatabaseController.java ]
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
|
<p>package com.s4c.stg.db.ctr;
import java.util.List;
import java.util.Locale;
import javax.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.s4c.stg.service.UserService;
import com.s4c.stg.user.UserVO;
@Controller
public class DatabaseController{
private static final Logger logger = LoggerFactory.getLogger(DatabaseController.class);
@Resource(name="userService")
private UserService service;
/**
* Simply selects the home view to render by returning its name.
*/
@RequestMapping(value = "/db", method = RequestMethod.GET)
public String home(Locale locale, Model model) throws Exception{
logger.info("db");
List<UserVO> userList = service.selectUser();
model.addAttribute("userList", userList);
return "db";
}
}
</p>
|
index.jsp에서 하이퍼링크를 통해 db라는 페이지로 요청을 보내면 db.jsp 파일을 보여주기 위해서 @RequestMapping(value="/db", method = RequestMethod.GET) 를 해주었고, model에 userList를 추가하여 db를 return 하고 있습니다. 여기서 db를 return 한다는 것은 db.jsp의 화면을 보여주겠다는 의미입니다.
5. JSP 파일 설정하기
db.jsp 파일은 views의 폴더에 만들어주어야 합니다.
[ index.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">
<head>
<title>HelloWorld Index Page</title>
</head>
<body>
<center>
<h2>Hello World</h2>
<h3>
<a href="db">Click Here</a>
</h3>
</center>
</body>
|
[ db.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
|
<p><%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Home</title>
</head>
<body>
<h1>Hello world!<a href = "/">Click Here</a></h1>
<table>
<thead>
<tr>
<th>아이디</th>
<th>비밀번호</th>
<th>돈</th>
</tr>
</thead>
<tbody>
<c:forEach items="${userList}" var="user">
<tr>
<td>${user.id}</td>
<td>${user.pw}</td>
<td>${user.money}</td>
</tr>
</c:forEach>
</tbody>
</table>
</body>
</html>
</p>
|
6. 실행 화면
'[Spring Boot]' 카테고리의 다른 글
[Spring Boot] JPA (0) | 2023.10.18 |
---|---|
[Spring Boot] DTO, DAO, Vo (2) | 2023.10.15 |
[Spring Boot] 스프링 부트에서 자주 사용하는 어노테이션 (0) | 2023.10.13 |
[Spring Boot] 스프링 부트에서 자주 사용하는 어노테이션 (1) | 2023.10.12 |
[Spring Boot] 스프링 부트 시작하기( 기초 설정 방법) (0) | 2023.10.06 |