1. 데이터를 받을 폼을 만든다. boardFrom.jsp


<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<link rel="stylesheet" type="text/css" href="css/style.css" />

<title>글쓰기 양식 폼</title>

</head>

<body>

<form action="boardFormAction.bo" method="post">

<fieldset>

<legend>글쓰기</legend>

<table>

<tr><td class="td_title">작성자</td><td><input type="text" name="name" class="input1" /></td></tr>

<tr><td class="td_title">제 목</td><td><input type="text" name="title" class="input1" /></td></tr>

<tr><td class="td_title">내 용</td><td><textarea name="textarea" class="input2"></textarea></td></tr>

<tr><td colspan="2" class="submit"><input type="submit" name="submit" value="확인" /><input type="reset" name="reset" value="취소" /></td></tr>

</table>

</fieldset>

</form>

</body>

</html>





2. 서블릿을 수정 (전에 BoardFrontController.java라고 만들어뒀던 것)

MVC 패턴에서 C에 해당. 컨트롤러.


package net.board.action;


import java.io.IOException;

import javax.servlet.RequestDispatcher;

import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;


@WebServlet("/BoardFrontController")

public class BoardFrontController extends HttpServlet {

private static final long serialVersionUID = 1L;

protected void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

doProcess(request, response);

}


protected void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

doProcess(request, response);

}

protected void doProcess(HttpServletRequest request, HttpServletResponse response) 

throws ServletException, IOException {

String requestURI = request.getRequestURI(); // 경로 뒷부분+bo부분

String contextPath = request.getContextPath(); // 경로 전체 부분

String command = requestURI.substring(contextPath.length()); // bo앞의 경로부분 잘라줌


if (command.equals("/boardForm.bo")) {

RequestDispatcher dispatcher = request.getRequestDispatcher("boardForm.jsp");

dispatcher.forward(request, response);


} else if (command.equals("/boardFormAction.bo")) {

// 파라미터를 받아와서 데이터베이스에 저장하는 것을 넣을 부분

}

}

}




3. 서블릿 있는 곳에서 인터페이스 생성 Action.java


package net.board.action;


import java.io.IOException;


import javax.servlet.RequestDispatcher;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;


public interface Action {

public void execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException ; 

// 인터페이스 안에 중괄호 없는 추상메서드 생성. 서블릿과 동일한 파라미터를 받게 한다.

}






4. Action.java 인터페이스를 구현하는 boardAddAction 클래스를 생성한다.




package net.board.action;


import java.io.IOException;

import java.sql.Connection;

import java.sql.DriverManager;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;


public class BoardAddAction implements Action {


@Override

public void execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

request.setCharacterEncoding("UTF-8");

String name = request.getParameter("name");

String title = request.getParameter("title");

String contents = request.getParameter("contents");

}

}





5. 데이터베이스에서 테이블을 만든다.

create table testBoard(
BOARD_NAME VARCHAR2(20),
BOARD_TITLE VARCHAR2(50),
BOARD_CONTENTS VARCHAR2(2000)
);




자바빈을 통한 접속 구현


1. 서블릿을 수정 BoardFrontController.java


Action.java 인터페이스를 구현하는  boardAddAction 클래스의 execute 메서드를 넣어준다.


package net.board.action;


import java.io.IOException;

import javax.servlet.RequestDispatcher;

import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;


@WebServlet("/BoardFrontController")

public class BoardFrontController extends HttpServlet {

private static final long serialVersionUID = 1L;

protected void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

doProcess(request, response);

}


protected void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

doProcess(request, response);

}

protected void doProcess(HttpServletRequest request, HttpServletResponse response) 

