오라클에서 테이블 만들기
select * from tab; //테이블 뭐가 있나 조회
create table test(
bno number primary key,
writer varchar2(20),
title varchar2(100),
content varchar2(1000),
reg_data date default sysdate);
create sequence test_seq;
insert into test (
bno, writer, title, content)
values (test_seq.nextval, 'aaa', '제목입니다', '내용입니다');
select * from test;
commit;
New > Dynamic Web Project > MVC_Board 프로젝트를 만든다.
* 만들 때 Generate web.xml deployment desciptor에 체크한 후 Finish한다.
톰캣 홈페이지의 Taglibs에 들어가 네가지를 다운받은 후, lib폴더에 붙여넣는다.
아파치 톰캣 웹사이트에 들어가 document > Oracle 부분의 소스를 참고할 것이다.
MVC 패턴 코드 전체구성
META-INF
context.xml : Resource name 부분을 복사 붙여넣기 후 수정
<?xml version="1.0" encoding="UTF-8"?>
<context>
<Resource name="jdbc/boardddb" auth="Container"
type="javax.sql.DataSource"
driverClassName="oracle.jdbc.driver.OracleDriver"
url="jdbc:oracle:thin:@127.0.0.1:1521:xe"
username="mvc" password="1234"
maxTotal="20" maxIdle="10"
maxWaitMillis="-1"/>
</context>
<!--maxTotl : 커넥트풀 최대유지 . -1 : 시간안정함 -->
web.xml 셋팅 : 부분을 복사 붙여넣기 후 수정 (web-content)
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
id="WebApp_ID" version="4.0">
<display-name>MVC_Board</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<resource-ref>
<description>Oracle Datasource example</description>
<res-ref-name>jdbc/boardddb</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
</web-app>
dao
DBConn.java
package dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;
public class DBConn {
public static Connection getConnection() {
Connection conn=null;
try {
Context initContext = new InitialContext();
Context envContext = (Context)initContext.lookup("java:/comp/env");
DataSource ds = (DataSource)envContext.lookup("jdbc/boardddb");
conn = ds.getConnection();
} catch (Exception ex) {
ex.printStackTrace();
}
return conn;
}
public static void closeConn(Connection con) {
try {
if(con!=null)
con.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static void closePs(PreparedStatement ps) {
try {
if(ps!=null)
ps.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static void closeRs(ResultSet rs) {
try {
if(rs!=null)
rs.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
BoardDao.java
package dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import dto.Board;
public class BoardDao {
//싱글톤
private BoardDao () {}
private static BoardDao dao = new BoardDao();
public static BoardDao getInstance() {
return dao;
}
public ArrayList<Board> selectAll(){
ArrayList<Board> list = new ArrayList<Board>();
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs= null;
String sql = "select * from test";
try {
conn = DBConn.getConnection();
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
while(rs.next()) {
Board board = new Board();
board.setBno(rs.getInt("bno"));
board.setWriter(rs.getString("writer"));
board.setTitle(rs.getString("title"));
board.setContent(rs.getString("content"));
board.setReg_data(rs.getTimestamp("reg_data"));
list.add(board);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
DBConn.closeRs(rs);
DBConn.closePs(ps);
DBConn.closeConn(conn);
}
System.out.println(list.toString());
return list;
}
public Board selectOne(int bno){
Board board = null;
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs= null;
String sql = "select * from test where bno=?";
try {
conn = DBConn.getConnection();
ps = conn.prepareStatement(sql);
ps.setInt(1, bno);
rs = ps.executeQuery();
while(rs.next()) {
board = new Board();
board.setBno(rs.getInt("bno"));
board.setWriter(rs.getString("writer"));
board.setTitle(rs.getString("title"));
board.setContent(rs.getString("content"));
board.setReg_data(rs.getTimestamp("reg_data"));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
DBConn.closeRs(rs);
DBConn.closePs(ps);
DBConn.closeConn(conn);
}
return board;
}
public void insert(Board board) {
Connection conn = null;
PreparedStatement ps = null;
String sql = "insert into test(bno, writer, title, content)"
+ "values(test_seq.nextval,?,?,?)";
try {
conn = DBConn.getConnection();
ps = conn.prepareStatement(sql);
ps.setString(1, board.getWriter());
ps.setString(2, board.getTitle());
ps.setString(3, board.getContent());
int n = ps.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
DBConn.closePs(ps);
DBConn.closeConn(conn);
}
}
public void update(Board board) {
Connection conn = null;
PreparedStatement ps = null;
String sql = "update test set writer=?, title=?, content=? where bno=?";
try {
conn = DBConn.getConnection();
ps = conn.prepareStatement(sql);
ps.setString(1, board.getWriter());
ps.setString(2, board.getTitle());
ps.setString(3, board.getContent());
ps.setInt(4, board.getBno());
int n = ps.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
DBConn.closePs(ps);
DBConn.closeConn(conn);
}
}
public void delete(int bno) {
Connection conn = null;
PreparedStatement ps = null;
String sql = "delete from test where bno=?";
try {
conn = DBConn.getConnection();
ps = conn.prepareStatement(sql);
ps.setInt(1, bno);
int n = ps.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
DBConn.closePs(ps);
DBConn.closeConn(conn);
}
}
}
dto
Board.java
package dto;
import java.sql.Timestamp;
public class Board {
private int bno;
private String writer;
private String title;
private String content;
private Timestamp reg_data;
public int getBno() {
return bno;
}
public void setBno(int bno) {
this.bno = bno;
}
public String getWriter() {
return writer;
}
public void setWriter(String writer) {
this.writer = writer;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public Timestamp getReg_data() {
return reg_data;
}
public void setReg_data(Timestamp reg_data) {
this.reg_data = reg_data;
}
@Override
public String toString() {
return "Board [bno=" + bno + ", writer=" + writer + ", title=" + title + ", content=" + content + ", reg_data="
+ reg_data + "]";
}
}
controller
BoardServlet.java (전단서블릿)
package controller;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import controller.service.BoardService;
import oracle.net.aso.s;
/**
* Servlet implementation class BoardServlet
*/
@WebServlet("*.do")
public class BoardServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public BoardServlet() {
super();
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doProcess(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
/* get은 자동인데 포스트는 한글처리해줘야된다 */
request.setCharacterEncoding("utf-8");
doProcess(request, response);
}
protected void doProcess(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String requestURI = request.getRequestURI();
String contextPath = request.getContextPath();
String command = requestURI.substring(contextPath.length());
ActionFactory af = ActionFactory.getInstance();
BoardService service =af.getService(command) ;
if(service!=null)
service.execute(request, response);
}
}
ActionFactory.java
package controller;
import controller.service.BoardDeleteService;
import controller.service.BoardListService;
import controller.service.BoardService;
import controller.service.BoardUpdateService;
import controller.service.BoardViewService;
import controller.service.BoardWriteFormService;
import controller.service.BoardWriteService;
public class ActionFactory {
//싱글톤
private ActionFactory () {}
private static ActionFactory af = new ActionFactory();
public static ActionFactory getInstance() {
return af;
}
public BoardService getService(String command) {
BoardService service = null;
if(command.equals("/list.do"))
service = new BoardListService();
else if(command.equals("/writeForm.do")) {
service = new BoardWriteFormService();
}else if(command.equals("/write.do")) {
service = new BoardWriteService();
}else if(command.equals("/view.do")) {
service = new BoardViewService();
}else if(command.equals("/update.do")) {
service = new BoardUpdateService();
}else if(command.equals("/delete.do")) {
service = new BoardDeleteService();
}
return service;
}
}
controller.service
BoardService.java
package controller.service;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public interface BoardService {
public void execute(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException;
}
BoardListService.java
package controller.service;
import java.io.IOException;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import dao.BoardDao;
import dto.Board;
public class BoardListService implements BoardService {
@Override
public void execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
BoardDao dao = BoardDao.getInstance();
ArrayList<Board> list = dao.selectAll(); //게시판리스트 받아옴
request.setAttribute("boardlist", list); //리케스트의 속성으로 넣음 (실제부르는이름, 보이는이름)
request.getRequestDispatcher("/board/list.jsp").forward(request, response);
//포워드 정보 페이지로 request, response를 갖고 list.jsp로 감. 가면 boardlist를 바로 읽을 수 있음
}
}
BoardWriteFormService.java
package controller.service;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class BoardWriteFormService implements BoardService{
@Override
public void execute(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.getRequestDispatcher("board/write.jsp")
.forward(request, response);
}
}
BoardWriteService.java
package controller.service;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import dao.BoardDao;
import dto.Board;
public class BoardWriteService implements BoardService {
@Override
public void execute(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Board board = new Board();
board.setWriter(request.getParameter("writer"));
board.setTitle(request.getParameter("title"));
board.setContent(request.getParameter("content"));
BoardDao dao = BoardDao.getInstance();
dao.insert(board);
response.sendRedirect("list.do");
}
}
BoardViewService.java
package controller.service;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import dao.BoardDao;
import dto.Board;
public class BoardViewService implements BoardService {
@Override
public void execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int bno = Integer.parseInt(request.getParameter("bno"));
BoardDao dao = BoardDao.getInstance();
Board board = dao.selectOne(bno);
request.setAttribute("board", board);
request.getRequestDispatcher("board/view.jsp")
.forward(request, response);
}
}
BoardUpdateService.java
package controller.service;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import dao.BoardDao;
import dto.Board;
public class BoardUpdateService implements BoardService {
@Override
public void execute(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Board board = new Board();
board.setBno(Integer.parseInt(request.getParameter("bno")));
board.setWriter(request.getParameter("update"));
board.setTitle(request.getParameter("title"));
board.setContent(request.getParameter("content"));
BoardDao dao = BoardDao.getInstance();
dao.update(board);
response.sendRedirect("list.do");
}
}
BoardDeleteService.java
package controller.service;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import dao.BoardDao;
import dto.Board;
public class BoardDeleteService implements BoardService {
@Override
public void execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int bno = Integer.parseInt(request.getParameter("bno"));
BoardDao dao = BoardDao.getInstance();
dao.delete(bno);
response.sendRedirect("list.do");
}
}
WebContent
index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%response.sendRedirect("list.do"); %>
</body>
</html>
board
list.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<table>
<tr>
<td colspan="4" align="right">
<a href="writeForm.do">글쓰기</a></td>
</tr>
<tr>
<th>번호</th>
<th>제목</th>
<th>작성자</th>
<th>작성일</th>
</tr>
<c:forEach items="${boardlist}" var="board">
<tr>
<td>${board.bno }</td>
<td><a href="view.do?bno=${board.bno }">${board.title}</a></td>
<td>${board.writer }</td>
<td><fmt:formatDate value="${board.reg_data }"/></td>
</tr>
</c:forEach>
</table>
</body>
</html>
view.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="update.do" method="post">
<table>
<tr>
<th>번호</th>
<td><input type="text" name="bno" readonly value=${board.bno }></td>
</tr>
<tr>
<th>작성자</th>
<td><input type="text" name="writer" value=${board.writer }></td>
</tr>
<tr>
<th>제목</th>
<td><input type="text" name="title" value=${board.title }></td>
</tr>
<tr>
<th>내용</th>
<td><textarea rows="7" cols="50" name="content">${board.content}</textarea></td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" value="수정">
<input type="reset" value="취소">
<input type="button" value="삭제" onclick="location.href='delete.do?bno=${board.bno}'">
<input type="button" value="목록" onclick="location.href='list.do'">
</td>
</tr>
</table>
</form>
</body>
</html>
write.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="write.do" method="post">
<table>
<tr>
<th>작성자</th>
<td><input type="text" name="writer"></td>
</tr>
<tr>
<th>제목</th>
<td><input type="text" name="title"></td>
</tr>
<tr>
<th>내용</th>
<td><textarea rows="7" cols="50" name="content"></textarea></td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" value="저장">
<input type="reset" value="취소">
<input type="button" value="목록" onclick="location.href='list.do'">
</td>
</tr>
</table>
</form>
</body>
</html>
처리 순서 요약
index(뷰)에서 요청 -> boardservlet 에서 do/post 중 하나 -> process에서 request정보, 전체 uri 중 contextpath(프로젝트 우측 버튼, 프로퍼티에 가면 web project setting의 context root)를 가져온다. (index 앞의 response.sendRedirect("list.do"); list.do 앞에 이것저것 붙는다. ) uri는 실제 리소스 주소 (MVC_Board/list.do)다. url은 http부터.
contextpath.length() 는 길이. 전체 주소에서 path의 길이 (/ 포함)
어떤 값이 나오는 게 궁금하면 System.out.println(requestURI....contextpath...command)등으로 출력해본다.
BoardServlet의 BoardService에서 서비스를 얻기위해
ActionFactory 서비스 생성 후 레퍼런스 리턴
다시 BoardServlet 와서 request, response 참조값을 가지고 함수 호출..
db의 값을 가지고 list.jsp 페이지로 간다.
list.jsp에...
'Frameworks > Spring' 카테고리의 다른 글
Spring mybatis를 이용하여 게시판 만들기 (0) | 2019.08.28 |
---|---|
Spring MVC 패턴 스프링 게시판 만들기 (1) | 2019.08.27 |
Spring MVC 개요, 구조, Resourse 폴더, 컨트롤러 구현 (전통적인 3버전 방법) (0) | 2019.08.27 |
스프링 프레임워크 Spring Framework (2) Spring 개발 환경 설정 (0) | 2019.08.23 |
스프링 프레임워크 Spring Framework (1) 프레임워크 정의, 장점, 스트링프레임워크, 컨테이너 개념 (0) | 2019.08.23 |