Riucc's Storage
RSS
태그
관리
쓰기
카테고리
  • IT (593)
    • 정리 (0)
    • C# (42)
    • ASP.NET MVC (16)
    • JQuery&Javascript (12)
    • CSS (11)
    • 데이터베이스 (32)
    • Windows Server (6)
    • Active Directory (3)
    • Exchange (9)
    • JAVA (2)
    • JSP (39)
    • JSP 게시판 만들기 (21)
    • JSP 개발 참고 (15)
    • JSP 안드로이드 (4)
    • Servlet (17)
    • Spring (42)
    • HTML (14)
    • NodeJS (46)
    • MongoDB (11)
    • 리눅스 (18)
    • 자료구조 (16)
    • 아이폰 (24)
    • 안드로이드 (68)
    • API 활용하기 (10)
    • 소켓네트워크 (28)
    • 라즈베리파이 (11)
    • AWS클라우드 (10)
    • 빅데이터Hadoop (22)
    • 커널모듈프로그래밍 (8)
    • 기타 (10)
    • 자격증 (26)
Riucc's Storage

[JSP] - 게시물 작성 및 게시물 DB 출력하기

JSP 개발 참고|2018. 5. 4. 16:48
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

○ 게시물 작성 및 게시물 DB 출력하기 

 

// fileDTO.java


public class fileDTO {

String userPropilePicture;

String userWriteID;

String fileName;

String fileRealName;

String title;

String content;

int userCoinAmount;

int userLikeAmount;

int userCommentAmount;

int userReportAmount;

String userWriteTime;

// 생성자 생성

        public fileDTO() {}


public fileDTO(String userPropilePicture, String userWriteID, String fileName, String fileRealName, String title,

String content, int userCoinAmount, int userLikeAmount, int userCommentAmount, int userReportAmount,

String userWriteTime) {

super();

this.userPropilePicture = userPropilePicture;

this.userWriteID = userWriteID;

this.fileName = fileName;

this.fileRealName = fileRealName;

this.title = title;

this.content = content;

this.userCoinAmount = userCoinAmount;

this.userLikeAmount = userLikeAmount;

this.userCommentAmount = userCommentAmount;

this.userReportAmount = userReportAmount;

this.userWriteTime = userWriteTime;

}


public String getUserWriteTime() {

return userWriteTime;

}


public void setUserWriteTime(String userWriteTime) {

this.userWriteTime = userWriteTime;

}


public String getTitle() {

return title;

}



public String getUserPropilePicture() {

return userPropilePicture;

}


public void setUserPropilePicture(String userPropilePicture) {

this.userPropilePicture = userPropilePicture;

}


public String getUserWriteID() {

return userWriteID;

}


public void setUserWriteID(String userWriteID) {

this.userWriteID = userWriteID;

}


public int getUserCoinAmount() {

return userCoinAmount;

}


public void setUserCoinAmount(int userCoinAmount) {

this.userCoinAmount = userCoinAmount;

}


public int getUserLikeAmount() {

return userLikeAmount;

}


public void setUserLikeAmount(int userLikeAmount) {

this.userLikeAmount = userLikeAmount;

}


public int getUserCommentAmount() {

return userCommentAmount;

}


public void setUserCommentAmount(int userCommentAmount) {

this.userCommentAmount = userCommentAmount;

}


public int getUserReportAmount() {

return userReportAmount;

}


public void setUserReportAmount(int userReportAmount) {

this.userReportAmount = userReportAmount;

}


public void setTitle(String title) {

this.title = title;

}


public String getContent() {

return content;

}


public void setContent(String content) {

this.content = content;

}


public String getFileName() {

return fileName;

}

public void setFileName(String fileName) {

this.fileName = fileName;

}

public String getFileRealName() {

return fileRealName;

}

public void setFileRealName(String fileRealName) {

this.fileRealName = fileRealName;

}

}


// fileDAO.java


public class fileDAO {

private Connection conn;

// 생성자를 통해 db연결 해줌

public fileDAO() {

try {

String dbURL = "jdbc:mysql://localhost:3306/test";

String dbID = "root";

String dbPW = "wlgns930";

Class.forName("com.mysql.jdbc.Driver");

conn = DriverManager.getConnection(dbURL, dbID, dbPW);

} catch(Exception e) {

e.printStackTrace();

}

}


