board.QnaDTO

board.QnaDAO


1.새글입력 메서드명 : setContent()




글쓰기 : writeForm.jsp

답글쓰기 : rewriteForm.jsp

글리스트 : listView.jsp

뷰페이지 : contentView.jsp


table : qnaBoard

글번호 : num (primary key)

글제목 : title

글내용 : content

원본글 : ref(원본글이면 원본글의 num, 답변글이면,? 원본글의 num?)

답글순서 : step ( 최신글이면 1, ++ )

들여쓰기 : depth(원본글의 답변이면 1, 답변글의 답변글이면 2)



******************************************************************



Q&A 테이블


create table qnaboard(

num number(6) primary key,

title varchar2(2000),

content varchar2(3000),

ref number(6),

step numbeR(6),

depth number(6)


)



******************************************************************



QnaDTO.java


package board;


public class QnaDTO {

private int num;

private String title;

private String content;

private int ref;

private int step;

private int depth;

public int getNum() {

return num;

}

public void setNum(int num) {

this.num = num;

}

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 int getRef() {

return ref;

}

public void setRef(int ref) {

this.ref = ref;

}

public int getStep() {

return step;

}

public void setStep(int step) {

this.step = step;

}

public int getDepth() {

return depth;

}

public void setDepth(int depth) {

this.depth = depth;

}

}




******************************************************************



package board;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;

import com.sun.corba.se.spi.orbutil.fsm.State;

