2016년 8월 5일 금요일

05day JSP

리플라이(*)

  • 댓글
  • 기본테이블 - 추가컬럼
리플라이
  • 알고리즘
    • 기본적인 알고리즘
리스트
  • 쓰기
  • 자세히 보기
    • 수정
    • 삭제
    • 답글         seq를 사용해서 어느글에 대한 답글을 만듦
글쓰기
  • seq
  • grp = seq
  • grps = 0
  • grpl = 0
답글쓰기
  • seq
  • grp      group
    • 조상글 seq 일치
    • 부모글 grp 일치
  • grps  같은 group 내부의 순서를 결정
    • 부모글의 같은 grp에서 
      • 부모들의 grps보다 큰 grps 번호있으면 무조건 +1
      • 자신은 부모의 grps +1
  • grpl   글의 깊이(답글 들여쓰기)
    • 부모글의 grpl+1
          seq grp grps grpl
부모1 1 1 0 0 (write)
부모2 2   2 0 0 (w)
답1-1 3 1 4←3←2←1 1 (reply)
답1-2 4    1     2←1 1 (r)
답1-3 5    1     1 1 (r)
답1-1-1 6 1 6←5←4 2 (r)
딥1-1-2 7 1 5←4 2 (r)
답1-2-1 8    1 3 2 (r)

---order by grp  desc, grps asc
부2 2 2
부1 1 1
1-3 5 1
1-2 4 1
1-2-1 8 1
1-1 3 1
1-1-2 7 1
1-1-1 6 1



1
create table reply1(
 seq            number                            not null   primary key,
 grp  number      not null,
 grps  number      not null,
 grpl  number      not null, 
 subject       varchar2(100)                     not null,
 writer          varchar2(12)                      not null,
 mail           varchar2(50),
 password    varchar2(12)                      not null,
 content      varchar2(2000),
 hit            number                            not null,
 wip           varchar2(15)                      not null,
 wdate        date                                not null
 );

insert into reply1 values (board_seq.nextval, board_seq.currval, 0,0, '제목', '이름', 'test@test.com', '1234', '내용',
0, '000.000.000.000', sysdate);


2. board_list1
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import = "java.sql.Connection" %>
<%@ page import = "java.sql.PreparedStatement" %>
<%@ page import = "java.sql.ResultSet" %>
<%@ page import = "java.sql.SQLException" %>