        // 게시물을 DB에 업로드하기 위한 함수

public int upload(String userPropilePicture, String userWriteID, String userFileName, String userFileRealName,

String userWriteTitle, String userWriteContent, 

int userCoinAmount, int userLikeAmount, int userCommentAmount, int userReportAmount) {

String SQL = "INSERT INTO userwritetest VALUES (?, ?, now(), ?, ?, ?, ?, ?, ?, ?, ?)";

try {

PreparedStatement pstmt = conn.prepareStatement(SQL);

pstmt.setString(1,  userPropilePicture);

pstmt.setString(2,  userWriteID);

pstmt.setString(3,  userFileName);

pstmt.setString(4,  userFileRealName);

pstmt.setString(5,  userWriteTitle);

pstmt.setString(6,  userWriteContent);

pstmt.setInt(7,  userCoinAmount);

pstmt.setInt(8,  userLikeAmount);

pstmt.setInt(9,  userCommentAmount);

pstmt.setInt(10,  userReportAmount);


return pstmt.executeUpdate();

} catch(Exception e) {

e.printStackTrace();

}

return -1;

}

        // 게시물 DB에서 출력하기 위한 함수

public ArrayList<fileDTO> getWriteList(){

ArrayList<fileDTO> writeList = null;

PreparedStatement pstmt = null;

ResultSet rs = null;

// 최신순 정렬

String SQL = "SELECT * FROM userwriteTest ORDER BY userWriteTime desc";

try {

pstmt = conn.prepareStatement(SQL);

rs = pstmt.executeQuery();

writeList = new ArrayList<fileDTO>();

while(rs.next()) {

fileDTO file = new fileDTO();

file.setUserPropilePicture(rs.getString("userPropilePicture"));

file.setUserWriteID(rs.getString("userWriteID"));

// 시간을 오전 오후로 나누어서 표시를 해주자

int chatTime = Integer.parseInt(rs.getString("userWriteTime").substring(11, 13));

String timeType = "오전";

if(Integer.parseInt(rs.getString("userWriteTime").substring(11, 13)) >= 12) {

timeType = "오후";

chatTime -= 12;

}

file.setUserWriteTime(rs.getString("userWriteTime").substring(0, 11) + " " + timeType + " " + chatTime + "시 " + rs.getString("userWriteTime").substring(14, 16) + "분");

file.setFileName(rs.getString("userFileName"));

file.setFileRealName(rs.getString("userFileRealName"));

file.setTitle(rs.getString("userWriteTitle"));

file.setContent(rs.getString("userWriteContent"));

file.setUserCoinAmount(rs.getInt("userCoinAmount"));

file.setUserLikeAmount(rs.getInt("userLikeAmount"));

file.setUserCommentAmount(rs.getInt("userCommentAmount"));

file.setUserReportAmount(rs.getInt("userReportAmount"));

writeList.add(file);

}

} catch(Exception e) {

e.printStackTrace();

} finally {

try {

if(rs != null) rs.close();

if(pstmt != null) pstmt.close();

} catch(Exception e) {

e.printStackTrace();

}

}

return writeList;

}

}


// userWrite.jsp (게시물 작성위한 폼이 있는 jsp 파일)


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

<!DOCTYPE html>

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>Insert title here</title>




<!--  부트스트랩 파일로 만들어서 땡겨오기 -->

<link rel="stylesheet" href="css/bootstrap.min.css">

<link rel="stylesheet" href="js/jquery.min.js">

<link rel="stylesheet" href="js/popper.min.js">

<link rel="stylesheet" href="js/bootstrap.min.js">


<!--  이미지파일 올리면 미리보게 하기 위한 것 -->

<script type="text/javascript">

var InputImage = (function loadImageFile() {

if (window.FileReader) {

var ImagePre;

var ImgReader = new window.FileReader();

var fileType = /^(?:image\/bmp|image\/gif|image\/jpeg|image\/png|image\/x\-xwindowdump|image\/x\-portable\-bitmap)$/i;


ImgReader.onload = function(Event) {

if (!ImagePre) {

var newPreview = document.getElementById("imagePreview");

ImagePre = new Image();

ImagePre.style.width = "200px";

ImagePre.style.height = "140px";

newPreview.appendChild(ImagePre);

}

ImagePre.src = Event.target.result;


};


return function() {

var img = document.getElementById("image").files;

if (!fileType.test(img[0].type)) {

alert("이미지 파일을 업로드 하세요");

return;

}

ImgReader.readAsDataURL(img[0]);

}

}

document.getElementById("imagePreview").src = document

.getElementById("image").value;

})();

</script>


</head>

<body>


<!-- Nav -->

<nav class="navbar navbar-default bg-primary navbar-fixed-top">

<div class="container-fluid">

<div class="navbar-header">

<a class="navbar-brand text-white" href="index.jsp">사이트 로고</a>

</div>


<ul class="nav justify-content-center">

<li class="nav-item"><a class="nav-link text-white" href="#">대세글</a></li>

<li class="nav-item"><a class="nav-link text-white" href="#">최신글</a></li>

<li class="nav-item"><a class="nav-link text-white" href="#">인기글</a></li>

</ul>


<ul class="nav justify-content-end">

<li class="nav-item"><a class="nav-link text-white" href="./userWrite.jsp">글쓰기</a></li>