public class QnaDAO {
private String user = "user02";
private String password = "user02";
private String url = "jdbc:oracle:thin:@192.168.116.128:1521:xe";
private String dirver = "oracle.jdbc.driver.OracleDriver";
private Connection con;
private PreparedStatement st;
private ResultSet rs;
public QnaDAO(){
try {
Class.forName(dirver);
con = DriverManager.getConnection(url, user, password);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/*
//setDummy 메소드 실행
public static void main(String[] args) {
QnaDAO q = new QnaDAO();
q.setDummy();
}
//Dummy data 만드는 메서드
public void setDummy(){
String sql = "insert into qnaboard values(?,?,?,?,0,0)";
try {
st = con.prepareStatement(sql);
for(int i=8 ; i<120 ; i++){
st.setInt(1, i);
st.setString(2, "title"+i);
st.setString(3, "content"+i);
st.setInt(4, i);
st.executeQuery();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
*/
//총 게시물 수를 받아오는 메서드
public int getCount(){
   int result = 0;
String sql = "select count(num) from qnaboard";
try {
st = con.prepareStatement(sql);
rs = st.executeQuery();
if(rs.next()){
result = rs.getInt(1);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
//리스트 받아오기
public ArrayList<QnaDTO> getList(int curpage){
int start = 0;
int last = 0;
start = (curpage-1)*10+1;
last = curpage*10;
String sql ="select * from"
+"(select rownum R, A.* from" 
+"(select * from qnaboard order by num desc) A)"
+ "where R between ? and ?";
ArrayList<QnaDTO> ar = new ArrayList<>();
try {
st = con.prepareStatement(sql);
st.setInt(1, 1);
st.setInt(2, 10);
rs = st.executeQuery();
while(rs.next()){
QnaDTO q = new QnaDTO();
q.setNum(rs.getInt("num"));
q.setTitle(rs.getString("title"));
q.setContent(rs.getString("content"));
q.setRef(rs.getInt("ref"));
q.setStep(rs.getInt("step"));
q.setDepth(rs.getInt("depth"));
ar.add(q);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return ar;
}
//부모 새글 쓰기
public int setContent(QnaDTO qd){
int result = 0;
try {
int max = getMax()+1;
String sql = "insert into qnaboard values(?, ?, ?, ?, ?, ?)";
st = con.prepareStatement(sql);
st.setInt(1, max);
st.setString(2, qd.getTitle());
st.setString(3, qd.getContent());
st.setInt(4, max); //원본글의 ref는 자신의 num
st.setInt(5, 0); //원본글의 스텝 0
st.setInt(6, 0); //원보글의 들여쓰기 0
result = st.executeUpdate();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
//글의 최신번호를 가져오기위한 내부 메서드
private int getMax(){
int max = 0;
try {
String sql = "select max(num) from qnaboard";
Statement st = con.createStatement();
rs = st.executeQuery(sql);
if(rs.next()){
max = rs.getInt(1);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return max;
}
}



******************************************************************

index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<a href="writeForm.jsp">글쓰기</a>
<a href="listView.jsp?curpage=1">리스트보기</a>
</body>
</html>


******************************************************************


writeForm.jsp


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

    pageEncoding="UTF-8"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

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

<title>Insert title here</title>

</head>

<body>

원본글쓰기 폼

<form action="writePro.jsp" method="post">


<input type="text" name="title"><br>

<textarea rows="20" cols="20" name="content"></textarea><br>

<input type="submit" value="등록">


</form>


</body>

</html>



******************************************************************


writePro.jsp


<%@page import="board.QnaDAO"%>

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

    pageEncoding="UTF-8"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

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

<title>Insert title here</title>

</head>

<body>

<jsp:useBean id="qd" class="board.QnaDTO" />

<jsp:setProperty property="*" name="qd"/>

<%

QnaDAO qa = new QnaDAO();

int result = qa.setContent(qd);

if(result>0){

%>

<h2>글쓰기 성공</h2>

<a href="#">리스트 보기</a>

<% }else{ %>

<h2>글쓰기 실패</h2>

<a href="./qnaWrite.jsp">글쓰기</a>

<% }  %>



</body>

</html>


******************************************************************


listView.jsp



<%@page import="board.QnaDTO"%>

<%@page import="java.util.ArrayList"%>

<%@page import="board.QnaDAO"%>

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

    pageEncoding="UTF-8"%>

<%

int curpage = Integer.parseInt(request.getParameter("curpage"));

QnaDAO qdao = new QnaDAO();

ArrayList<QnaDTO> ar = qdao.getList(curpage);

int total = qdao.getCount();

if(total%10==0){

total = total/10;

}else{

total = (total/10)+1;

}

%>    

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

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

<title>Insert title here</title>

</head>

<body>

<table>

<tr>

<td>번호</td><td>제목</td>

</tr>

<%

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

%>

<tr>

<td><%=ar.get(i).getNum() %></td>

<td><%=ar.get(i).getTitle() %></td>

</tr>

<%} %>

<%

for(int i=1 ; i<=total ; i++){%>

<a href="listView.jsp?curpage=<%=i %>"><%=i %></a>

<% }%>

</table>

</body>

</html>




******************************************************************

답글 들여쓰기 쿼리문





insert into qnaboard values(1,'test','test',1,0,0)

insert into qnaboard values(2,'test2','test2',2,0,0)


insert into qnaboard values(3,'retest' ,'retest',1,1,1)


insert into qnaboard values(4,'re2test','re2test',1,1,1)


insert into qnaboard values(5,'re3test','re3test',1,1,1)



update qnaboard set step=step+1 where ref=1 and step>0;


select * from qnaboard


select * from qnaboard order by ref desc;


select * from qnaboard order by step asc;



select * from qnaboard order by ref desc, step asc







******************************************************************


parameter 받아오는 방법

1. get방식

2. useBean 액션태그 사용


******************************************************************


자바 전체 주석 한번에

씨프트 + 화살표로 블럭지정  + 컨트롤 + 슬러시







블로그 이미지

테시리

,
게시판실습




블로그 이미지

테시리

,

dothome : mySQL 지원


mvc2 공부


영어 공부


*********************************************************

<답글>


글번호     작성자     제목     내용      re글번호     들여쓰기                     순서

1           ad          ad       ad        1             0                             0

2           ad2        ad2      ad2       2             0                            0

3           re          re         re        1             0(1번글들여쓰기)+1=1     +1

4           re2         re2       re2        2            1                       

5           re3         re3       re3        3            1(3번글들여쓰기)+1=2

7           re4         re4       re4       1             1번들여쓰기+1          3번글순서+1


답글 ==> 들여쓰기



교재 p.128 제10강 게시판 만들기


필드명

ref : 원본글

step : 답변글 순서

depth : 들여쓰기


교재 p.133 writeForm 글쓰기폼


******************************************************************



글번호   작성자   제목   내용   ref    depth     step

1         ad       ad      ad     1       0         0

2         re       re        re     1       1         1



답변글

num=?

int ref = 누구의 글 1

int step = 답변글 순서 0

int depth = 들여쓰기 0

number : 2


where ref=1 and step>0


step = 1

depth = depth +1



num = ?


number = 3


글번호   작성자   제목   내용   ref    depth     step

1         ad       ad      ad     1       0         0

2         re       re        re     1       1        step=step+1=2

3         res     res       res     1      1         1



******************************************************************



글번호   작성자   제목   내용   ref    depth     step

1          ad      ad     ad     1       0         0

2          ads    sfd     ad     1        1        1



신규글 ==>  글번호 = ref  새글은 글번호와 ref가 일치



1. 글번호? =  max(no)+1




















블로그 이미지

테시리

,

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>Insert title here</title>

<script type="text/javascript">

function check() {

var d = document.myForm.id;

alert(d.value);

}


function  idCheck() {

var yId = document.myForm.id;

// location.href="./result1.html?id="+yId.value;

window.open("./result1.html?id="+yId, "check", "width=500px height=300px") ;

}

</script>

</head>

<body>


<form action="result1.html" method="post" name="myForm">

<input type="text" name="id" id="d1"><button onclick="idCheck()">중복확인</button>

<input type="password" name="pw">

<input type="submit" onclick="=return check()">

</form>

</body>

</html>



********************************************************************


개인프로젝트 작업



-멤버DB

-테이블명 : recipemember

-필드명

- id

- pw

- name

- phone

- gender

- job

- age




********************************************************************


pool설정

11버젼부터 ojdbc6

서버 과부하를 막기위해 권장?




context.xml


<?xml version="1.0" encoding="UTF-8"?>

<Context>

    <Resource name="jdbc/myOracle" 

    auth="Container"

   driverClassName="oracle.jdbc.driver.OracleDriver"

   type="javax.sql.DataSource"

           username="user01" 

   password="user01" 

             url="jdbc:oracle:thin:@192.168.116.128:1521:xe"

          maxActive="500"  

  maxIdle="100"      

   maxWait="-1"/>    

</Context>



web.xml


<?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_3_1.xsd" id="WebApp_ID" version="3.1">

<resource-ref>

      <description>ConnectionPool</description>

      <res-ref-name>jdbc/myOracle</res-ref-name>

      <res-type>javax.sql.DataSource</res-type>

      <res-auth>Container</res-auth>

  </resource-ref>

</web-app>




test.jsp



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

    pageEncoding="UTF-8"%>

<%@ page import="javax.naming.*" %>

<%@ page import="javax.sql.*" %>

<%@ page import="java.sql.*" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

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

<title>Insert title here</title>

</head>

<body>

<%

Context initCtx = new InitialContext();

Context envCtx = ( Context ) initCtx.lookup( "java:comp/env" );

DataSource ds = ( DataSource ) envCtx.lookup( "jdbc/myOracle" );

Connection con = ds.getConnection();


String sql = "select * from member";

PreparedStatement st = con.prepareStatement(sql);

ResultSet rs = st.executeQuery();

if(rs.next()){

%>

<%= rs.getInt("age") %>

<%= rs.getString("id") %>

<% } %>

</body>

</html>





********************************************************************





블로그 이미지

테시리

,
구글 캠퍼스 스타트업 리쿠르팅 데이 참가




블로그 이미지

테시리

,

공지사항

글쓰기 

글쓰기 처리

리스트

컨텐트

수정

삭제



프로젝트 폴더구성, 파일구성, DB테이블 구성



*****************************************************


게시글 DB 테이블 필드명


==> 번호, 작성자, 타이틀, 내용, TIMESTAMP


JSP 교재 참고하기



create table test(

today timestamp

);




블로그 이미지

테시리

,

팀프로젝트에 앞서서 개별프로젝트 먼저 진행



뭐 만들지?


고민


*********************************************************


게시판 밑에 페이지 블록 묶음과 이전, 다음 링크 만들기


BoardDAO.java


package myDB;


import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.util.ArrayList;

import java.util.List;


public class BoardDAO {

private String user = "user01";

private String password = "user01";

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

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

private Connection con;

private PreparedStatement st;

private ResultSet rs;

public BoardDAO(){

try {

Class.forName(driver);

con = DriverManager.getConnection(url, user, password);

} catch (Exception e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

public List<BoardDTO> getlist(int curpage){

int start = 0;

int last = 0;

start = curpage*10-9;

last = curpage*10;

String sql="select * from (select rownum R, A.* from"

+"(select * from noticboard order by no desc) A)"

          +"where R between ? and ?";

List<BoardDTO> ar = new ArrayList<>();

try {

st = con.prepareStatement(sql);

st.setInt(1, start);

st.setInt(2, last);

   rs = st.executeQuery();

   while(rs.next()){

    BoardDTO b = new BoardDTO();

    b.setNo(rs.getInt("no"));

    b.setTitle(rs.getString("title"));

    b.setWriter(rs.getString("writer"));

    b.setContents(rs.getString("contents"));

    ar.add(b);

   }

} catch (Exception e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

return ar;

}

//총 게시글 수 리턴메소드 ==> 첫페이지, 마지막페이지 리턴으로 변경

public int getCount(int curpage){

int firstPage = 0; //처음 들어갈 번호

int lastPage = 0; //마지막 들어갈 번호

int block = 1 ; //블럭 그룹번호

int pagePerBlock = 5 ;  //한 블럭에 들어갈 페이지 번호 수

int count  = 0;

//받아온 curpage를 가지고 어느 block에 속하는지를 구하는 조건문

if(curpage%pagePerBlock==0){

block = curpage/pagePerBlock ;

}else{

block = curpage/pagePerBlock + 1 ;

}

//block을 이용해서 firstpage, lastpage를 구하는 공식

//firstPage = (block-1)*pagePerBlock+1;

//lastPage = block*pagePerBlock ;

/*

String sql = "select count(no) from noticboard";

try {

st = con.prepareStatement(sql);

rs = st.executeQuery();

if(rs.next()){

count = rs.getInt(1);

}

} catch (Exception e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

int t = count%10;

count = count/10;

if(t!=0){

count = count +1;

}

return count;

*/

return block;

}

public int getC(){

int totalContent = 0; //전체 글 수

int totalPage = 0; //전체 페이지 수 

int totalBlock = 0;

//전체 글 수를 받아 오는 query문

String sql = "select count(no) from noticboard";

try {

st = con.prepareStatement(sql);

rs = st.executeQuery();

if(rs.next()){

totalContent = rs.getInt(1);

}

} catch (Exception e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

// 전체 글 수를 이용해서 전체 페이지 수를 구하는 공식

if(totalContent%10==0){

totalPage = totalContent/10 ;

}else{

totalPage = (totalContent/10) +1;

}

// totalPage를 이용해서 전체 block 수를 구하는 공식

if(totalPage%5==0){

totalBlock = totalPage/5;

}else{

totalBlock = (totalPage/5)+1;

}

return totalBlock;

}

}





listView.jsp

<%@page import="myDB.BoardDTO"%>
<%@page import="java.util.List"%>
<%@page import="myDB.BoardDAO"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    
<%
int curpage = Integer.parseInt(request.getParameter("curpage"));
BoardDAO d = new BoardDAO();
List<BoardDTO> ar = d.getlist(curpage);
int block = d.getCount(curpage);
int totalBlock = d.getC();
%>    
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>공지사항페이지</title>
<link type="text/css" href="./practice.css" rel="stylesheet">
<style type="text/css">
table{
border:  1px solid blue;
border-collapse: collapse;
border-spacing: 0px;
width: 500px;
margin : 0 auto;
}
div{
width: 500px;
margin : 0 auto;
}
h3{
width : 500px;
margin : 0 auto;
}
</style>
</head>
<body>
<h3>
<a href="index.jsp">메인으로</a><br>
공지사항입니다</h3><br>
<table>
<tr>
<td>번호</td><td>제목</td><td>작성자</td>
</tr>
<%
for(int i=0;i<ar.size();i++){
%>
<tr>
<td><%=ar.get(i).getNo() %></td>
<td><%=ar.get(i).getTitle() %></td>
<td><%=ar.get(i).getWriter() %></td>
</tr>
<%} %>
</table>
<p></p>
<div>
 
<%
   int start = (block-1)*5+1;
int last = block*5;
if(block > 1){%>
<a href="listView.jsp?curpage=<%=start-1%>">[이전]</a>
<%}
for(int i=start ; i<= last ; i++){
%>
<a href="listView.jsp?curpage=<%=i %>"><%=i %></a>
<%}
if(block < totalBlock){
%>
<a href="listView.jsp?curpage=<%=last+1 %>">[다음]</a>
<% }%>
</div>



</body>
</html>



*********************************************************


어제 작업한 부분에서

로그인한 회원정보 보는 페이지

1. 처음에는 DAO에 정보보는 메소드를 만들어서 불러왔으나 최근에 가입한 회원정보를 불러옴 (쿼리문 수정해야할 것으로 보임)

2. 해결책 , 차라리 세션으로 객체를 생성해서 한번에 불러오니 해결




*********************************************************


private String user = "DB아이디";
private String password = "DB암호";
private String url="jdbc:oracle:thin:@서버아이피:서버SID";
private String driver="oracle.jdbc.driver.OracleDriver";
private Connection con;
private PreparedStatement st;
private ResultSet rs;  // select 문은 리턴타입이 리절트셋


*********************************************************


게시판 연습

index2.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<a href="viewList.jsp?curpage=1">공지사항보기</a>
</body>
</html>


viewList.jsp

<%@page import="notice_board.NoticeDTO"%>
<%@page import="java.util.List"%>
<%@page import="notice_board.NoticeDAO"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
int curPage = Integer.parseInt(request.getParameter("curpage") );
NoticeDAO nd = new NoticeDAO();
    List<NoticeDTO> ar =  nd.getList(curPage);
int block = nd.getBlock(curPage);
int start = block*5 -4;
int last = block*5;
int [] numAr = nd.getTotalBlock();
//int count = nd.getCount();
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<style type="text/css">
table {
width: 800px;
border: 1px solid blue;
border-spacing: 0px;
border-collapse: collapse;
margin: 0 auto;
}
td {
border: 1px dashed blue;
text-align: center;
}
div {
width: 800px;
margin: 0 auto;
}
</style>
</head>
<body>
<table>
<tr>
<td>글번호</td><td>글제목</td><td>작성자</td>
</tr>
<%
for(int i=0;i<ar.size();i++){
%>
<tr>
<td><%=ar.get(i).getNo() %></td>
<td><%=ar.get(i).getTitle() %></td>
<td><%=ar.get(i).getWriter() %></td>
</tr>
<%} %>
</table>
<div>
<% if(block>1){ %>
<a href="viewList.jsp?curpage=<%= start-1%>">[이전]</a>
<%} %>
<%
if(block>=numAr[1]){
last = numAr[0];
}
for(int i=start; i<=last;i++){ %>
<a href="viewList.jsp?curpage=<%=i %>"><%=i%></a>
<%}
if(block < numAr[1]){%>
<a href="viewList.jsp?curpage=<%=last+1 %>">[다음]</a>
<%}%>
</div>
</body>
</html>


NoticeDTO.java

package notice_board;

public class NoticeDTO {
private int no;
private String writer;
private String title;
private String content;
public int getNo() {
return no;
}
public void setNo(int no) {
this.no = no;
}
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 getContents() {
return content;
}
public void setContents(String content) {
this.content = content;
}
}



NoticeDAO.java

package notice_board;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class NoticeDAO {
private String user = "user01";
private String password = "user01";
private String url="jdbc:oracle:thin:@192.168.116.128:1521:xe";
private String driver="oracle.jdbc.driver.OracleDriver";
private Connection con;
private PreparedStatement st;
private ResultSet rs;
public NoticeDAO(){
try {
Class.forName(driver);
con = DriverManager.getConnection(url, user, password);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//******************************************************//
//DB에서 리스트를 꺼내오는 메소드
public List<NoticeDTO> getList(int curPage){
List<NoticeDTO> ar = new ArrayList<>();
//curPage =1 , 2
int start = 0 ; // setInt 1번에 들어갈 번호 , 1 , 11 ...
int last = 0; // setInt 2번에 들어갈 번호 , 10 , 20 ...
//start = curPage*10-9;
start = (curPage*10)-9;
last = curPage * 10;
String sql ="select * from"
+"(select rownum R, A.* from" 
+"(select * from noticboard order by no desc) A)"
+"where R between ? and ?";
try {
st = con.prepareStatement(sql);
st.setInt(1, start);
st.setInt(2, last);
rs = st.executeQuery();
while(rs.next()){
NoticeDTO n = new NoticeDTO();
n.setNo(rs.getInt("no"));
n.setTitle(rs.getString("title"));
n.setWriter(rs.getString("writer"));
n.setContents(rs.getString("contents"));
ar.add(n);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return ar;
}
public int[] getTotalBlock(){
int [] numAr = new int [2];
int pages=0;// 총페이지 수를 담을 변수
String sql = "select count(no) from noticboard";
try {
st = con.prepareStatement(sql);
rs = st.executeQuery();
if(rs.next()){
pages = rs.getInt(1);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(pages%10 ==0){
pages = pages/10;
}else {
pages = pages/10+1;
}
int totalBlock=0;//총 블럭수를 담을 변수
if(pages%5==0){
totalBlock= pages/5;
}else {
totalBlock= pages/5+1;
}
numAr[0]=pages;
numAr[1]=totalBlock;
return numAr;
}
//******************************************************//
//페이지당 블럭을 알아오는 메서드
//block 번호를 가지고 페이지 번호를 알아내려함
//block 이 1이라면 페이지 번호는 1~5까지 출력
//block 이 2 이라면 페이지 번호는 6~10까지 출력
public int getBlock(int curPage){
int block=0; //블럭의 번호를 저장하는 변수
int pagePerBlock=5; //블럭당 페이지 수
if(curPage%pagePerBlock==0){
block = curPage/pagePerBlock;
}else{
block = curPage/pagePerBlock+1;
}
return block;
}
}




*********************************************************

다음주까지 개인프로젝트 끝


같은 주제를


다른 사람들이 다른 방식으로 표현


주제 : 백주부가 지금까지 발표한 레시피를 소개하는 페이지


요구사항


1.회원제 : 회원가입 후 로그인

2.공지사항 : 관리자

3.방명록 : 회원만

4.Q&A게시판 : 회원만

5.게시판 리스트 보기 : 비회원도 가능, 그러나 상세보기는 회원만 가능


방명록,Q&A게시판을 사용하기 위해서는 회원가입, 로그인



[회원정보]

-이름

-아이디

-비밀번호

-전화번호

-성별

-직업

-나이



요구사항

검색기능 - 게시판(option)

관리자모드 - 회원검색기능(수정,삭제)(option)

관리자는 모든 게시판을 수정 삭제 가능(option)

회원은 각자의 정보를 수정할 수 있는 페이지가 있어야함.



테이블


회원테이블

공지사항테이블

방명록테이블

Q&A테이블


DB에 총 4개의 테이블 구성



PPT로 계획서 만들어서 제출



폴더, 패키지 나누기



*******************************************************

카페24 - DB호스팅 - MySQL 










블로그 이미지

테시리

,

JSP 교재


p.128 제10강 게시판만들기

p.139 글목록 가져오기




SELECT * FROM (

 SELECT ROWNUM R, A.* FROM (select nun, title, wdate

FROM board order by ?? desc) A




위에거 해석 

1. ROWNUM R : 가상의 rownum(행의수?) 변수를 R이라고 지정한다.

2. (select nun, title, wdate FROM board order by ?? desc) A  : board테이블에서 내림차순으로 nun, title, wdate를 뽑아 가상의 테이블 A로 지정

3. A.* : 가상의 테이블 A의 모든 필드를 불러온다.






최신글 3개 가져오기

select * from 

(select rownum R, A.* from

(select * from noticboard order by no desc) A)

where R between 1 and 3



>

1. (select * from NOTICBOARD order by no desc) A) : 가상의 테이블 A만듦.

2. ROWNUM R : 가상의 변수 rownum (행의수)을 R로 지정

3. A.* : A에서 모든 것을 가져온다. 




서브쿼리 ! : 쿼리안에 또다른 select 문이 등장



데이터베이스 교재

p.48 제 7강 서브쿼리




select count(no), max(no) from noticboard

select rownum R, writer from noticboard


이거 스크랩북에 다시 쳐보기



오늘쓴 스크랩북



select * from NOTICBOARD 


select * from 

(select ROWNUM R, A.* from 

(select * from NOTICBOARD order by no desc) A)

where R between 1 and 3


select * form 

(select * from noticboard order by no desc)

order by title desc


select * from 

(select rownum R, A.* from

(select * from noticboard order by no desc) A)

where R between 1 and 3


select count(no), max(no) from noticboard

select rownum R, writer from noticboard





*****************************************************************************8




DB연결 DAO클래스

DbDAO.java


package jsp_0914;


import java.sql.DriverManager;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Statement;

import java.util.ArrayList;

import java.util.List;


import com.sun.corba.se.pept.transport.Connection;


public class DbDAO {

private String user = "user01";

private String password = "user01";

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

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

private java.sql.Connection con;

private PreparedStatement st;

private ResultSet rs;

 

public DbDAO(){

try {

Class.forName(driver);

con = DriverManager.getConnection(url, user, password);

} catch (Exception e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

public List<BoardDTO> getlist(int curpage){

//String sql = "select * from noticboard order by no desc";

int start=0;

int last=0;

start = curpage*10-9;

last = curpage*10;

String sql = "select * from "

+ "(select rownum R, A.* from "

+ "(select * from noticboard order by no desc) A) "

+ "where R between ? and ?";

List<BoardDTO> ar = new ArrayList<>();

try {

st = con.prepareStatement(sql);

st.setInt(1, start);

st.setInt(2, last);

rs = st.executeQuery();

while(rs.next()){

BoardDTO b = new BoardDTO();

b.setNo(rs.getInt("no"));

b.setTitle(rs.getString("title"));

b.setWriter(rs.getString("writer"));

b.setContents(rs.getString("contents"));

   ar.add(b);

}

} catch (Exception e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

return ar;

}

 

//총 게시물의 수를 리턴하는 메소드

public int getCount(){

int count = 0;

String sql = "select count(no) from noticboard";

try {

st = con.prepareStatement(sql);

rs = st.executeQuery();

if(rs.next()){

count = rs.getInt(1);

}

} catch (SQLException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

int t = count%10;

count = count/10;

if(t!=0){

count=count+1;

}

return count;

}

/*

//임의의 글 30개 작성메소드

public void setDb(){

try {

Statement st = con.createStatement();

int num = 11;

for(num=11 ; num<41 ; num++ ){

String sql = "insert into noticboard values";

sql=sql+"("+num+", '"+num+"', '"+num+"', '"+num+"')";

st.executeQuery(sql);

}

} catch (Exception e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

public static void main(String[] args) {

DbDAO d = new DbDAO();

d.setDb();

}


*/

}





게시판DTO클래스
BoardDTO.java

package jsp_0914;

public class BoardDTO {
private int no;
private String writer;
private String title;
private String contents;
public int getNo() {
return no;
}
public void setNo(int no) {
this.no = no;
}
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 getContents() {
return contents;
}
public void setContents(String contents) {
this.contents = contents;
}
}



리스트보기
listView.jsp

<%@page import="com.sun.org.apache.bcel.internal.generic.CPInstruction"%>
<%@page import="java.util.List"%>

<%@page import="jsp_0914.BoardDTO"%>

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

int curpage =  Integer.parseInt( request.getParameter("curpage") );
DbDAO d = new DbDAO();
List<BoardDTO> ar = d.getlist(curpage);
int count = d.getCount();
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<style type="text/css">
table{
border : 1px solid red;
border-collapse: collapse;
border-spacing: 0px;
width : 500px;
margin : 0 auto;
}
div{
width:  500px;
margin : 0px auto;
}
</style>
</head>
<body>
<table>
<tr>
<td>번호</td><td>제목</td><td>작성자</td>
</tr>
<%
for(int i=0;i<ar.size();i++){
%>
<tr>
<td><%=ar.get(i).getNo() %></td>
<td><%=ar.get(i).getTitle() %></td>
<td><%=ar.get(i).getWriter() %></td>
</tr>
<%} %>
</table>

<p></p>
<div>
<%
for(int i=1 ; i<=count ; i++ ){
%>
<a href="listView.jsp?curpage=<%=i %>"><%=i %></a>
 <%} %>
</div>


</body>
</html>



인덱스

index.jsp



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

    pageEncoding="UTF-8"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

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

<title>Insert title here</title>

</head>

<body>

<a href="listView.jsp?curpage=1">리스트</a>

</body>

</html>











********************************************************************


notice_list.txt



** 게시물 리스트를 그룹화 **


1. DB에서 모든 게시물을 get


 1) 조건 : 내림차순으로 정렬

    sql = select * from noticboard order by no desc


 2) 조건 : 한 페이지에 보일 리스트의 갯수만 get

   select * from

   (select rownum R, A.* from 

   (select * from noticboard order by no desc) A )

   where r > ? and r < ?


    select * from

   (select rownum R, A.* from 

   (select * from noticboard order by no desc) A )

   where between ? and ?



   r > ? and r < ?  == 이 부분  : between ? and ? 과 같은 의미



   

2. rownum 구하기

  1) jsp 페이지에서 페이지 번호를 매개변수를 통해서 get (curpage);

  2) start = curpage*10-9

  3) last = curpage*10



3. jsp 페이지에 curpage 번호를 자동으로 프린트

 1) DB에서 총 게시물의 갯수를 get (count);

 2) int t = count%10;

 3) count = count/10;

 4) if(t != 0 ){ count++ }



4. 페이지블록 만들기 (번호10개씩 끊기, 내일 )





********************************************************************










































블로그 이미지

테시리

,

주의사항


회원가입 form에서 


각 인풋의 name 명과 DTO 클래스의 변수명은 무조건 일치시켜야 한다. ( jsp: usebean으로 연결되니까)


그리고


DB의 필드명과 DTO 변수명은 일치시키는 것이 알아보기 편하다.




***************************************************************************




로그인



일반회원 로그인

000님 환영합니다

공지사항보기 회원정보수정 회원탈퇴 로그아웃

공지사항보기->리스트->글쓰기x

컨탠츠뷰 -> 수정x,삭제x,목록O



admin 로그인

000님 환영합니다

공지사항보기 회원정보수정 전체회원보기 회원탈퇴 로그아웃

공지사항보기->리스트->글쓰기O

컨탠츠뷰 -> 수정O,삭제O,목록O




writer는 admin으로 고정, 수정x


블로그 이미지

테시리

,


oracle_select_option.txt


1. select 문

SELECT [DISTINCT] { *, column, [alias], , , }

FROM table_name

[WHERE conditions]

[ORDER bY {column, expression} [ ASC | DESC] ];


DISTINCT : 중복되는 행을 제거하는 옵션

* : 테이블의 모든 column을 출력

alias : 해당 column에 대해서 다른 이름을 부여 할때

table_name : 질의 대상 테이블 명

WHERE : 조건을 만족 하는 행들만 검색

conditions : column, 표현식, 상수 및 비교연산자

ORDER BY : 질의 결과 정렬을 위한 옵션 (ASC:오름차순(default), DESC:내림차순)



2. WHERE 절에 올 수 있는 연산자

 BETWEEN a and b : a와 b 사이의 데이터를 출력(a, b 값 포함)

  SELECT empno, ename FROM emp where  sal BETWEEN 3000 AND 5000;

  -->  급여가 3000에서 5000 사이인 사원만 출력


IN (list,,) : list의 값들 중 어느 하나와 일치하는 데이터 출력

   SELECT empno, ename FROM emp where  empno IN(7900, 7934);

  -->  사번이 7900 또는  7934번인 사원의 사번과 이름 출력


LIKE : 문자 형태로 일치하는 데이터를 출력

" % " : 여러개의 문자열을 나타내는 와일드카드

  SELECT empno, ename FROM emp where UPPER(ename) like '%K%';

  -->  이름 중 'K' 문자가 들어가 있는 사원 정보 출력

" _ " :  단 하나자의 문자열을 나타내는 와일드카드

  SELECT empno, ename FROM emp where UPPER(ename) like '_I%';

  -->  '_' 는 한문자, 이름 중 'I' 문자가 두번째에 위치한 사원 정보 출력


IS NULL : NULL 값을 가진 데이터를 출력

NOT BETWEEN a AND b : a와 b 사이에 있지 않은 데이터를 출력(a, b값 포함하지 않음)

NOT IN (list) : list와 일치 하지 않는 데이터를 출력

  SELECT empno, ename FROM emp where  empno NOT IN(7900, 7934);

  -->  사번이 7900 또는  7934번이 아닌 사원의 사번과 이름 출력

NOT LIKE : 문자형태와 일치 하지 않는 데이터를 출력

NOT IS NULL : NULL 값을 갖지 않는 데이터를 출력

 


***********************************************************


select * from saram



select * from saram where age>10 and age<23  order by salary desc

같은의미 다른 명령어

select * from SARAM where age between 10 and 23 order by salary desc



> ASC : 오름차순 정렬, DESC : 내림차순 정렬



***********************************************************


session.setattribute("string",object)  ------> 세션정보를 서버에 저장



***********************************************************

Cookie (교재 p.159 : 제 12강 Cookie&Session 참고)

Cookie ! 오픈마켓에서 오늘 본 품목을 옆에 띄워줄때 응용된다.

쿠키는 string 이름과 string value로 이루어져 있다.

session과 cookie의 차이

session은 서버에 저장,
cookie는 client에 저장


쿠키의 구성요소
1.이름 : 각각의 쿠키를 구별하는데 사용되는 이름
2.값 : 쿠키의 이름과 관련된 값
3.유효시간 : 쿠키의 유지시간
4.도메인 : 쿠키를 전송할 도메인
5.경로 : 쿠키를 전송할 요청자료

쿠키관련 메소드

 반환형

메소드 

설명 

 String 

 getName()

 쿠키의 이름을 구한다

 String 

 getValue()

 쿠키의 값을 구한다

 void

 setValue(String value)

 쿠키의 값을 지정한다

 void

 setDomain(String pattern)

 이 쿠키가 전송될 서버의 도메인을 지정한다

 String 

 getDomain()

 쿠키의 도메인을 구한다

 void

 setPath(String url)

 쿠키를 전송할 경로를 지정한다

 String 

 getPath()

 쿠키의 전송경로를 구한다

 void

 setMaxAge(int expiry)

 쿠키의 유효시간을 초단위로 지정한다. 음수를 입력할 경우 웹 브라우저를 닫을 때 쿠키가 함께 삭제 된다

 int

 getMaxAge()

 쿠키의 유효시간을 구한다


실습


<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
String sing = "choa";
session.setAttribute("id", sing);
Cookie c = new Cookie("idol","iu");
c.setValue("exid");
c.setMaxAge(60*60*24*7);
response.addCookie(c);
%>
<%=c.getName() %> : 쿠키의 이름<br>
<%=c.getValue() %> : value of cookie
</body>
</html>


결과

idol : 쿠키의 이름
exid : value of cookie


***********************************************************

배열로담기

cookie1.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
String sing = "choa";
session.setAttribute("id", sing);
Cookie c = new Cookie("idol","iu");
c.setValue("exid");
c.setMaxAge(60*60*24*7);
response.addCookie(c);
%>
<%=c.getName() %> : 쿠키의 이름<br>
<%=c.getValue() %> : value of cookie<br>
<a href="./cookie2.jsp">cookie2</a>
</body>
</html>

cookie2.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
Cookie [] co = request.getCookies(); //배열로 얻어온다. getCookie's'()
for(int i=0;i<co.length;i++){ %><br>
쿠키의 이름 :<%=co[i].getName() %><br>
쿠키의 벨류 :<%=co[i].getValue() %>
<% }%>
%>
</body>
</html>




***********************************************************

세션, 쿠키가 남긴 데이터를 이용해서 분석

알리바바

그 넓은 영토에서 어떻게 하루만에 배송이 가능한가?

세션, 쿠키를 이용한 데이터 분석으로 

미리 구매가 많이 일어나는 지점에 가져다 놓는다.


***********************************************************

삼성페이, 카카오페이에서 벌어들이는 수익은?

수수료, ? ===> 미미한 수익

데이터를 모으기 위함. ==> 미래를 예측

***********************************************************

게시판 만들기



작성자 , 내용, 제목, 번호



이중 프라이머리 키는 ??  ==> 번호 , 번호는 자동생성되도록,

일단 테이블 만들기

create table noticBoard(
no number(5) primary key,
writer varchar2(100),
title varchar2(100),
contents varchar2(500));

commit;

이클립스 스크랩북에서 입력
insert into noticBoard values (1,'admin','test1','test1')
insert into noticBoard values (2,'admin','test2','test2')
select * from noticBoard

select count(no) from noticBoard 
>개수 세기 결과 count(no) : 2

count는 게시글의 갯수


1,2, 5

insert into noticBoard values (5,'admin','test5','test5')
select * from noticBoard

select count(no) from noticBoard
>게시글의 수 : 3을 리턴

select max(no) from noticBoard
>가장 큰 번호 : 5를 리턴

max는 번호 중에 가장 큰 수를 리턴;


이 경우에는 max를 사용하는 것이 낫다.




select count(no), max(no) from noticBoard




게시판폼

nWriteForm.jsp


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

    pageEncoding="UTF-8"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

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

<title>Insert title here</title>

<style type="text/css">

table{


}

</style>

</head>

<body>

<form action="./noticePro.jsp" method="post">

<table border="1">

   <tr>

   <td width="30%">제  목 : </td>

    <td width="70%"><input type="text" name="title"><br></td>

   </tr>

<tr>

<td>작성자 : </td>

<td><input type="text" name="writer" ><br></td>

</tr>

<tr>

<td colspan=2>

내  용 : <br>

<textarea rows="20" cols="80" name="contents" ></textarea>

</td>

</tr>

<tr>

<td>

<input type="submit" value="등록">

<input type="reset" value="다시 작성">

</td>

</tr>

</table>

</form>

</body>

</html>



프로세스 noticePro.jsp


<%@page import="notice.NoticeBoardDAO"%>

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

    pageEncoding="UTF-8"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

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

<title>Insert title here</title>

</head>

<body>

<jsp:useBean id="n" class="notice.NoticeBoardDTO"/>

<jsp:setProperty property="*" name="n"/>

<%

NoticeBoardDAO bd = new NoticeBoardDAO();

int num = bd.setNotice(n);

if(num>0){%>

등록완료<br>

<a href="list.jsp">리스트보기</a>

      <%

      }else{

      response.sendRedirect("./nWriteForm.jsp");

      }

%>

%>

</body>

</html>



자바DAO NoticeBoardDAO.java


package notice;


import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Statement;

import java.util.ArrayList;


import com.sun.xml.internal.bind.v2.runtime.unmarshaller.XsiNilLoader.Array;


public class NoticeBoardDAO {


private String user = "user01";

private String password = "user01";

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

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

private Connection con;

private PreparedStatement st;

private ResultSet rs;

public NoticeBoardDAO(){

try {

Class.forName(driver); //드라이버 로딩

con = DriverManager.getConnection(url, user, password);

} catch (Exception e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}


//리스트 꺼내오기...

public ArrayList<NoticeBoardDTO> getList(){

ArrayList<NoticeBoardDTO> ar = new ArrayList<>();

String sql = "select no, title, writer from noticBoard order by no desc";

//sql문 스크랩북에서 확인하기

try {

st = con.prepareStatement(sql);

rs = st.executeQuery();

while(rs.next()){

NoticeBoardDTO n = new NoticeBoardDTO();

n.setNo(rs.getInt("no"));

n.setTitle(rs.getString("title"));

n.setWriter(rs.getString("writer"));

ar.add(n);

}

} catch (Exception e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

return ar;

}

//글쓰기 입력 메소드

public int setNotice(NoticeBoardDTO d){

int num = getNo();

String sql = "insert into noticBoard values(?, ?, ?, ?)";

try {

st = con.prepareStatement(sql);

st.setInt(1, num+1);

st.setString(2, d.getWriter());

st.setString(3, d.getTitle());

st.setString(4, d.getContents());

num = st.executeUpdate();

} catch (Exception e) {

num=0;

e.printStackTrace();

}

return num;

}

//글번호 최대값을 가져오는 메소드(1,2,5 번다음에 글쓰면 3이아니라 6이 오게해줌)

int getNo(){

String sql = "select max(no) from noticBoard";

int num=0;

try {

Statement st = con.createStatement();

rs = st.executeQuery(sql);

if(rs.next()){

num=rs.getInt(1);

}

} catch (Exception e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

return num;

}

public static void main(String[] args) {

NoticeBoardDAO n = new NoticeBoardDAO();

System.out.println(n.getNo());

}


}




자바 DTO  NoticeBoardDTO.java

package notice;

public class NoticeBoardDTO {
private int no;
private String writer;
private String title;
private String contents;
public int getNo() {
return no;
}
public void setNo(int no) {
this.no = no;
}
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 getContents() {
return contents;
}
public void setContents(String contents) {
this.contents = contents;
}
}


리스트  list.jsp

<%@page import="notice.NoticeBoardDTO"%>
<%@page import="java.util.ArrayList"%>
<%@page import="notice.NoticeBoardDAO"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    
 <%
  NoticeBoardDAO nd = new NoticeBoardDAO();
  ArrayList<NoticeBoardDTO> ar = nd.getList();
 %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<!-- table 사용해서 -->
<table border=1>
<tr>
<td>글번호</td>
<td>글제목</td>
<td>작성자</td>
</tr>
<% 
for(int i=0;i<ar.size();i++){
%>
<tr>
<td><%=ar.get(i).getNo() %></td>
<td><%=ar.get(i).getTitle() %></td>
<td><%=ar.get(i).getWriter() %></td>
</tr>
<%} %>
</table>
</body>
</html>



***********************************************************


DAO : DB와 연결하는 클래스


DTO : 변수(접근지정자 private)와 게터세터 메소드로 이루어진 클래스


***********************************************************


get 방식 : 링크를 클릭하는 것은 전부 get 방식이다.

post 방식



***********************************************************

a링크로 파라미터 넘기기  ?파라미터이름=값


newFile.jsp


<%@page import="notice.NoticeBoardDTO"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
NoticeBoardDTO n = new NoticeBoardDTO();
n.setNo(3);

%>

<a href="newFile2.jsp?n=<%=n.getNo()%>">test</a>
</body>
</html>


newFile2.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
String name = request.getParameter("n");
%>
<%=name %>
</body>
</html>


***********************************************************





***********************************************************




***********************************************************



블로그 이미지

테시리

,