프로젝트 생성시 Spring Boot, DevTools, JDBC API, MySQL Driver, thymeleaf, SpringWeb을 dependencies에 넣는다.
appication.properties에 데이터 넣기
spring.datasource.url=jdbc:mysql:/아이피/test
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.username=아이디
spring.datasource.password=비밀번호
logging.level.root=warn
logging.level.org.springframwork.web=debug
spring.messages.encording=utf-8
- DB와 연결하기위한 세팅(현재 네이버 클라우드를 이용했음)
- logging level을 debug로 연결하기 위한 세팅
- 브라우저에서 한글을 출력하기위한 세팅
BootJdbcDemoApplication수정
@SpringBootApplication
@ComponentScan(basePackages = {"com.example"})
public class BootJdbcDemoApplication {
public static void main(String[] args) {
SpringApplication.run(BootJdbcDemoApplication.class, args);
}
}
main method가 있는 클래스만이 아닌 com.example안에 있는 모든 클래스 Component스캔을 위한 Annotaion 사용
CityVO 클래스생성
@Data
@AllArgsConstructor
@NoArgsConstructor
public class CityVO {
private int id;
private String name;
private String countryCode;
private String district;
private int population;
}
CityDao Interface 생성
public interface CityDao {
CityVO selectCity(String name);
List<CityVO> selectAllCitybyCountryCode(String countryCode);
}
CityDao Impl 클래스 생성(CityDao implements)
@Repository("cityDao")
public class CityDaoImpl implements CityDao {
@Autowired
private JdbcTemplate jdbcTemplate;
private class CityMapper implements RowMapper<CityVO>{
@Override
public CityVO mapRow(ResultSet rs, int rowNum) throws SQLException {
CityVO city = new CityVO(rs.getInt("id"), rs.getString("name"),
rs.getString("countryCode"), rs.getString("district"),
rs.getInt("population"));
return city;
}
}
@Override
public CityVO selectCity(String name) {
String sql = "SELECT ID, Name, CountryCode, District, Population FROM city " +
"WHERE name = ?";
return this.jdbcTemplate.queryForObject(sql, new CityMapper(), name);
}
@Override
public List<CityVO> selectAllCitybyCountryCode(String countryCode) {
String sql = "SELECT ID, Name, CountryCode, District, Population FROM city " +
"WHERE CountryCode = ?";
return this.jdbcTemplate.query(sql, new CityMapper(), countryCode);
}
}
jdbc template를 이용할 때 select문을 이용하려면 반드시 RowMapper를 이용하여 받아와야만 한다.
RowMapper안에 있는 메소드 mapRow를 이용하며 메소드를 여러번 실행할 것인지 한번만 실행할 것인지를 알아서 사용할 수 있다.
jdbc template를 이용하여 하나의 데이터를 가져올 때에는 리턴타입이 T라고 되어있는 것을 쓰면 되는데 그 중 queryforObject를 이용하였고 list형식으로 되어있는 데이터를 가져올 때는 리턴타입이 List<T>인 메소드를 이용하면 되는데 그 중 query라는 메소드를 이용하였다.
CityService Interface 생성
public interface CityService {
CityVO red(String name);
List<CityVO> readAll(String countryCode);
}
db연동은 repository
service의 역할은 controller와 repository를 연결과 비즈니스로직을 처리해줌
CityServiceImpl 클래스 생성(CityService implements)
@Service("cityService")
public class CityServiceImpl implements CityService {
@Autowired
private CityDao cityDao;
@Override
public CityVO read(String name) {
return this.cityDao.selectCity(name);
}
@Override
public List<CityVO> readAll(String countryCode) {
return this.cityDao.selectAllCitybyCountryCode(countryCode);
}
}
controller로 받은 list들을 dao에 보내준다.
CityController 클래스생성
@RestController
@Slf4j
public class CityController {
@Autowired
private CityService cityService;
@GetMapping("/")
public String list(Model model) {
List<CityVO> list = this.cityService.readAll("KOR");
list.forEach(city -> log.info(list.toString()));
return "hi";
}
@GetMapping("/{name}")
public String listByName(@PathVariable String name) {
CityVO city = this.cityService.read(name);
System.out.println(city.toString());
return "hi";
}
}
console창에서 확인하기위한 매소드임으로 리턴은 신경 x
/{name}은 pathvariable로 받기위해 사용
map을 이용하는 방법
@Autowired
private CityService cityService;
@GetMapping("/")
public Map list() {
Map<String, Object> map = new HashMap<String, Object>();
List<CityVO> list = this.cityService.readAll("KOR");
map.put("results", list);
return map;
}
@GetMapping("/{name}")
public Map listByName(@PathVariable String name) {
Map<String, Object> map = new HashMap<String, Object>();
CityVO city = this.cityService.read(name);
map.put("city", city);
return map;
}
Restfulapi를 이용하기위해서는 map을 사용해야한다.
받아온 list들을 맵을 이용하여 jason형태로 나타낼 수 있다.
ajex를 사용할 때에는 무조건 map을 이용하여야하기 때문에 restfulapi에 대해서 잘 알아두는 것이 도움이 된다.
html로 확인하기
CityController.java 수정
@Controller
@Slf4j
public class CityController {
@Autowired
private CityService cityService;
@GetMapping("/")
public String list(Model model) {
List<CityVO> list = this.cityService.readAll("KOR");
model.addAttribute("cities", list);
return "list";
}
@GetMapping("/{name}")
public Map listByName(@PathVariable String name) {
Map<String, Object> map = new HashMap<String, Object>();
CityVO city = this.cityService.read(name);
map.put("city", city);
return map;
}
}
페이지로 넘겨주기위해서 @Controller로 바꿔주고 리턴타입을 String으로 바꿔준다.
webjar이용하기
<dependency>
<groupId>org.webjars</groupId>
<artifactId>bootstrap</artifactId>
<version>3.4.1</version>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>3.6.0</version>
</dependency>
이전에는 폴더에 직접 넣어서 bootstrap과 jquery를 이용했지만 webjar를 통해서 별도의 설치없이 사용이 가능하다.
index.html
<!DOCTYPE html>
<html lang="en" xmlns:th="https://www.thymeleaf.org">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>wwww.example.com</title>
<link rel="stylesheet" th:href="@{/webjars/bootstrap/3.4.1/css/bootstrap.min.css}" />
<script th:src="@{/webjars/jquery/3.6.0/jquery.min.js}"></script>
</head>
<body>
<div class="container">
<div class="row">
<h1 class="text-center">World cities</h1>
<table class="table table-hover">
<thead>
<td>일련번호</td>
<td>도시이름</td>
<td>국가코드</td>
<td>지역</td>
<td>도시인구</td>
</thead>
<tbody>
<tr th:each="city : ${cities}">
<td th:text="${city.id}"></td>
<td><a th:href="@{/{name}(name=${city.name})}" th:text="${city.name}"></a></td>
<td th:text="${city.countryCode}"></td>
<td th:text="${city.district}"></td>
<td th:text="${city.population}"></td>
</tr>
</tbody>
</table>
</div>
</div>
</body>
</html>
bootstrap을 이용하여 테이블의 css를 해결하였고 경로는 maven dependensies에서 확인이 가능하다.
@{}를 이용하여 링크를 사용하였고 {name}뒤에는 name에 어떤 값이 들어가는지를 넣었다.
class명 | 설명 |
container | 테이블을 페이지 가운데로 모아 여백을 만들 수 있음 |
table-hober | 커서에 올려논 테이블의 위치를 부각시켜주는 역할 |
detail.html
<!DOCTYPE html>
<html lang="en" xmlns:th="https://www.thymeleaf.org">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>wwww.example.com</title>
<link rel="stylesheet" th:href="@{/webjars/bootstrap/3.4.1/css/bootstrap.min.css}" />
<script th:src="@{/webjars/jquery/3.6.0/jquery.min.js}"></script>
</head>
<body>
<div th:object="${city}">
<h1 th:text="*{name}"></h1>
<ul>
<li>번호 : <span th:text="*{id}"></span></li>
<li><span th:text="*{countryCode}"></span></li>
<li><span th:text="*{district}"></span></li>
<li><span th:text="*{population}"></span></li>
</ul>
</div>
</body>
</html>
'SpringBoot 코딩' 카테고리의 다른 글
8. RestFulApi를 이용한 프로젝트만들기, war packaging 진짜 Tomcat사용하기 (demo) (0) | 2021.12.09 |
---|---|
7.2 Mybatis와 hikariCP를 이용한 프로젝트 만들기(BootJdbcDemo) (0) | 2021.11.26 |
5. Thymeleaf사용하기 (templatedemo) (0) | 2021.11.24 |
4. 정적페이지를 이용한 SpringBoot Project(spring web) (0) | 2021.11.23 |
3. spring initializr을 이용한 project만들기(demo) (0) | 2021.11.23 |