오늘의 코딩순서
(폴더: oBootDbConnect) (줌 10:15쯤~
메인페이지 http://localhost:8382
- jdbcMemberRepository.class + SpringConfig.class
(폴더: oBootBoard) (줌 10:44~
메인페이지 http://localhost:8383/list
- build.gradle
- application.yml + BDto.class + BDao.interface + JdbcDao.class(현장 HW 1-1) + BExecuteCommand.class + BController.class + list.jsp + header.jsp
- content_view.jsp + BController.class + BExecuteCommand.class + JdbcDao.class(현장 HW 2)
- JdbcDao.class(현장 HW 3)
오늘의 코딩 포인트
(폴더: oBootDbConnect)
- JdbcMemberRepository.class ==> @Repository 주석처리후 아래 SpringConfig.class 작성
package com.oracle.oBootDbConnect.repository;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceUtils;
import org.springframework.stereotype.Repository;
import com.oracle.oBootDbConnect.domain.Member7;
//@Repository
public class JdbcMemberRepository implements MemberRepository {
// JDBC 사용
private final DataSource dataSource;
@Autowired
public JdbcMemberRepository(DataSource dataSource) {
this.dataSource = dataSource;
}
private Connection getConnection() {
return DataSourceUtils.getConnection(dataSource);
}
// 현장 HW 2-1
// DB에 insert 되는 로직 만들기
@Override
public Member7 save(Member7 member7) {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
String sql = "insert into member7(id,name) values(member_seq.nextval,?)";
//id는 request 데이터라 들어오지 않았기 때문에, sequence 값으로 넘겨주기
System.out.println("JdbcMemberRepository save sql->"+sql);
try {
conn = getConnection();
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, member7.getName());
pstmt.executeUpdate();
return member7;
} catch (Exception e) {
throw new IllegalStateException();
} finally {
close(conn, pstmt, rs);
}
}
// DB에 있는 내용을 가져와서 ArrayList에 넣기
@Override
public List<Member7> findAll() {
Connection conn = null;
PreparedStatement pstmt =null;
ResultSet rs = null;
String sql = "select * from member7";
System.out.println("JdbcMemberRepository findAll() sql->"+sql);
try {
conn = getConnection();
pstmt = conn.prepareStatement(sql);
rs = pstmt.executeQuery();
List<Member7> members = new ArrayList<>();
while(rs.next()) {
Member7 member = new Member7();
member.setId(rs.getLong("id"));
member.setName(rs.getString("name"));
members.add(member);
}
return members;
} catch (Exception e) {
throw new IllegalStateException();
} finally {
close(conn, pstmt, rs);
}
}
// 메모리 해제
private void close(Connection conn , PreparedStatement pstmt , ResultSet rs)
{
//JSP에서 한 방식으로 close를 해도 되고, 아래의 방식으로 해도 됨
try {
if (rs != null) rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (pstmt != null) pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (conn != null) close(conn);
} catch (SQLException e) {
e.printStackTrace();
}
}
private void close(Connection conn) throws SQLException {
DataSourceUtils.releaseConnection(conn, dataSource);
}
}
- SpringConfig.class
Tip)- @Bean
- @Component 를 포함하는 @Controller, @Service, @Repository 애노테이션이 아니면 Springbean 으로 자동 등록되지 않기 때문에, 따로 @Bean설정을 하고 SpringConfig를 넣어줘야 함
- 이 부분의 설정을 잘 운영하면 다른 소프트웨어를 사용하려 할때도 유지보수가 용이해짐
- 생성자부분 설명 10:33분 부터 다시 보고 작성하기
- return new MemoryMemberRepository(); => 입력한 값을 Memory에만 업로드하며, DB에는 저장되지 않음
- return new JdbcMemberRepository(dataSource); => 입력한 값이 DB에도 업로드됨
- @Bean
package com.oracle.oBootDbConnect;
import javax.sql.DataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.oracle.oBootDbConnect.repository.JdbcMemberRepository;
import com.oracle.oBootDbConnect.repository.MemberRepository;
import com.oracle.oBootDbConnect.repository.MemoryMemberRepository;
@Configuration
public class SpringConfig {
private DataSource dataSource;
public SpringConfig() {
this.dataSource = dataSource;
}
@Bean
public MemberRepository memberRepository() {
return new MemoryMemberRepository(); // ==> Memory로 부품 교체할때 사용
// ()안에 아무것도 없다는 것은 따로 설정한 생성자가 없기 때문에, 기본 생성자를 쓰겠다는 것
//return new JdbcMemberRepository(dataSource); ==> Oracle로 부품 교체할때 사용
}
}
(폴더: oBootBoard)
- 새 Spring Starter 폴더 생성
- build.gradle
로직에 아래 세 줄 추가하여 수동으로 프로그램 삽입하기 => build.gradle에 우클릭해서 Refresh 꼭 하기
implementation 'org.apache.tomcat.embed:tomcat-embed-jasper'
implementation group: 'org.glassfish.web', name: 'jakarta.servlet.jsp.jstl', version: '2.0.0'
implementation 'com.googlecode.json-simple:json-simple:1.1.1'
plugins {
id 'java'
id 'org.springframework.boot' version '3.3.2'
id 'io.spring.dependency-management' version '1.1.6'
}
group = 'com.oracle'
version = 'version.1.0'
java {
toolchain {
languageVersion = JavaLanguageVersion.of(17)
}
}
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-jdbc'
implementation 'org.springframework.boot:spring-boot-starter-web'
runtimeOnly 'com.oracle.database.jdbc:ojdbc11'
implementation 'org.apache.tomcat.embed:tomcat-embed-jasper'
implementation group: 'org.glassfish.web', name: 'jakarta.servlet.jsp.jstl', version: '2.0.0'
implementation 'com.googlecode.json-simple:json-simple:1.1.1'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
}
tasks.named('test') {
useJUnitPlatform()
}
- application.yml(class 아니고 New File임!) => 줄 잘 안맞춰주면 인식못함
아래 로직 저장후, main폴더에 WEB-INF폴더 만들고, 그 안에 views 폴더 만들기
server:
port: 8383
# Oracle Connect
spring:
datasource:
driver-class-name: oracle.jdbc.OracleDriver
url: jdbc:oracle:thin:@localhost:1521/xe
username: scott
password: tiger
# View Resolver
mvc:
view:
prefix: /WEB-INF/views/
suffix: .jsp
- MVC Board TBL 만들기
- BDto.class ==> DTO에 해당
Tip)- getter and setter 방식 + 생성자 방식으로 DTO만들기
package com.oracle.oBootBoard.dto;
import java.sql.Timestamp;
public class BDto {
int bId;
String bName;
String bTitle;
String bContent;
Timestamp bDate;
int bHit;
int bGroup;
int bStep;
int bIndent;
public BDto() {
}
public BDto(int bId, String bName, String bTitle, String bContent,
Timestamp bDate, int bHit, int bGroup,
int bStep, int bIndent) {
this.bId = bId;
this.bName = bName;
this.bTitle = bTitle;
this.bContent = bContent;
this.bDate = bDate;
this.bHit = bHit;
this.bGroup = bGroup;
this.bStep = bStep;
this.bIndent = bIndent;
}
public int getbId() {
return bId;
}
public void setbId(int bId) {
this.bId = bId;
}
public String getbName() {
return bName;
}
public void setbName(String bName) {
this.bName = bName;
}
public String getbTitle() {
return bTitle;
}
public void setbTitle(String bTitle) {
this.bTitle = bTitle;
}
public String getbContent() {
return bContent;
}
public void setbContent(String bContent) {
this.bContent = bContent;
}
public Timestamp getbDate() {
return bDate;
}
public void setbDate(Timestamp bDate) {
this.bDate = bDate;
}
public int getbHit() {
return bHit;
}
public void setbHit(int bHit) {
this.bHit = bHit;
}
public int getbGroup() {
return bGroup;
}
public void setbGroup(int bGroup) {
this.bGroup = bGroup;
}
public int getbStep() {
return bStep;
}
public void setbStep(int bStep) {
this.bStep = bStep;
}
public int getbIndent() {
return bIndent;
}
public void setbIndent(int bIndent) {
this.bIndent = bIndent;
}
}
- header.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<link href="resources/css/board.css" rel="stylesheet" type="text/css">
- list.jsp ==> View에 해당, 메인 페이지 조회방법
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ include file="header.jsp" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>게시판 ${count}</h1>
<table>
<tr>
<td>번호</td><td>이름</td><td>제목</td><td>날짜</td><td>히트</td>
</tr>
<c:forEach items="${boardList }" var="mvc_board">
<tr>
<td>${mvc_board.bId}</td>
<td>${mvc_board.bName}</td>
<td>
<c:forEach begin="1" end="${mvc_board.bIndent}">↳</c:forEach>
<!-- ↳부분은 이미지도 삽입 가능 -->
<a href="content_view?bId=${mvc_board.bId}">${mvc_board.bTitle}</a>
</td>
<td>${mvc_board.bDate}</td>
<td>${mvc_board.bHit}</td>
</tr>
</c:forEach>
<tr>
<td colspan="5"> <a href="write_view">글작성</a> </td>
</tr>
</table>
</body>
</html>
- BController.class
package com.oracle.oBootBoard.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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 com.oracle.oBootBoard.command.BExecuteCommand;
@Controller
public class BController {
private static final Logger logger = LoggerFactory.getLogger(BController.class);
private final BExecuteCommand bExecuteService;
@Autowired
public BController(BExecuteCommand bExecuteService) {
this.bExecuteService = bExecuteService;
}
@RequestMapping("list")
//list.jsp와 연결
public String list(Model model) {
logger.info("list start...");
bExecuteService.bListCmd(model);
model.addAttribute("count","50");
return "list";
}
}
- BExecuteCommand.class ==>Service에 해당
package com.oracle.oBootBoard.command;
import java.util.ArrayList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import com.oracle.oBootBoard.dao.BDao;
import com.oracle.oBootBoard.dto.BDto;
@Service
public class BExecuteCommand {
private final BDao jdbcDao;
@Autowired
public BExecuteCommand(BDao jdbcDao) {
this.jdbcDao = jdbcDao;
}
public void bListCmd(Model model) {
// Dao 연결 //list.jsp와 연결
ArrayList<BDto> boardDtoList = jdbcDao.boardList();
System.out.println("BListCommand boardDtoList.size()->"+boardDtoList.size());
model.addAttribute("boardList",boardDtoList);
// call by reference로 이동
}
}
- BDao.interface
package com.oracle.oBootBoard.dao;
import java.util.ArrayList;
import com.oracle.oBootBoard.dto.BDto;
public interface BDao {
public ArrayList<BDto> boardList();
public BDto contentView(String strId);
}
- JdbcDao.class ==> 위의 interface를 상속받음 (현장 HW 1-1)
package com.oracle.oBootBoard.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceUtils;
import org.springframework.stereotype.Repository;
import com.oracle.oBootBoard.dto.BDto;
@Repository
public class JdbcDao implements BDao {
//JDBC 사용
private final DataSource dataSource;
@Autowired
public JdbcDao(DataSource dataSource) {
this.dataSource = dataSource;
}
private Connection getConnection() {
return DataSourceUtils.getConnection(dataSource);
}
@Override
public ArrayList<BDto> boardList() {
ArrayList<BDto> bList = new ArrayList<BDto>();
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
System.out.println("BDao boardList start...");
// (0801)현장 HW 1
try {
connection = getConnection();
String query = "SELECT bId, bName, bTitle, bContent, bDate, bHit,"
+ " bGroup, bStep, bIndent"
+ " From mvc_board order by bGroup desc, bStep asc";
preparedStatement = connection.prepareStatement(query);
System.out.println("BDao query->"+query);
resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
int bId = resultSet.getInt("bId");
String bName = resultSet.getString("bName");
String bTitle = resultSet.getString("bTitle");
String bContent = resultSet.getString("bContent");
Timestamp bDate = resultSet.getTimestamp("bDate");
int bHit = resultSet.getInt("bHit");
int bGroup = resultSet.getInt("bGroup");
int bStep = resultSet.getInt("bStep");
int bIndent = resultSet.getInt("bIndent");
BDto dto = new BDto(bId, bName, bTitle, bContent, bDate, bHit,
bGroup, bStep, bIndent);
bList.add(dto);
}
} catch (SQLException e) {
System.out.println("list dataSource->" + e.getMessage());
e.printStackTrace();
} finally {
try {
if (resultSet != null) resultSet.close();
if (preparedStatement != null) preparedStatement.close();
if (connection != null) connection.close();
} catch (Exception e2) {
System.out.println("e2.getMessage->"+e2.getMessage());
e2.printStackTrace();
}
}
return bList;
}
- content_view.jsp ==> 글 제목 눌렀을때 내용이 나오도록 DB와 연결하여 조회(select)하기
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ include file="header.jsp" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="modify" method="post">
<input type="hidden" name="bId" value="${mvc_board.bId}">
<table border="1">
<tr>
<td> 번호 </td><td> ${mvc_board.bId} </td>
</tr>
<tr>
<td> 히트 </td><td> ${mvc_board.bHit} </td>
</tr>
<tr>
<td> 이름 </td><td><input type="text" name="bName" value="${mvc_board.bName}"></td>
</tr>
<tr>
<td> 제목 </td>
<td> <input type="text" name="bTitle" value="${mvc_board.bTitle}"></td>
</tr>
<tr>
<td> 내용 </td>
<td> <textarea rows="10" name="bContent" >${mvc_board.bContent}</textarea></td>
</tr>
<tr >
<td colspan="2"> <input type="submit" value="수정">
<a href="list">목록보기</a>
<a href="delete?bId=${mvc_board.bId}">삭제</a>
<a href="reply_view?bId=${mvc_board.bId}">답변</a></td>
</tr>
</table>
</form>
</body>
</html>
- BController.class
package com.oracle.oBootBoard.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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 com.oracle.oBootBoard.command.BExecuteCommand;
import jakarta.servlet.http.HttpServletRequest;
@Controller
public class BController {
private static final Logger logger = LoggerFactory.getLogger(BController.class);
private final BExecuteCommand bExecuteService;
@Autowired
public BController(BExecuteCommand bExecuteService) {
this.bExecuteService = bExecuteService;
}
@RequestMapping("/content_view")
//content_view.jsp와 연결
public String content_view(HttpServletRequest request, Model model) {
System.out.println("content_view start...");
model.addAttribute("request",request);
// 이름 request 객체 request
bExecuteService.bContentCmd(model);
return "content_view";
}
}
- BExecuteCommand.class
package com.oracle.oBootBoard.command;
import java.util.ArrayList;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import com.oracle.oBootBoard.dao.BDao;
import com.oracle.oBootBoard.dto.BDto;
import jakarta.servlet.http.HttpServletRequest;
@Service
public class BExecuteCommand {
private final BDao jdbcDao;
@Autowired
public BExecuteCommand(BDao jdbcDao) {
this.jdbcDao = jdbcDao;
}
public void bContentCmd(Model model) {
System.out.println("BExecuteCommand bContentCmd start...");
// model을 Map으로 전환 //content_view.jsp와 연결
Map<String, Object> map = model.asMap();
HttpServletRequest request = (HttpServletRequest)map.get("request");
// BController의 model.addAttribute("request",request); 와 이어짐
// String request(key값)을 주면 객체 request를 돌려줌(Map 방식)
String bId = request.getParameter("bId");
BDto board = jdbcDao.contentView(bId);
model.addAttribute("mvc_board",board);
// Tip: 어떤 것과 연결된 것인지 알아볼수 있게, TBL명으로 함
}
- JdbcDao.class(현장 HW 2)
package com.oracle.oBootBoard.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceUtils;
import org.springframework.stereotype.Repository;
import com.oracle.oBootBoard.dto.BDto;
@Repository
public class JdbcDao implements BDao {
//JDBC 사용
private final DataSource dataSource;
@Autowired
public JdbcDao(DataSource dataSource) {
this.dataSource = dataSource;
}
private Connection getConnection() {
return DataSourceUtils.getConnection(dataSource);
}
// (0801)현장 HW 2 => content_view.jsp와 연결
@Override
public BDto contentView(String strId) {
BDto bDto = null;
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
upHit(strId);
System.out.println("contentView start...");
try {
connection = getConnection();
String query = "select * from mvc_board where bId = ?";
// ?값을 PK가 아닌 것으로 넣을 때는, multi row로 취급해야하며, do-while문을 사용해서 오류를 잡아야함
preparedStatement = connection.prepareStatement(query);
preparedStatement.setInt(1, Integer.parseInt(strId));
resultSet = preparedStatement.executeQuery();
if (resultSet.next()) {
int bId = resultSet.getInt("bId");
String bName = resultSet.getString("bName");
String bTitle = resultSet.getString("bTitle");
String bContent = resultSet.getString("bContent");
Timestamp bDate = resultSet.getTimestamp("bDate");
int bHit = resultSet.getInt("bHit");
int bGroup = resultSet.getInt("bGroup");
int bStep = resultSet.getInt("bStep");
int bIndent = resultSet.getInt("bIndent");
bDto = new BDto(bId, bName, bTitle, bContent, bDate, bHit,
bGroup, bStep, bIndent);
}
} catch (SQLException e) {
e.printStackTrace();
}
return bDto;
}
- JdbcDao.class(현장 HW 3)
// (0801)현장 HW 3. 히트수 올리기
private void upHit(String bId) {
Connection connection = null;
PreparedStatement preparedStatement = null;
System.out.println("upHit start...");
try {
connection = getConnection();
String query = "update mvc_board set bHit = bHit + 1 where bId = ?";
preparedStatement = connection.prepareStatement(query);
preparedStatement.setString(1, bId);
int rn = preparedStatement.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (preparedStatement != null) preparedStatement.close();
if (connection != null) connection.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
질문목록
수업교재
오늘의 숙제
'Spring' 카테고리의 다른 글
2024_08_06_화~08_07_수 (0) | 2024.08.06 |
---|---|
2024_08_05_월~08_06_화 (0) | 2024.08.05 |
2024_08_02_금 (0) | 2024.08.02 |
2024_07_31_수 (0) | 2024.07.31 |
2024_07_30_화 (0) | 2024.07.30 |