<%@ page import = "javax.naming.Context" %>
<%@ page import = "javax.naming.InitialContext" %>
<%@ page import = "javax.naming.NamingException" %>
<%@ page import = "javax.sql.DataSource" %>
<%
    request.setCharacterEncoding("utf-8");

    int cpage = 1;
    if(request.getParameter("cpage")!=null && !request.getParameter("cpage").equals("")){
        cpage = Integer.parseInt(request.getParameter("cpage"));
    }
    //페이지당 출력 데이터 갯수
    int recordPerPage =10;
    //전체 데이터 갯수
    int totalRecord = 0;
    //전체 페이지 갯수
    int totalPage = 1;
    //페이지당 블럭 갯수
    int blockPerPage = 5;
    
    Connection conn = null;
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    StringBuffer result = new StringBuffer();
    
    try{
        Context initCtx = new InitialContext();
        Context envCtx = (Context)initCtx.lookup("java:comp/env");
        DataSource dataSource = (DataSource)envCtx.lookup("jdbc/oracle");
        
        conn = dataSource.getConnection();
        
        String sql = "select seq, grpl, subject, writer, to_char(wdate,'YY.MM.DD') wdate, hit, trunc(sysdate-wdate) wgap from reply1 order by grp desc, grps asc";
        //Resultset 옵션주기
        pstmt = conn.prepareStatement(sql, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        
        rs= pstmt.executeQuery();
        
        //전체데이터 갯수
        rs.last(); //마지막 데이터를 읽음
        totalRecord = rs.getRow(); //마지막 데이터 행번호를 가져옴
        rs.beforeFirst(); //데이터를 다시 처음으로 올림
        
        //전체 페이지 갯수
        totalPage = ((totalRecord-1)/recordPerPage) +1;
        
        //페이지를 넘길떄 처음 읽을 데이터의 행   0,10,20,30,40,...
        int skip=(cpage-1)*recordPerPage;
        //ResultSet에 읽고싶은 위치를 지정
        if(skip!=0)rs.absolute(skip);
        
        //recordPerPage만큼 짤려서 화면에 출력
        for(int i=0; i<recordPerPage && rs.next();i++){
            String seq = rs.getString("seq");
            
            //들여쓰기
            int grpl = rs.getInt("grpl");
            String sgrpl = "";
            for(int j = 1; j<=grpl; j++){
                sgrpl += "&nbsp;&nbsp;";
            }
            
            String subject = rs.getString("subject");
            String writer = rs.getString("writer");
            String wdate = rs.getString("wdate");
            String hit = rs.getString("hit");
            int wgap = rs.getInt("wgap");
            
            result.append("<table width='100%' border='0' cellpadding='0' cellspacing='0'>");
            result.append("<tr>");
            result.append("    <td height='1'></td>");
            result.append("</tr>");
            result.append("<tr>");
            result.append("    <td>");
            result.append("        <table width='100%' border='0' cellpadding='0' cellspacing='0'>");
            result.append("            <tr height='25' onMouseOver=\"this.className='evencell'\" onMouseOut=\"this.className=''\">");
            result.append("                <td width='40' align='center'>"+seq+"</td>");
            result.append("                <td>");
            result.append("                    <span style='width:370' class='elltxt'>");
            
            //답글 들여쓰기 입력
            if(grpl !=0){
                result.append(sgrpl +"<img src='../images/ico_re.gif' width='9'>");
            }
            
            result.append("                        <a href='board_view1.jsp?seq="+seq+"&cpage="+cpage+"'>"+subject+"</a>");
            
            //new이미지 24시간
            if(wgap == 0) {
                result.append("                <img src='../images/ico_n.gif' width='8' height='8' border='0' hspace='3'>");
            }
            
            result.append("                    </span>");
            result.append("                </td>");
            result.append("                <td width='100' align='center'>"+writer+"</td>");
            result.append("                <td width='80' align='center'>"+wdate+"</td>");
            result.append("                <td width='50' align='center'>"+hit+"</td>");
            result.append("            </tr>");
            result.append("        </table>");
            result.append("    </td>");
            result.append("</tr>");
            result.append("<tr>");
            result.append("    <td height='1'></td>");
            result.append("</tr>");
            result.append("<tr>");
            result.append("    <td align='center' class='imgline'></td>");
            result.append("</tr>");
            result.append("</table>");            
        }
        
    }catch(NamingException e){
        System.out.println("에러 : " + e.getMessage());
    }catch(SQLException e){
        System.out.println("에러 : " + e.getMessage());
    }finally{
        if(rs!=null) rs.close();
        if(pstmt!=null) pstmt.close();
        if(conn!=null) conn.close();
    }

%>
<html>
<head>
<title></title>
<meta http-equiv='Content-Type' content='text/html;charset=utf-8'>
<link rel='stylesheet' type='text/css' href='../images/common.css'>
</head>

<body bgcolor='#ffffff' topmargin='5' rightmargin='0' leftmargin='5' bottommargin='10'>

<table width='750px' border='0' cellpadding='0' cellspacing='0' align='center'>
<tr>
    <td height='23' bgcolor='#f0f0f0' align='right'></td>
</tr>
<tr>
    <td bgcolor='#ffffff' style='padding:20'>
        <table width='100%' border='0' cellpadding='0' cellspacing='0'>
        <tr>
            <td align='center' class='gline'></td>
        </tr>
        <tr>
            <td align='center'>
                <table width='100%' border='0' cellpadding='0' cellspacing='0' class='titlecell'>
                <tr height='25' align='center'>
                    <td width='40'>No</td>
                    <td>제목</td>
                    <td width='100'>이름</td>
                    <td width='80'>등록일</td>
                    <td width='50'>조회수</td>
                </tr>
                </table>
            </td>
        </tr>
        <tr>
            <td align='center' class='gline'></td>
        </tr>
        <tr>
            <td height='3'></td>
        </tr>
        </table>
        
<!-- 리스트 시작 -->
<%= result %>
<!-- 리스트 끝 -->

        <table width='100%' border='0' cellpadding='0' cellspacing='0'>
        <tr>
            <td width='500' height='30'>
<!-- 페이지 네비게이션 시작 -->
<%
    //화면 하단에 보이는 페이지 리스트 갯수
    int startBlock = ((cpage-1)/blockPerPage)*blockPerPage+1;
    int endBlock =startBlock+blockPerPage-1;
    if(endBlock >=totalPage){
        endBlock = totalPage;
    }
%>
<%
    //블럭 옮기기
    if(startBlock==1){
        out.println("<img src='../images/moveset/p_left_arrow_01_off.gif' align='absmiddle' hspace='2' border='0'>");
    }else{
        out.println("<a href='board_list1.jsp?cpage="+(startBlock-blockPerPage)+"'><img src='../images/moveset/p_left_arrow_01.gif' align='absmiddle' hspace='2' border='0'></a>");
    }
%>
                
    <%
        //페이지 옮기기 //page가 1일때는 이전페이지로 못감, 화살표 색깔off로 바뀜
        if(cpage==1){
            out.println("<img src='../images/moveset/p_left_arrow_02_off.gif' align='absmiddle' hspace='8' border='0'>");
        }else{
            out.println("<a href='board_list1.jsp?cpage="+(cpage-1)+"'><img src='../images/moveset/p_left_arrow_02.gif' align='absmiddle' hspace='8' border='0'></a>");
        }
    %>
                

                <img src='../images/moveset/p_orange.gif' align='absmiddle' hspace='3' border='0'>
        <%
            for(int i=startBlock;i<=endBlock; i++){
                if(cpage==i){
                    out.println("<b><u>["+i+"]</u></b>&nbsp;");
                }else{
                    out.println("<a href='board_list1.jsp?cpage="+i+"'>"+i+"</a>&nbsp;");
                }
                
            }
        %>
                <img src='../images/moveset/p_orange.gif' align='absmiddle' hspace='3' border='0'>
    <%
        //페이지 옮기기 //page가 끝페이지일때  다음 페이지로 못감, 화살표 색깔off로 바뀜
        if(cpage==totalPage){
            out.println("<img src='../images/moveset/p_right_arrow_02_off.gif' align='absmiddle' hspace='8' border='0'>");
        }else{
            out.println("<a href='board_list1.jsp?cpage="+(cpage+1)+"'><img src='../images/moveset/p_right_arrow_02.gif' align='absmiddle' hspace='2' border='0'></a>");
        }
    %>
<%
    //블럭 옮기기
    if(endBlock==totalPage){
        out.println("<img src='../images/moveset/p_right_arrow_01_off.gif' align='absmiddle' hspace='2' border='0'>");
    }else{
        out.println("<a href='board_list1.jsp?cpage="+(startBlock+blockPerPage)+"'><img src='../images/moveset/p_right_arrow_01.gif' align='absmiddle' hspace='2' border='0'></a>");
    }
%>
<!-- 페이지 네비게이션 끝 -->    
            </td>        
            <td align='right'>
                <a href='board_write1.jsp?cpage=<%=cpage%>'><img src='../images/btn_wri.gif' border='0'></a>
            </td>
        </tr>
        </table>
    </td>
</tr>
</table>        
        
<table width='750px' border='0' cellpadding='0' cellspacing='0' align='center'>
<tr>
    <td height='15' bgcolor='#f0f0f0' style='padding:5' align='center'></td>
</tr>
</table>

</body>
</html>


3board_reply1
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
    request.setCharacterEncoding("utf-8");
    String cpage = request.getParameter("cpage");
    String seq = request.getParameter("seq");
%>
<html>
<head>
<title></title>
<meta http-equiv='Content-Type' content='text/html;charset=utf-8'>
<link rel='stylesheet' type='text/css' href='../images/common.css'>
<script type="text/javascript">
    function ChkForm() {
        //필수 입력값 검사
        if(document.wfrm.subject.value.trim() ==""){
            alert('제목을 입력하셔야 합니다.');
            return false;
        }
        if(document.wfrm.writer.value.trim() ==""){
            alert('이름을 입력하셔야 합니다.');
            return false;
        }
        if(document.wfrm.password.value.trim() ==""){
            alert('암호를 입력하셔야 합니다.');
            return false;
        }
    }
</script>
</head>

<body bgcolor='#ffffff' topmargin='5' rightmargin='0' leftmargin='5' bottommargin='10'>

<table width='750px' border='0' cellpadding='0' cellspacing='0' align='center'>
<tr>
    <td height='23' bgcolor='#f0f0f0' align='right'></td>
</tr>
<tr>
    <td bgcolor='#ffffff' style='padding:20'>
        <form action='board_reply1_ok.jsp' method='post' name='wfrm' onSubmit='return ChkForm(this)'>
        <input type="hidden" name="seq" value="<%=seq%>">
        <input type="hidden" name="cpage" value="<%=cpage%>">
        <table width='100%' border='0' cellpadding='0' cellspacing='0'>
        <tr>
            <td width='70' style='padding:5' valign='top' align='right'>
                <font class='titdot'>&#149;&nbsp;</font>
                <font class='title'>제목</font> :
            </td>
            <td>
                <input type='text' name='subject' size='80' class='form'>
            </td>
        </tr>
        <tr>
            <td colspan='2' class='imgline'></td>
        </tr>
        <tr>
            <td width='70' style='padding:5' valign='top' align='right'>
                <font class='titdot'>&#149;&nbsp;</font>
                <font class='title'>작성자</font> :
            </td>
            <td>
                이름&nbsp;&nbsp;<input type='text' name='writer' size='10' maxlength='10' class='form'>&nbsp;&nbsp;/&nbsp;
                메일&nbsp;&nbsp;<input type='text' name='mail' size='40' maxlength='70' class='form'>&nbsp;&nbsp;/&nbsp;
                암호&nbsp;&nbsp;<input type='password' name='password' size='10' maxlength='10' class='form'>
            </td>
        </tr>
        <tr>
            <td colspan='2' class='imgline'></td>
        </tr>
        <tr>
            <td width='70' style='padding:5' valign='top' align='right'>
                <font class='titdot'>&#149;&nbsp;</font>
                <font class='title'>내용</font> :
            </td>
            <td>
                <textarea name='content' style='width:620;height:300' class='form'></textarea>
            </td>
        </tr>
        <tr>
            <td colspan='2' class='gline'></td>
        </tr>
        </table>

        <table width='100%' cellpadding='0' cellspacing='0' border='0'>
        <tr>
            <td width='500' height='30'>&nbsp;</td>
            <td align='right'>
                <input type='image' src='../images/btn_rep.gif' border='0'>&nbsp;
                <a href='board_list1.jsp?cpage=<%=cpage %>'><img src='../images/btn_list.gif' border='0'></a>
            </td>
        </tr>
        </table>
        </form>
    </td>
</tr>
</table>        
        
<table width='750px' border='0' cellpadding='0' cellspacing='0' align='center'>
<tr>
    <td height='15' bgcolor='#f0f0f0' style='padding:5' align='center'></td>
</tr>
</table>

</body>
</html>


4.board_reply_ok
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import = "java.sql.Connection" %>
<%@ page import = "java.sql.PreparedStatement" %>
<%@ page import = "java.sql.ResultSet" %>
<%@ page import = "java.sql.SQLException" %>
<%@ page import = "javax.naming.Context" %>
<%@ page import = "javax.naming.InitialContext" %>
<%@ page import = "javax.naming.NamingException" %>
<%@ page import = "javax.sql.DataSource" %>
<%-- 숨김페이지라서 HTML 코드 없음 --%>
<%
    request.setCharacterEncoding("utf-8");
    String seq = request.getParameter("seq");
    String cpage = request.getParameter("cpage");

    //클라이언트 정보 받기
    String subject =request.getParameter("subject");
    String writer =request.getParameter("writer");
    String mail =request.getParameter("mail");
    String password =request.getParameter("password");
    String content =request.getParameter("content");
    String wip = request.getRemoteAddr();
    
    //데이터베이스 연결
    Connection conn = null;
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    int flag = 1;  //데이터베이스 입력 성공실패 여부  성공0, 실패 1
    
    try{
        Context initCtx = new InitialContext();
        Context envCtx = (Context)initCtx.lookup("java:comp/env");
        DataSource dataSource = (DataSource)envCtx.lookup("jdbc/oracle");
        
        conn = dataSource.getConnection();
        
        //부모글의 grp 정보 가져오기
        String sql = "select grp, grps, grpl from reply1 where seq=?";
        pstmt = conn.prepareStatement(sql);
        pstmt.setString(1, seq);
        
        rs = pstmt.executeQuery();
        int grp = 0;
        int grps = 0;
        int grpl = 0;
        if(rs.next()){
            grp = rs.getInt("grp");
            grps = rs.getInt("grps");
            grpl = rs.getInt("grpl");
        }
        //자신보다 큰것들의 grps 증가
        sql= "update reply1 set grps = grps+1 where grp=? and grps>?";
        pstmt = conn.prepareStatement(sql);
        pstmt.setInt(1, grp);
        pstmt.setInt(2, grps);
        pstmt.executeUpdate();
        
        //답글 DB 입력
        sql = "insert into reply1 values (board_seq.nextval, ?, ?, ?, ?, ?, ?, ?, ?, 0, ?, sysdate)";
        pstmt = conn.prepareStatement(sql);
        pstmt.setInt(1, grp);
        pstmt.setInt(2, grps +1);
        pstmt.setInt(3, grpl +1);
        pstmt.setString(4, subject);
        pstmt.setString(5, writer);
        pstmt.setString(6, mail);
        pstmt.setString(7, password);
        pstmt.setString(8, content);
        pstmt.setString(9, wip);
        
        //executeUpdate 리턴 값: 영향 받은 행수
        int result = pstmt.executeUpdate();
        if(result ==1){
            flag =0;
        }
        
    }catch(NamingException e){
        System.out.println("에러 : " + e.getMessage());
    }catch(SQLException e){
        System.out.println("에러 : " + e.getMessage());
    }finally{
        if(rs !=null)rs.close();
        if(pstmt !=null)pstmt.close();
        if(conn !=null)conn.close();
    }
    
    //성공시 리스트페이지 , 실패시 이전페이지로 이동 자바스크립트
    out.println("<script type='text/javascript'>");
    if(flag ==0){
        out.println("alert('답글쓰기에 성공했습니다')");
        out.println("location.href='board_view1.jsp?cpage="+cpage+"&seq="+seq+"';");
    }else{
        out.println("alert('답글쓰기에 실패했습니다')");
        out.println("history.back()");
    }
    out.println("</script>");
    
%>


5.board_view1
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import = "java.sql.Connection" %>
<%@ page import = "java.sql.PreparedStatement" %>
<%@ page import = "java.sql.ResultSet" %>
<%@ page import = "java.sql.SQLException" %>

<%@ page import = "javax.naming.Context" %>
<%@ page import = "javax.naming.InitialContext" %>
<%@ page import = "javax.naming.NamingException" %>
<%@ page import = "javax.sql.DataSource" %>

<%
    //선택한 글의 seq 받아오기
    request.setCharacterEncoding("utf-8");
    String seq = request.getParameter("seq");
    String cpage = request.getParameter("cpage");
    
    String subject ="";
    String writer = "";
    String mail = "";
    String wip = "";
    String wdate = "";
    String hit = "";
    String content = "";
    
    //데이터베이스 연결
    Connection conn = null;
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    
    try{
        Context initCtx = new InitialContext();
        Context envCtx = (Context)initCtx.lookup("java:comp/env");
        DataSource dataSource = (DataSource)envCtx.lookup("jdbc/oracle");
        
        conn = dataSource.getConnection();
        
        //조회수 증가
        String sql = "update reply1 set hit=hit+1 where seq=?";
        pstmt = conn.prepareStatement(sql);
        pstmt.setString(1, seq);
        pstmt.executeUpdate();
        
        //view창 출력
        sql = "select subject, writer, mail, wip, wdate, hit, content from reply1 where seq=?";
        pstmt=conn.prepareStatement(sql);
        pstmt.setString(1, seq);
        
        rs = pstmt.executeQuery();
        if(rs.next()){
            subject = rs.getString("subject");
            writer = rs.getString("writer");
            mail = rs.getString("mail")==null?"":rs.getString("mail");   //공백처리
            wip = rs.getString("wip");
            wdate = rs.getString("wdate");
            hit = rs.getString("hit");
            content = rs.getString("content")==null?"":rs.getString("content").replaceAll("\n", "<br>"); //엔터키 처리
        }
        
    }catch(NamingException e){
        System.out.println("에러 : " + e.getMessage());
    }catch(SQLException e){
        System.out.println("에러 : " + e.getMessage());
    }finally{
        if(rs!=null) rs.close();
        if(pstmt!=null) pstmt.close();
        if(conn!=null) conn.close();
    }
%>

<html>
<head>
<title></title>
<meta http-equiv='Content-Type' content='text/html;charset=utf-8'>
<link rel='stylesheet' type='text/css' href='../images/common.css'>
</head>

<body bgcolor='#ffffff' topmargin='5' rightmargin='0' leftmargin='5' bottommargin='10'>

<table width='750px' border='0' cellpadding='0' cellspacing='0' align='center'>
<tr>
    <td height='23' bgcolor='#f0f0f0' align='right'></td>
</tr>
<tr>
    <td bgcolor='#ffffff' style='padding:20'>
        <table width='100%' cellpadding='0' cellspacing='0' border='0' align='center'>
        <tr>
            <td height='25'><font class='titdot'>&#149;&nbsp;</font><font class='title'>제목</font> | <%=subject %></td>
        </tr>
        <tr>
            <td class='imgline'></td>
        </tr>
        <tr>
            <td height='25'><font class='titdot'>&#149;&nbsp;</font><font class='title'>이름</font> | <%=writer %>(<%=mail %>) (<%=wip %>)</td>
        </tr>
        <tr>
            <td class='imgline'></td>
        </tr>
        <tr>
            <td height='25'>
                <table width='100%' cellpadding='0' cellspacing='0' border='0' align='center'>
                <tr>
                    <td><font class='titdot'>&#149;</font><font class='title'> 날짜</font> | <%=wdate %></td>
                    <td align='right'><font class='titdot'>&#149;&nbsp;</font><font class='title'>조회</font> | <%=hit %></td>
                </tr>
                </table>
            </td>
        </tr>
        <tr>
            <td  class='imgline'></td>
        </tr>
        <tr>
            <td height='100'><%=content %></td>
        </tr>
        </table>

        <table width='100%' border='0' cellspacing='0' cellpadding='0' align='center'>
        <tr>
            <td id='tailarea'></td>
        </tr>
        </table>

        <table width='100%' border='0' cellspacing='1' cellpadding='1'>
        <tr>
            <td colspan='2' class='gline'></td>
        </tr>
        <tr>
            <td width='500' height='30'>
                <a href='board_write1.jsp?cpage=<%=cpage %>'><img src='../images/btn_wri.gif' border='0'></a>                  
                <a href='board_modify1.jsp?seq=<%=seq%>&cpage=<%=cpage %>'><img src='../images/btn_mod.gif' border='0'></a> 
                <a href='board_delete1.jsp?seq=<%=seq%>&cpage=<%=cpage %>'><img src='../images/btn_del.gif' border='0'></a> 
                <a href='board_reply1.jsp?seq=<%=seq%>&cpage=<%=cpage %>'><img src='../images/btn_rep.gif' border='0'></a>
            </td>
            <td align='right'>
                <a href='board_list1.jsp?cpage=<%=cpage %>'><img src='../images/btn_list.gif' border='0'></a>
            </td>
        </tr>
        <tr>
            <td colspan='2' class='gline'></td>
        </tr>
        </table>
    </td>
</tr>
</table>        
        
<table width='750px' border='0' cellpadding='0' cellspacing='0' align='center'>
<tr>
    <td height='15' bgcolor='#f0f0f0' style='padding:5' align='center'></td>
</tr>
</table>

</body>
</html>


6.
글삭제

  • 실제 테이블 - 글삭제(x)
  • 제목 - 사용자에 의해 삭제 - 수정
  • 글 목록 - 제목에서 링크 제거

board_delete_ok
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import = "java.sql.Connection" %>
<%@ page import = "java.sql.PreparedStatement" %>
<%@ page import = "java.sql.SQLException" %>

<%@ page import = "javax.naming.Context" %>
<%@ page import = "javax.naming.InitialContext" %>
<%@ page import = "javax.naming.NamingException" %>
<%@ page import = "javax.sql.DataSource" %>
<%-- 숨김페이지라서 HTML 코드 없음 --%>
<%
    request.setCharacterEncoding("utf-8");
    //클라이언트 정보 받기
    String seq =request.getParameter("seq");
    String password =request.getParameter("password");
    
    //데이터베이스 연결
    Connection conn = null;
    PreparedStatement pstmt = null;
    int flag = 2; 
    
    try{
        Context initCtx = new InitialContext();
        Context envCtx = (Context)initCtx.lookup("java:comp/env");
        DataSource dataSource = (DataSource)envCtx.lookup("jdbc/oracle");
        
        conn = dataSource.getConnection();
        //데이터 삭제가 아니라 ip 수정
        String sql = "update reply1 set wip ='000000000000000' where seq=? and password=?";
        pstmt = conn.prepareStatement(sql);
        pstmt.setString(1, seq);
        pstmt.setString(2, password);
        
        //executeUpdate 리턴 값: 영향 받은 행수
        int result = pstmt.executeUpdate();
        if(result ==0){
            flag =1;
        }else if(result ==1){
            flag =0;
        }
        
    }catch(NamingException e){
        System.out.println("에러 : " + e.getMessage());
    }catch(SQLException e){
        System.out.println("에러 : " + e.getMessage());
    }finally{
        if(pstmt !=null)pstmt.close();
        if(conn !=null)conn.close();
    }
    
    //성공시 리스트페이지 , 실패시 이전페이지로 이동 자바스크립트
    out.println("<script type='text/javascript'>");
    if(flag ==0){
        out.println("alert('글삭제에 성공했습니다')");
        out.println("location.href='board_list1.jsp';");
    }else if(flag==1){
        out.println("alert('비밀번호가 잘못되었습니다.')");
        out.println("history.back();");
    }else{
        out.println("alert('글삭제에 실패했습니다')");
        out.println("history.back();");
    }
    out.println("</script>");
    
%>

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import = "java.sql.Connection" %>
<%@ page import = "java.sql.PreparedStatement" %>
<%@ page import = "java.sql.ResultSet" %>
<%@ page import = "java.sql.SQLException" %>

<%@ page import = "javax.naming.Context" %>
<%@ page import = "javax.naming.InitialContext" %>
<%@ page import = "javax.naming.NamingException" %>
<%@ page import = "javax.sql.DataSource" %>
<%
    request.setCharacterEncoding("utf-8");

    int cpage = 1;
    if(request.getParameter("cpage")!=null && !request.getParameter("cpage").equals("")){
        cpage = Integer.parseInt(request.getParameter("cpage"));
    }
    //페이지당 출력 데이터 갯수
    int recordPerPage =10;
    //전체 데이터 갯수
    int totalRecord = 0;
    //전체 페이지 갯수
    int totalPage = 1;
    //페이지당 블럭 갯수
    int blockPerPage = 5;
    
    Connection conn = null;
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    StringBuffer result = new StringBuffer();
    
    try{
        Context initCtx = new InitialContext();
        Context envCtx = (Context)initCtx.lookup("java:comp/env");
        DataSource dataSource = (DataSource)envCtx.lookup("jdbc/oracle");
        
        conn = dataSource.getConnection();
        
        String sql = "select seq, grpl, subject, writer, to_char(wdate,'YY.MM.DD') wdate, hit, trunc(sysdate-wdate) wgap, wip from reply1 order by grp desc, grps asc";
        //Resultset 옵션주기
        pstmt = conn.prepareStatement(sql, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        
        rs= pstmt.executeQuery();
        
        //전체데이터 갯수
        rs.last(); //마지막 데이터를 읽음
        totalRecord = rs.getRow(); //마지막 데이터 행번호를 가져옴
        rs.beforeFirst(); //데이터를 다시 처음으로 올림
        
        //전체 페이지 갯수
        totalPage = ((totalRecord-1)/recordPerPage) +1;
        
        //페이지를 넘길떄 처음 읽을 데이터의 행   0,10,20,30,40,...
        int skip=(cpage-1)*recordPerPage;
        //ResultSet에 읽고싶은 위치를 지정
        if(skip!=0)rs.absolute(skip);
        
        //recordPerPage만큼 짤려서 화면에 출력
        for(int i=0; i<recordPerPage && rs.next();i++){
            String seq = rs.getString("seq");
            
            //들여쓰기
            int grpl = rs.getInt("grpl");
            String sgrpl = "";
            for(int j = 1; j<=grpl; j++){
                sgrpl += "&nbsp;&nbsp;";
            }
            
            String subject = rs.getString("subject");
            String writer = rs.getString("writer");
            String wdate = rs.getString("wdate");
            String hit = rs.getString("hit");
            String wip = rs.getString("wip");
            int wgap = rs.getInt("wgap");
            
            result.append("<table width='100%' border='0' cellpadding='0' cellspacing='0'>");
            result.append("<tr>");
            result.append("    <td height='1'></td>");
            result.append("</tr>");
            result.append("<tr>");
            result.append("    <td>");
            result.append("        <table width='100%' border='0' cellpadding='0' cellspacing='0'>");
            result.append("            <tr height='25' onMouseOver=\"this.className='evencell'\" onMouseOut=\"this.className=''\">");
            result.append("                <td width='40' align='center'>"+seq+"</td>");
            result.append("                <td>");
            result.append("                    <span style='width:370' class='elltxt'>");
            
            //답글 들여쓰기 입력
            if(grpl !=0){
                result.append(sgrpl +"<img src='../images/ico_re.gif' width='9'>");
            }
            //삭제된 게시글
            if(wip.equals("000000000000000")){
                result.append("                        <span>"+"사용자에의해 삭제되었습니다"+"</span>");
            }else{
                result.append("                        <a href='board_view1.jsp?seq="+seq+"&cpage="+cpage+"'>"+subject+"</a>");
            }
            
            //new이미지 24시간
            if(wgap == 0) {
                result.append("                <img src='../images/ico_n.gif' width='8' height='8' border='0' hspace='3'>");
            }
            
            result.append("                    </span>");
            result.append("                </td>");
            result.append("                <td width='100' align='center'>"+writer+"</td>");
            result.append("                <td width='80' align='center'>"+wdate+"</td>");
            result.append("                <td width='50' align='center'>"+hit+"</td>");
            result.append("            </tr>");
            result.append("        </table>");
            result.append("    </td>");
            result.append("</tr>");
            result.append("<tr>");
            result.append("    <td height='1'></td>");
            result.append("</tr>");
            result.append("<tr>");
            result.append("    <td align='center' class='imgline'></td>");
            result.append("</tr>");
            result.append("</table>");            
        }
        
    }catch(NamingException e){
        System.out.println("에러 : " + e.getMessage());
    }catch(SQLException e){
        System.out.println("에러 : " + e.getMessage());
    }finally{
        if(rs!=null) rs.close();
        if(pstmt!=null) pstmt.close();
        if(conn!=null) conn.close();
    }

%>
<html>
<head>
<title></title>
<meta http-equiv='Content-Type' content='text/html;charset=utf-8'>
<link rel='stylesheet' type='text/css' href='../images/common.css'>
</head>

<body bgcolor='#ffffff' topmargin='5' rightmargin='0' leftmargin='5' bottommargin='10'>

<table width='750px' border='0' cellpadding='0' cellspacing='0' align='center'>
<tr>
    <td height='23' bgcolor='#f0f0f0' align='right'></td>
</tr>
<tr>
    <td bgcolor='#ffffff' style='padding:20'>
        <table width='100%' border='0' cellpadding='0' cellspacing='0'>
        <tr>
            <td align='center' class='gline'></td>
        </tr>
        <tr>
            <td align='center'>
                <table width='100%' border='0' cellpadding='0' cellspacing='0' class='titlecell'>
                <tr height='25' align='center'>
                    <td width='40'>No</td>
                    <td>제목</td>
                    <td width='100'>이름</td>
                    <td width='80'>등록일</td>
                    <td width='50'>조회수</td>
                </tr>
                </table>
            </td>
        </tr>
        <tr>
            <td align='center' class='gline'></td>
        </tr>
        <tr>
            <td height='3'></td>
        </tr>
        </table>
        
<!-- 리스트 시작 -->
<%= result %>
<!-- 리스트 끝 -->

        <table width='100%' border='0' cellpadding='0' cellspacing='0'>
        <tr>
            <td width='500' height='30'>
<!-- 페이지 네비게이션 시작 -->
<%
    //화면 하단에 보이는 페이지 리스트 갯수
    int startBlock = ((cpage-1)/blockPerPage)*blockPerPage+1;
    int endBlock =startBlock+blockPerPage-1;
    if(endBlock >=totalPage){
        endBlock = totalPage;
    }
%>
<%
    //블럭 옮기기
    if(startBlock==1){
        out.println("<img src='../images/moveset/p_left_arrow_01_off.gif' align='absmiddle' hspace='2' border='0'>");
    }else{
        out.println("<a href='board_list1.jsp?cpage="+(startBlock-blockPerPage)+"'><img src='../images/moveset/p_left_arrow_01.gif' align='absmiddle' hspace='2' border='0'></a>");
    }
%>
                
    <%
        //페이지 옮기기 //page가 1일때는 이전페이지로 못감, 화살표 색깔off로 바뀜
        if(cpage==1){
            out.println("<img src='../images/moveset/p_left_arrow_02_off.gif' align='absmiddle' hspace='8' border='0'>");
        }else{
            out.println("<a href='board_list1.jsp?cpage="+(cpage-1)+"'><img src='../images/moveset/p_left_arrow_02.gif' align='absmiddle' hspace='8' border='0'></a>");
        }
    %>
                

                <img src='../images/moveset/p_orange.gif' align='absmiddle' hspace='3' border='0'>
        <%
            for(int i=startBlock;i<=endBlock; i++){
                if(cpage==i){
                    out.println("<b><u>["+i+"]</u></b>&nbsp;");
                }else{
                    out.println("<a href='board_list1.jsp?cpage="+i+"'>"+i+"</a>&nbsp;");
                }
                
            }
        %>
                <img src='../images/moveset/p_orange.gif' align='absmiddle' hspace='3' border='0'>
    <%
        //페이지 옮기기 //page가 끝페이지일때  다음 페이지로 못감, 화살표 색깔off로 바뀜
        if(cpage==totalPage){
            out.println("<img src='../images/moveset/p_right_arrow_02_off.gif' align='absmiddle' hspace='8' border='0'>");
        }else{
            out.println("<a href='board_list1.jsp?cpage="+(cpage+1)+"'><img src='../images/moveset/p_right_arrow_02.gif' align='absmiddle' hspace='2' border='0'></a>");
        }
    %>
<%
    //블럭 옮기기
    if(endBlock==totalPage){
        out.println("<img src='../images/moveset/p_right_arrow_01_off.gif' align='absmiddle' hspace='2' border='0'>");
    }else{
        out.println("<a href='board_list1.jsp?cpage="+(startBlock+blockPerPage)+"'><img src='../images/moveset/p_right_arrow_01.gif' align='absmiddle' hspace='2' border='0'></a>");
    }
%>
<!-- 페이지 네비게이션 끝 -->    
            </td>        
            <td align='right'>
                <a href='board_write1.jsp?cpage=<%=cpage%>'><img src='../images/btn_wri.gif' border='0'></a>
            </td>
        </tr>
        </table>
    </td>
</tr>
</table>        
        
<table width='750px' border='0' cellpadding='0' cellspacing='0' align='center'>
<tr>
    <td height='15' bgcolor='#f0f0f0' style='padding:5' align='center'></td>
</tr>
</table>

</body>
</html>


7. 파일 업로드
cos.jar(meltipartparser)라이브러리 다운 http://www.servlets.com/



업로드파일을 넣어둘 폴더를 생성

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta name="viewport" content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0">
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

<!-- upload는 반드시 post타입으로 : 데이터가 크기때문에 get방식 안됨 -->
<form action="upload_ok01.jsp" method="post" enctype="multipart/form-data">
    파일: <input type="file" name="upload" size="20">
    <input type="submit" value='파일 전송'>
</form>

</body>
</html>


<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="com.oreilly.servlet.multipart.DefaultFileRenamePolicy" %>
<%@ page import="com.oreilly.servlet.MultipartRequest" %>
<%
    //업로드 경로 //제한용량 //인코딩 정해야함
    String uploadPath ="C:\\Users\\user\\Documents\\UploadEx01\\WebContent\\upload";  //역슬레쉬 escaping
    int maxFileSize = 1024*1024*1; //1MB
    String encoding ="utf-8";

    //DefaultFileRenamePolicy : 중복 파일명이 있으면 이름뒤에 숫자를 증가함
    MultipartRequest multi = new MultipartRequest(request, uploadPath, maxFileSize, encoding, new DefaultFileRenamePolicy());
    out.println("파일 업로드 완료");
%>

설정한 1MB이상의 파일을 올릴 경우

8. 업로드파일 속성을 출력
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="com.oreilly.servlet.multipart.DefaultFileRenamePolicy" %>
<%@ page import="com.oreilly.servlet.MultipartRequest" %>
<%@ page import="java.io.File" %>

<%
    //업로드 경로 //제한용량 //인코딩 정해야함
    String uploadPath ="C:\\Users\\user\\Documents\\UploadEx01\\WebContent\\upload";  //역슬레쉬 escaping
    int maxFileSize = 1024*1024*20; //20MB
    String encoding ="utf-8";
    
    //DefaultFileRenamePolicy : 중복 파일명이 있으면 이름뒤에 숫자를 증가함
    MultipartRequest multi = new MultipartRequest(request, uploadPath, maxFileSize, encoding, new DefaultFileRenamePolicy());
    
    out.println("파일 업로드 완료 <br>");
    out.println(multi.getFilesystemName("upload")+"<br>");    //업로드 시킨 파일 이름
    out.println(multi.getOriginalFileName("upload")+"<br>");  //원래 파일 이름
    
    //file을 자바객체로 만듦  //파일 속성들을 표시할 수 있음
    File file = multi.getFile("upload");
    out.println(file.length() +"<br>");
%>


9
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="com.oreilly.servlet.multipart.DefaultFileRenamePolicy" %>
<%@ page import="com.oreilly.servlet.MultipartRequest" %>
<%@ page import="java.io.File" %>

<%
    //업로드 경로 //제한용량 //인코딩 정해야함
    String uploadPath ="C:\\Users\\user\\Documents\\UploadEx01\\WebContent\\upload";  //역슬레쉬 escaping
    int maxFileSize = 1024*1024*20; //20MB
    String encoding ="utf-8";
    
    //DefaultFileRenamePolicy : 중복 파일명이 있으면 이름뒤에 숫자를 증가함
    MultipartRequest multi = new MultipartRequest(request, uploadPath, maxFileSize, encoding, new DefaultFileRenamePolicy());
    
    out.println("파일 업로드 완료 <br>");
    out.println(multi.getFilesystemName("upload")+"<br>");    //업로드 시킨 파일 이름
    out.println(multi.getOriginalFileName("upload")+"<br>");  //원래 파일 이름
    
    //file을 자바객체로 만듦  //파일 속성들을 표시할 수 있음
    File file = multi.getFile("upload");
    out.println(file.length() +"<br>");
%>
MIME type : 브라우저가 해석할 수있는 자료의 형태
          : txt, 이미지 파일은 해석해서 보여줌
다운로드 : <a href='./upload/<%=multi.getFilesystemName("upload")%>'>다운로드</a>

이미지는 브라우저가 해석가능한 파일이라서 브라우저에 보여줌

10
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta name="viewport" content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0">
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

<!-- upload는 반드시 post타입으로 : 데이터가 크기때문에 get방식 안됨 -->
<form action="upload_ok01.jsp" method="post" enctype="multipart/form-data">
    파일: <input type="file" name="upload" size="20">
    <input type="submit" value='파일 전송'>
</form>

</body>
</html>

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="com.oreilly.servlet.multipart.DefaultFileRenamePolicy" %>
<%@ page import="com.oreilly.servlet.MultipartRequest" %>
<%@ page import="java.io.File" %>

<%
    //업로드 경로 //제한용량 //인코딩 정해야함
    String uploadPath ="C:\\Users\\user\\Documents\\UploadEx01\\WebContent\\upload";  //역슬레쉬 escaping
    int maxFileSize = 1024*1024*20; //20MB
    String encoding ="utf-8";
    
    //DefaultFileRenamePolicy : 중복 파일명이 있으면 이름뒤에 숫자를 증가함
    MultipartRequest multi = new MultipartRequest(request, uploadPath, maxFileSize, encoding, new DefaultFileRenamePolicy());
    
    out.println("파일 업로드 완료 <br>");
    out.println(multi.getFilesystemName("upload")+"<br>");    //업로드 시킨 파일 이름
    out.println(multi.getOriginalFileName("upload")+"<br>");  //원래 파일 이름
    
    //file을 자바객체로 만듦  //파일 속성들을 표시할 수 있음
    File file = multi.getFile("upload");
    out.println(file.length() +"<br>");
%>
MIME type : 브라우저가 해석할 수있는 자료의 형태<br>
          : txt, 이미지 파일은 해석해서 보여줌<br>
다운로드 : <a href='./upload/<%=multi.getFilesystemName("upload")%>'>다운로드</a><br>
<!-- download.jsp에서 다운로드 처리 -->
다운로드.jsp에서 처리 : <a href='./download.jsp?filename=<%=multi.getFilesystemName("upload")%>'>다운로드</a>

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" trimDirectiveWhitespaces="true" %>
<%@page import="java.io.FileInputStream"%>
<%@ page import="java.io.File" %>
<%@ page import="java.io.InputStream" %>
<%@ page import="java.net.URLEncoder" %>
<%@ page import="com.oreilly.servlet.ServletUtils" %>

<%
    String fileName = request.getParameter("filename");
    String sFilePath ="C:\\Users\\user\\Documents\\UploadEx01\\WebContent\\upload\\" + fileName;
    
    byte b[] = new byte[4096];
    File oFile = new File(sFilePath);
    
    out.clearBuffer();
    response.setContentType("application/octet-stream"); //8byte 스트림방식으로 전송
    response.setHeader("Content-Disposition", "attachment;filename=" +URLEncoder.encode(fileName, "utf-8"));
    FileInputStream in = new FileInputStream(sFilePath);
    ServletOutputStream sout = response.getOutputStream();
    int numRead;
    while((numRead=in.read(b,0,b.length))!=-1){
        sout.write(b, 0, numRead);
    }
    sout.flush();
    sout.close();
    in.close();
    
%>



댓글 없음:

댓글 쓰기