<li class="nav-item"><a class="nav-link text-white" href="./userLogin.jsp">로그인+회원가입</a></li>

</ul>

</div>

</nav>


<div class="container-fluid">

<div class="row">

<div class="col-lg-3"></div>

<div class="col-lg-6 mt-5">

<div class="panel-group">

<div class="panel panel-default">

<div class="panel-body">

<form role="form" method="post" action="./userWriteAction.jsp" enctype="multipart/form-data">

<div class="form-group">

<label for="usr">제목:</label> <input type="text" class="form-control" name="title">

</div>


<div class="form-group">

<label for="comment">내용:</label>

<textarea class="form-control" rows="5" name="comment"></textarea>

</div>


<!-- 이미지 불러와서 미리보게하기 -->

<div id="imagePreview"></div><br>

<input id="image" type="file" name="file" onchange="InputImage();">

<div class="form-group">

<label for="exampleInputFile">이미지 파일(.jpg .gif .png)</label>

</div>

<div class="form-group mt-5">

<button type="submit" class="btn btn-primary mr-3">글쓰기</button>

<button type="submit" class="btn btn-primary">지우기</button>

</div>

</form>

</div>

</div>

</div>

</div>

<div class="col-lg-3"></div>

</div>

</div>


</body>

</html>


// userWrite.jsp (게시물을 DB에 올리기 위한 jsp)


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

    pageEncoding="UTF-8"%>

    

<!-- 파일업로드 위한 라이브러리 임포트 -->

<%@ page import="file.fileDAO" %>

<%@ page import="java.io.File" %>

<!-- 파일 이름이 동일한게 나오면 자동으로 다른걸로 바꿔주고 그런 행동 해주는것 -->

<%@ page import="com.oreilly.servlet.multipart.DefaultFileRenamePolicy" %>

<!-- 실제로 파일 업로드 하기 위한 클래스 -->

<%@ page import="com.oreilly.servlet.MultipartRequest" %>


<%

    request.setCharacterEncoding("UTF-8");

// 제목과 내용 테스트를 위한 출력

String title = null;

String comment = null;

// 아까 만든 폴더를 가져올 수 있게함

  String uploadDir = this.getClass().getResource("").getPath();

uploadDir = uploadDir.substring(1,uploadDir.indexOf(".metadata"))+"testSite/WebContent/uploadImage";

System.out.println("절대경로 : " + uploadDir); 

 

// 총 100M 까지 저장 가능하게 함

int maxSize = 1024 * 1024 * 100;

String encoding = "UTF-8";

// 사용자가 전송한 파일 정보 토대로 업로드 장소에 크기 및 파일 업로드 수행할 수 있게 

MultipartRequest multipartRequest

= new MultipartRequest(request, uploadDir, maxSize, encoding,

new DefaultFileRenamePolicy());

// 이전 클래스 name = "file" 실제 사용자가 저장한 실제 네임

String fileName = multipartRequest.getOriginalFileName("file");

// 실제 서버에 업로드 된 파일시스템 네임

String fileRealName = multipartRequest.getFilesystemName("file");

// enctype="multipart/form-data" 에서 request.getParameter null 문제

// request.getParameter 대신에 multi객체.getParameter로 받아야 null이 안뜬다 !

// 제목과 내용 입력이 되었다면 변수로 데이터값을 넣어줌

if(multipartRequest.getParameter("title") != null){

title = multipartRequest.getParameter("title");

}

if(multipartRequest.getParameter("comment") != null){

comment = multipartRequest.getParameter("comment");

}

// 디비에 업로드 메소드

new fileDAO().upload("profile1.PNG", "rhkwk424", fileName, fileRealName, title, comment, 4, 5, 6, 7);

    // 테스트 위한 콘솔 출력

    System.out.println("유저프로필명 : profile1.PNG");

    System.out.println("유저아이디 : rhkwk424");

    System.out.println("파일명 : " + fileName);

    System.out.println("실제파일명 : " + fileRealName); 

    System.out.println("제목 : " + title);

    System.out.println("내용 : " + comment);  

    System.out.println("코인 수 : 4");

    System.out.println("좋아요 수 : 5");

    System.out.println("댓글 수 : 6");

    System.out.println("감사 수 : 7");


%>


<script>alert('글쓰기 성공'); </script>

<script>location.href = 'index.jsp';</script>

</body>

</html>


// index.jsp (게시물을 출력하기 위한 jsp)


<!--  메인 9칸  게시물 출력-->

<div class="col-lg-9 mt-4">

    <!--  실제 DB에서 데이터를 뽑아오기 위한 구문 -->

<%

ArrayList<fileDTO> writeList = new ArrayList<fileDTO>();

writeList = new fileDAO().getWriteList();

