데용량 clob 4.GB 를 사용시 ojbc7 을 사용해라
일반 varchar2 데이터 처러럼 insert , update 가 된다.
SQL
create table board(
num number not null PRIMARY KEY , --일련번호
writer VARCHAR2(50) not null,
subject VARCHAR2(50) not null,
passwd VARCHAR2(60) not null, -- 수정/삭제용비번
reg_date date default sysdate, --작성일자
readcount number default 0, --조회수
ref number not null, -- 게시물그룹
re_step number not null, -- 게시물 그룹의 순번
re_level number not null, --답변의 단계
content clob not null, -- clob 4GB 까지 입력가능
ip VARCHAR2(30) not null,
filename varchar2(200), --첨부파일 이름
filesize number default 0,--파일 사이즈
down number default 0 --다운로드 횟수
);
insert into board (NUM, WRITER, SUBJECT, PASSWD, REF, RE_STEP,
RE_LEVEL, CONTENT, IP)
VALUES (1, 'kim', '제목', '1234', 1, 1, 0, '내용', '127.0.0.1');
select * from board;
commit;
select
num, writer, subject, reg_date, readcount , filename, filesize,
down, ref, re_step, re_level
from BOARD
order by num desc ;
insert into board (NUM, WRITER, SUBJECT, PASSWD, REF, RE_STEP,
RE_LEVEL, CONTENT, IP, FILENAME, FILESIZE) VALUES (
(select nvl(max(num)+1, 1) from board),
'WRITER', 'SUBJECT', 'PASSWD',
(select nvl(max(num)+1, 1) from board)
, 1 , 0,
'CONTENT', 'IP' , 'dfd', 10 );
1. 업로드 테스트
upload.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ include file="../include/header.jsp" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script src="http://code.jquery.com/jquery-3.2.1.min.js"></script>
</head>
<body>
파일업로드 :post 방식
<form method="post" enctype="multipart/form-data" action="upload_result.jsp">
이름 : <input name="name"><br>
제목 : <input name="subjet"><br>
파일1 : <input type="file" name="file1"><br>
파일2 : <input type="file" name="file2"><br>
<input type="submit" value="업로드">
</form>
</body>
</html>
upload_result.jsp
<%@page import="java.io.File"%>
<%@page import="java.util.Enumeration"%>
<%@page import="com.oreilly.servlet.multipart.DefaultFileRenamePolicy"%>
<%@page import="com.oreilly.servlet.MultipartRequest"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ include file="../include/header.jsp" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script src="http://code.jquery.com/jquery-3.2.1.min.js"></script>
</head>
<body>
업로드 파일 경로
<%= request.getServletContext().getRealPath("/")+"/upload" %>
<%
//업로드 디렉토리 지정
String upload_path= request.getServletContext().getRealPath("/")+"/upload";
//1024byte =>1kb, 1024kB=>1MB, 1024MB=>1GB
int size=10*1024*1024;//업로드 최대사이즈(바이트 단위)
String name="";
String subject="";
String filename="",filename2="";
int filesize=0, filesize2=0;
try{
//request 객체를 확장한 클래스 (파일업로드 기능 추가)
//request객체, 업로드 디렉토리, 최대사이즈,
MultipartRequest multi =new MultipartRequest(
request,upload_path, size, "utf-8",
new DefaultFileRenamePolicy());
name=multi.getParameter("name");
subject=multi.getParameter("subject");
//첨부파일 집합
Enumeration files=multi.getFileNames();
String file1=(String)files.nextElement();//1번 파일
String file2=(String)files.nextElement();//2번 파일
filename=multi.getFilesystemName(file1);//파일 이름
File f1=multi.getFile(file1);
filesize=(int)f1.length();//파일 사이즈
filename2=multi.getFilesystemName(file2);//파일 이름
File f2=multi.getFile(file2);
filesize2=(int)f2.length();//파일 사이즈
}catch(Exception e){
e.printStackTrace();
}
%>
이름 : <%= name %> <br>
제목 : <%= subject %> <br>
파일1 이름 :<%= filename %> <br>
파일1 크기 : <%= filesize %> <br>
파일1 이름 : <%= filename %> <br><br>
파일2 크기 : <%= filesize2 %> <br>
파일2 이름 : <%= filename2 %> <br>
</body>
</html>
파일업로드 :post 방식
|
업로드 파일 경로 D:\dev\jsp_hms(2017-05-19)\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\web03_jsp\/upload 이름 : 테스트
|
2. 게시판 파일 업로드 글 쓰기
MybatisManager
package sqlmap;
import java.io.Reader;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
public class MybatisManager {
//싱글톤 패턴으로 SqlSessionFactory 생성
//SqlSessionFactoryBuilder => SqlSessionFactory
//=>SqlSession
//(sql 실행 객체 : JDBC의 Statement + Result 객체 )
private static SqlSessionFactory instance;
private MybatisManager() {} //private 생성자
public static SqlSessionFactory getInstance(){
Reader reader=null;
try {
// Java Resources의 src
//mybatis 설정파일 정보를 읽음
reader = Resources.getResourceAsReader(
"sqlmap/sqlMapConfig.xml");
//SqlSessionFactory 생성기
instance = new SqlSessionFactoryBuilder().build(reader);
} catch (Exception e) {
e.printStackTrace();
}finally{
try{
if(reader!=null)reader.close();
}catch(Exception e){
e.printStackTrace();
}
}
return instance;
}
}
sqlMapConfig.xml
<?xml version="1.0" encoding="UTF-8"?>
<!-- xml 지시어, xml directive -->
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- 알리아스 설정 -->
<typeAliases>
<!-- typeAlias type="전체경로" alias="별칭" -->
<!-- <typeAlias type="emp.dto.EmpDTO" alias="e" /> -->
</typeAliases>
<!-- db연결 참조코드 -->
<!-- <environments default="">
<environment id="">
<transactionManager type="JDBC" />
<dataSource type="JNDI">
<property name="data_source"
value="java:comp/env/jdbc/myoracle" />
</dataSource>
</environment>
</environments> -->
<!--
<environments default="development">
<environment id="development">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/testDB" />
<property name="username" value="test" />
<property name="password" value="test12" />
</dataSource>
</environment>
</environments>
-->
<environments default="development">
<environment id="development">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="driver" value="oracle.jdbc.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:@127.0.0.1:1521:xe" />
<property name="username" value="java" />
<property name="password" value="1111" />
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="/memo/mapper/memo.xml"/>
<mapper resource="guestbook/mapper/guestbook.xml"/>
<mapper resource="page/emp.xml"/>
<mapper resource="board/mapper/board.xml"/>
</mappers>
<!-- 실제 sql query -->
<!-- <mappers>
<mapper resource="emp/mapper/emp.xml" />
<mapper resource=
"student/mapper/student.xml" />
<mapper resource=
"student/mapper/dept.xml" />
<mapper resource=
"student/mapper/prof.xml" />
<mapper resource=
"student/mapper/lecture.xml" />
<mapper resource=
"memo/mapper/memo.xml" />
<mapper resource=
"board/mapper/board.xml" />
</mappers> -->
</configuration>
Constant
package common;
import javax.servlet.http.HttpServletRequest;
public class Constant {
public HttpServletRequest request;
//업로드 최대 용량
public static final int MAX_UPLOAD=10*1024*1024;
//업로드 디렉토리
public static String uplLoadPath(HttpServletRequest request){
String path=request.getServletContext().getRealPath("/")+"/upload";
return path;
}
}
board.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- memo.xml -->
<!-- 저장 프로시저 호출 방법 { call 프로시저이름(매개변수) } -->
<mapper namespace="board">
<!-- 네임스페이스 id는 중복이 될 수 없음 -->
<select id="list" resultType="board.dto.BoardDTO">
select
num, writer, subject, reg_date, readcount , filename, filesize,
down, ref, re_step, re_level
from BOARD
order by num desc
</select>
<!-- <insert id="insert" >
insert into board (NUM, WRITER, SUBJECT, PASSWD, REF, RE_STEP,
RE_LEVEL, CONTENT, IP)
VALUES ((select nvl(max(num)+1, 1) from board)
, 'kim', '제목', '1234',
(select nvl(max(num)+1, 1) from board)
, 1, 0, '내용', '127.0.0.1')
</insert> -->
<insert id="insert">
insert into board (NUM, WRITER, SUBJECT, PASSWD, REF, RE_STEP,
RE_LEVEL, CONTENT, IP, filename, filesize)
VALUES (
(select nvl(max(num)+1, 1) from board), #{writer},
#{subject}, #{passwd},
(select nvl(max(num)+1, 1) from board)
, 1 , 0, #{content}, #{ip} ,#{filename}, #{filesize}
)
</insert>
</mapper>
BoardDTO
package board.dto;
import java.sql.Date;
public class BoardDTO {
private int num; //일련번호
private String writer;
private String subject;
private String passwd; //수정/삭제용비번
private Date reg_date; //java.sql.Date 작성일자
private int readcount; //조회수
private int ref; //게시물그룹
private int re_step; // 게시물 그룹의 순번
private int re_level; //답변의 단계
private String content; //clob 4GB 까지 입력가능
private String ip;
private int comment_count; //댓글의 갯수
private String filename; //첨부파일 이름
private int filesize; //파일 사이즈
private int down; //다운로드 횟수
private String ext;//첨부파일 확장자
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
public String getWriter() {
return writer;
}
public void setWriter(String writer) {
this.writer = writer;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getPasswd() {
return passwd;
}
public void setPasswd(String passwd) {
this.passwd = passwd;
}
public Date getReg_date() {
return reg_date;
}
public void setReg_date(Date reg_date) {
this.reg_date = reg_date;
}
public int getReadcount() {
return readcount;
}
public void setReadcount(int readcount) {
this.readcount = readcount;
}
public int getRef() {
return ref;
}
public void setRef(int ref) {
this.ref = ref;
}
public int getRe_step() {
return re_step;
}
public void setRe_step(int re_step) {
this.re_step = re_step;
}
public int getRe_level() {
return re_level;
}
public void setRe_level(int re_level) {
this.re_level = re_level;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public int getComment_count() {
return comment_count;
}
public void setComment_count(int comment_count) {
this.comment_count = comment_count;
}
public String getFilename() {
return filename;
}
public void setFilename(String filename) {
this.filename = filename;
}
public int getFilesize() {
return filesize;
}
public void setFilesize(int filesize) {
this.filesize = filesize;
}
public int getDown() {
return down;
}
public void setDown(int down) {
this.down = down;
}
public String getExt() {
return ext;
}
public void setExt(String ext) {
this.ext = ext;
}
@Override
public String toString() {
return "BoardDTO [num=" + num + ", writer=" + writer + ", subject=" + subject + ", passwd=" + passwd
+ ", reg_date=" + reg_date + ", readcount=" + readcount + ", ref=" + ref + ", re_step=" + re_step
+ ", re_level=" + re_level + ", content=" + content + ", ip=" + ip + ", comment_count=" + comment_count
+ ", filename=" + filename + ", filesize=" + filesize + ", down=" + down + ", ext=" + ext + "]";
}
}
BoardDAO
package board.dao;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import board.dto.BoardDTO;
import sqlmap.MybatisManager;
public class BoardDAO {
//싱글톤
private static BoardDAO instance;
public static BoardDAO getInstance(){
if(instance==null){
instance=new BoardDAO();
}
return instance;
}
//외부에서 new를 할 수 없음
private BoardDAO(){
}
public List<BoardDTO> list(){
List<BoardDTO> list=null;
SqlSession session=null;
try{
session=MybatisManager.getInstance().openSession();
list=session.selectList("board.list");
}catch(Exception e){
e.printStackTrace();
}finally{
if(session!=null)session.close();
}
return list;
}
public void insert(BoardDTO dto){
SqlSession session=null;
try{
session
=MybatisManager.getInstance().openSession();
session.insert("board.insert", dto);
session.commit();
}catch(Exception e){
e.printStackTrace();
}finally{
if(session !=null) session.close();
}
}
}
BoardController
package board;
import java.io.File;
import java.io.IOException;
import java.util.Enumeration;
import java.util.List;
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;
import org.apache.ibatis.reflection.SystemMetaObject;
import com.oreilly.servlet.MultipartRequest;
import com.oreilly.servlet.multipart.DefaultFileRenamePolicy;
import com.oreilly.servlet.multipart.MultipartParser;
import board.dao.BoardDAO;
import board.dto.BoardDTO;
import common.Constant;
@WebServlet("/board_servlet/*")
public class BoardController extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String url=request.getRequestURL().toString();
String contextPath=request.getContextPath();
//dao 객체 생성
BoardDAO dao=BoardDAO.getInstance();
if(url.indexOf("list.do")!=-1){
//dao에 자료 요청
List<BoardDTO> list=dao.list();
//출력 페이지로 넘기기 전에 저장
request.setAttribute("list", list);
//출력 페이지로 포워딩
String page="/board/list.jsp";
RequestDispatcher rd
=request.getRequestDispatcher(page);
rd.forward(request, response);
}else if(url.indexOf("insert.do")!=-1){
//파일업로드 처리
File uploadDir=new File(Constant.uplLoadPath(request));
if(!uploadDir.exists()){
uploadDir.mkdirs();
}
//request, 업로드 경로, 업로드 제한 용량, 문자셋, 중복파일
MultipartRequest multi=
new MultipartRequest(
request,
Constant.uplLoadPath(request),
Constant.MAX_UPLOAD,
"utf-8",
new DefaultFileRenamePolicy() );
String filename="";
int filesize=0;
try{
//첨부파일 집합
Enumeration files =multi.getFileNames();
while(files.hasMoreElements()){//다음 요소가 있으면
String file1=(String)files.nextElement();
//첨부파일의 이름
filename=multi.getOriginalFileName(file1);
File f1=multi.getFile(file1);
if(f1!=null){
filesize=(int)f1.length();//파일크기
}
}
}catch(Exception e){
e.printStackTrace();
}
//폼에서 입력한 값들
String writer=multi.getParameter("writer");
String subject=multi.getParameter("subject");
String content=multi.getParameter("content");
String passwd=multi.getParameter("passwd");
String ip=request.getRemoteAddr();//ip 주소
BoardDTO dto=new BoardDTO();
dto.setWriter(writer);
dto.setSubject(subject);
dto.setContent(content);
dto.setPasswd(passwd);
dto.setIp(ip);
dto.setFilename(filename);
dto.setFilesize(filesize);
//테이블에 저장
System.out.println(dto.toString());
dao.insert(dto);
//목록으로 이동
String page=contextPath+"/board_servlet/list.do";
response.sendRedirect(page);
}else if(url.indexOf("view.do")!=-1){
}else if(url.indexOf("commentList.do")!=-1){
}else if(url.indexOf("comment_add.do")!=-1){
}else if(url.indexOf("download.do")!=-1){
}else if(url.indexOf("reply.do")!=-1){
}else if(url.indexOf("passwd_check.do")!=-1){
}else if(url.indexOf("update.do")!=-1){
}else if(url.indexOf("delete.do")!=-1){
}else if(url.indexOf("search.do")!=-1){
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ include file="../include/header.jsp" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script src="http://code.jquery.com/jquery-3.2.1.min.js"></script>
</head>
<body>
<c:redirect url="/board_servlet/list.do"/>
</body>
</html>
list.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ include file="../include/header.jsp" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script src="http://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(function(){
$("#btnWriter").click(function(){
location.href="${path}/board/write.jsp";
});
});
</script>
<style type="text/css">
table{
width :900px;
}
</style>
</head>
<body>
<h2>게시판</h2>
<p><button type="button" id="btnWriter">글쓰기</button></p>
<table border="1" >
<tr>
<th>번호</th>
<th>이름</th>
<th>제목</th>
<th>날짜</th>
<th>조회수</th>
<th>첨부파일</th>
<th>다운로드</th>
</tr>
<c:forEach var="dto" items="${list}">
<tr>
<td>${dto.num}</td>
<td>${dto.writer}</td>
<td>${dto.subject }</td>
<td>${dto.reg_date}</td>
<td>${dto.readcount}</td>
<td>${dto.filename }</td>
<td>${dto.down }</td>
</tr>
</c:forEach>
</table>
</body>
</html>
write.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ include file="../include/header.jsp" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script src="http://code.jquery.com/jquery-3.2.1.min.js"></script>
<style type="text/css">
table {
width:700px;
}
</style>
</head>
<body>
<h2>게시판 쓰기</h2>
<form name="form1" id="form1" method="post"
action="${path}/board_servlet/insert.do"
enctype="multipart/form-data">
<table border="1" >
<tr>
<td>이름</td>
<td><input type="text" name="writer" ></td>
</tr>
<tr>
<td>제목</td>
<td><input type="text" name="subject" size="60" ></td>
</tr>
<tr>
<td>본문</td>
<td><textarea rows="5" cols="100" name="content"></textarea></td>
</tr>
<tr>
<td>첨부파일</td>
<td><input type="file" name="file1" ></td>
</tr>
<tr>
<td>비밀번호</td>
<td><input type="password" name="passwd" ></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="확인">
</td>
</tr>
</table>
</form>
</body>
</html>
게시판글쓰기
|
게시판 쓰기
|
댓글 ( 4)
댓글 남기기