throws ServletException, IOException {

String requestURI = request.getRequestURI(); // 경로 뒷부분+bo부분

String contextPath = request.getContextPath(); // 경로 전체 부분

String command = requestURI.substring(contextPath.length()); // bo앞의 경로부분 잘라줌


if (command.equals("/boardForm.bo")) {

RequestDispatcher dispatcher = request.getRequestDispatcher("boardForm.jsp");

dispatcher.forward(request, response);


} else if (command.equals("/boardFormAction.bo")) {

// 파라미터를 받아와서 데이터베이스에 저장하는 것을 넣을 부분

Action action = new BoardAddAction();

action.execute(request, response); // 메서드 오버라이딩

}

}

}



2. 자바빈 클래스 (DTO) 생성 BoardBean.java 

DTO 데이터 트랜스포트 오브젝트. 데이터를 전송하는 오브젝트.

패키지는 기존과 달리 net.board.db로 별도 설정.




package net.board.db;


public class BoardBean {


private String name;

private String title;

private String contents;


public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public String getTitle() {

return title;

}

public void setTitle(String title) {

this.title = title;

}

public String getContents() {

return contents;

}

public void setContents(String contents) {

this.contents = contents;

}

}





3. Action.java 인터페이스를 구현하는 boardAddAction 클래스에 자바빈을 반영

(연결 부분은 DAO로 옮겨서 삭제함)


package net.board.action;


import java.io.IOException;

import java.sql.Connection;

import java.sql.DriverManager;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;


import net.board.db.BoardBean;


public class BoardAddAction implements Action {


@Override

public void execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

request.setCharacterEncoding("UTF-8");

BoardBean boardBean = new BoardBean(); // 자바빈 인스턴스 생성

String name = request.getParameter("name");

String title = request.getParameter("title");

String contents = request.getParameter("contents");

boardBean.setName(name); // 자바빈으로 받아오는 값을 넣어줌.

boardBean.setTitle(title);

boardBean.setContents(contents);

}

}




3. DAO 데이터 엑세스 오브젝트 생성 

데이터에 실질적으로 데이터 저장하는 오브젝트. SQL문으로 구성.

MVC모델의 M에 해당하는 비지니스 로직.


package net.board.db;


import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.PreparedStatement;

import java.sql.SQLException;


public class BoardDAO {


boolean connection = false;

Connection conn = null;


public BoardDAO() {  // 접속을 담당하는 메서드


String driver = "oracle.jdbc.driver.OracleDriver";

String url = "jdbc:oracle:thin:@localhost:1521:xe";


try {

Class.forName(driver);

conn = DriverManager.getConnection(url, "hr", "tiger");

connection = true;

System.out.println("DB 연결 성공");

} catch (Exception e) {

connection = false;

System.out.println("DB 연결 실패");

e.printStackTrace();

}

}


public void boardInsert(BoardBean boardBean) {  // SQL을 담당하는 메서드


String sql = "INSERT INTO TESTBOARD VALUES (?, ?, ?)";


try {

PreparedStatement pstmt = conn.prepareStatement(sql);

pstmt.setString(1, boardBean.getName());

pstmt.setString(2, boardBean.getTitle());

pstmt.setString(3, boardBean.getContents());

pstmt.executeUpdate();

} catch (SQLException e) {

e.printStackTrace();

}

}

}




4BoardAddAction.java도 수정


package net.board.action;


import java.io.IOException;

import java.sql.Connection;

import java.sql.DriverManager;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;


import net.board.db.BoardBean;

import net.board.db.BoardDAO;


public class BoardAddAction implements Action {


@Override

public void execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

request.setCharacterEncoding("UTF-8");

BoardBean boardBean = new BoardBean(); // 자바빈 인스턴스 생성

BoardDAO boardDao = new BoardDAO();   // DAO 인스턴스 생성

String name = request.getParameter("name");

String title = request.getParameter("title");

String contents = request.getParameter("contents");

boardBean.setName(name); // 자바빈으로 받아오는 값을 넣어줌.

boardBean.setTitle(title);

boardBean.setContents(contents);

boardDao.boardInsert(boardBean);

}

}







Posted by netyhobby
,