for(int i=0; i<writeList.size(); i++){

fileDTO write = writeList.get(i);

%>

<!--  본문 데이터  -->

<div class="row">

<div class="col-lg-9">

<div class="card bg-light mt-3">

<div class="card-header bg-light">

<div class="row">

<div class="col-8 text-left">

<img src="./userProfilePicture/<%= write.getUserPropilePicture() %>" class="img-circle"

width="32px" height="27px">&nbsp;<%= write.getUserWriteID() %> &nbsp;<small><%= write.getUserWriteTime() %></small>

</div>

<div class="col-4 text-right"></div>

</div>

</div>

<div class="card-body">

<div class="row">

<div class="col-3">

<img src="./uploadImage/<%= write.getFileRealName() %>" width="150px" height="100px">

</div>

<div class="col-9">

<h5 class="card-title"><%= write.getTitle() %></h5>

<p class="card-text"><%= write.getContent() %></p>

<div class="row">

<div class="col-9 text-left">

금액<span style="color: red;"> <%= write.getUserCoinAmount() %></span> 추천<span

style="color: red;"> <%= write.getUserLikeAmount() %></span> 댓글<span style="color: red;">

<%= write.getUserCommentAmount() %></span> 감사<span style="color: red;"> <%= write.getUserReportAmount() %></span>

</div>

<div class="col-3 text-right">

<a onclick="return confirm('보팅 하시겠습니까?')"

href="./likeAction.jsp?evaluationID=">추천</a> <a

onclick="return confirm('신고 하시겠습니까?')"

href="./likeAction.jsp?evaluationID=">신고</a>

</div>

</div>

</div>

</div>

</div>

</div>

</div>

</div>


<%

}

%>


</div>




저작자표시 (새창열림)

'JSP 개발 참고' 카테고리의 다른 글

[JSP] - 게시물 상세 DB 출력하기  (0) 2018.05.05
[JSP] - 게시물 검색 및 검색된 내용의 DB 출력하기  (0) 2018.05.05
[JSP] - 이미지 파일 올렸을 때 미리보기  (0) 2018.05.03
[JSP] - 파일 enctype="multipart/form-data" 사용 시 request.getParameter null 해결방법  (0) 2018.05.02
[JSP] - 네이버 스마트에디터 사용  (0) 2018.05.02

댓글()
카테고리
  • IT (593)
    • 정리 (0)
    • C# (42)
    • ASP.NET MVC (16)
    • JQuery&Javascript (12)
    • CSS (11)
    • 데이터베이스 (32)
    • Windows Server (6)
    • Active Directory (3)
    • Exchange (9)
    • JAVA (2)
    • JSP (39)
    • JSP 게시판 만들기 (21)
    • JSP 개발 참고 (15)
    • JSP 안드로이드 (4)
    • Servlet (17)
    • Spring (42)
    • HTML (14)
    • NodeJS (46)
    • MongoDB (11)
    • 리눅스 (18)
    • 자료구조 (16)
    • 아이폰 (24)
    • 안드로이드 (68)
    • API 활용하기 (10)
    • 소켓네트워크 (28)
    • 라즈베리파이 (11)
    • AWS클라우드 (10)
    • 빅데이터Hadoop (22)
    • 커널모듈프로그래밍 (8)
    • 기타 (10)
    • 자격증 (26)
최근 등록 현황
최근 글
최근 월별 글
최근 댓글
최근 글
최근 월별 글
최근 댓글
최근 글
최근 월별 글
최근 댓글
달력
지난달
2025.6
다음달
일월화수목금토
1234567
891011121314
15161718192021
22232425262728
2930
태그 구름
  • nodejs express
  • 안드로이드
  • 정보처리산업기사 총정리
  • 정보처리산업기사 요약
  • 이클립스 디비 연동
  • 카카오 로그인 연동
  • 정보처리산업기사 16년
  • 정규화
  • 소켓
  • 카카오 로그인
  • jsp
  • 데이터베이스
  • 정보처리산업기사 정리
  • 리눅스
  • 정보처리산업기사 필기
  • 정보처리산업기사 15년
  • 정보처리산업기사 16년 필기
  • 안드로이드 intent
  • 소켓 프로그래밍
  • 정보처리기사 실기 정리
  • 이클립스 mysql 연동
  • 정보처리산업기사 15년 필기
  • 정규형
  • 안드로이드 카카오 로그인 연동
  • HTML
  • 커널 모듈 프로그래밍
  • 정보처리산업기사 필기 정리
  • nodejs MySQL 연동하기(Connection Pool)
  • 안드로이드 카카오 로그인
  • 자료구조
카운터
전체 방문자
오늘
어제
Skin by M1REACT. Designed by M1STORY.TISTORY.COM. Valid XHTML 1.0 and CSS 3. Copyright ⓒ Riucc's Storage. All rights reserved.

티스토리툴바