list0.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
<style>
div.container {width:900px; margin: 50px auto;}
thead th {background-color: #eee;}
table {border-collapse: collapse; width:100%;}
td,th{padding 4px; border: 1px solid lightgray;}
td {text-align: center;}
input{padding:5px; font-size:10pt;}
button {margin:10px; padding:0.4em 2em;}
tr[data-url]:hover {background-color: #ffb; cursor:pointer;}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">
</script>
</head>
<body>
<div class="container">
<h1>책 목록</h1>
<form>
<label>이름</label> <input type="text" name="srchText"
value="${srchText}" placeholder="검색조건" />
<button type="submit">조회</button>
</form>
<table>
<thead>
<tr>
<th>id</th>
<th>제목</th>
<th>저자</th>
<th>출판사</th>
<th>카테고리</th>
<th>가격</th>
</tr>
</thead>
<tbody>
<c:forEach var="book" items="${books}">
<tr data-url="detail?id=${book.id}">
<td>${book.id}</td>
<td>${book.title}</a></td>
<td>${book.author}</td>
<td>${book.publisher}</td>
<td>${book.categoryName}</td>
<td>${book.price}</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
<script>
$("[data-url]").click(function() {
var url = $(this).attr("data-url");
location.href = url;
})
</script>
</body>
</html>
detail.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
<style>
div.container { width: 600px; margin: 50px auto; }
body { font-family: 굴림체; }
table { width: 500px; border-collapse: collapse; }
table td:nth-child(1) { background-color: #eee; }
td { padding: 5px; border: 1px solid lightgray; }
</style>
</head>
<body>
<div class="container">
<h1>책목록</h1>
<table>
<tr>
<td>ID</td>
<td>${book.id}</td>
</tr>
<tr>
<td>제목</td>
<td>${book.title}</td>
</tr>
<tr>
<td>저자</td>
<td>${book.author}</td>
</tr>
<tr>
<td>카테고리ID</td>
<td>${book.categoryId}</td>
</tr>
<tr>
<td>카테고리</td>
<td>${book.categoryName}</td>
</tr>
<tr>
<td>가격</td>
<td>${book.price}</td>
</tr>
</table>
<a href="javascript:window.history.back()">돌아가기</a>
</div>
</body>
</html>
BookController.java
package net.skhu.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import net.skhu.mapper.BookMapper;
@Controller
public class BookController {
@Autowired BookMapper bookMapper;
@RequestMapping("book/list")
public String list(Model model) {
model.addAttribute("books",bookMapper.findAll());
return "book/list";
}
@RequestMapping("book/detail")
public String detail(Model model,Integer id) {
if(id==null) id = 3;
model.addAttribute("book",bookMapper.findById(id));
return "book/detail";
}
@RequestMapping ("book/list0")
public String list0(Model model,String srchText) {
if(srchText==null)srchText="";
model.addAttribute("books",bookMapper.findByTitle(srchText+"%"));
model.addAttribute("srchText",srchText);
return "book/list0";
}
}
Book.java
package net.skhu.dto;
public class Book {
int id;
String title;
String author;
String categoryName;
int categoryId;
int price;
String publisher;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getCategoryName() {
return categoryName;
}
public void setCategoryName(String categoryName) {
this.categoryName = categoryName;
}
public int getCategoryId() {
return categoryId;
}
public void setCategoryId(int categoryId) {
this.categoryId = categoryId;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public String getPublisher() {
return publisher;
}
public void setPublisher(String publisher) {
this.publisher = publisher;
}
}
BookMapper.java
package net.skhu.mapper;
import java.util.List;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import net.skhu.dto.Book;
@Mapper
public interface BookMapper {
@Select("""
SELECT b.*, c.name categoryName
FROM book b LEFT JOIN category c ON b.categoryId = c.id""")
List<Book> findAll();
@Select("""
SELECT b.*, c.name categoryName
FROM book b
LEFT JOIN category c ON b.categoryId = c.id
WHERE b.id=#{id}""")
Book findById(int id);
@Select("""
SELECT b.*, c.name categoryName
FROM book b JOIN category c ON b.categoryId = c.id
WHERE b.title LIKE #{srchText}""")
List<Book> findByTitle(String srchText);
}
## 실행결과
책 목록 클릭시,
다시 책 목록 화면에서 책 이름으로 검색하면,
추가적으로 src/main/resources/application.properties 파일에서,
사용할 db 연결, 포트설정 등등을 하고,
pom.xml 파일은 따로 구성해주어야한다.
application.properties
spring.mvc.view.prefix=/WEB-INF/views/
spring.mvc.view.suffix=.jsp
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/book2?useUnicode=yes&characterEncoding=UTF-8&allowMultiQueries=true&serverTimezone=Asia/Seoul
spring.datasource.username=user1
spring.datasource.password=데이터베이스패스워드
server.port=8088
- 4번째 줄에서 사용할 db 이름이 'book2'이기 때문에 book2라고 썼다.
만약 다른 db를 사용하게 되면, 이름을 바꿔주어야 한다.
- 8088 포트를 사용할 것이기 때문에 포트도 재설정했다.
- 데이터베이스 패스워드를 코드에 넣어주었다. (개인정보 유출 가능성 있으니 주의)
pom.xml
<dependency>
<groupId>jakarta.servlet.jsp.jstl</groupId>
<artifactId>jakarta.servlet.jsp.jstl-api</artifactId>
</dependency>
<dependency>
<groupId>org.glassfish.web</groupId>
<artifactId>jakarta.servlet.jsp.jstl</artifactId>
</dependency>
<dependency> <groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
위 코드를 pom.xml 파일 dependencies 태그에 추가해주어야 한다.
'Spring' 카테고리의 다른 글
회원 서비스 개발 & 테스트 (0) | 2022.09.13 |
---|---|
회원리포지토리 테스트 케이스 작성 (0) | 2022.09.13 |
댓글