본문 바로가기

Learning/JSP

게시판 1

  • writeForm.jsp: 게시판에 글 등록하는 폼

 

 

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

    pageEncoding="UTF-8"%>

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>Insert title here</title>

</head>

<body>

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

<table border=1>

    <tr>

        <td>이름</td>

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

    </tr>

    <tr>

        <td>제목</td>

        <td><input type="text" name="subject"></td>

    </tr>

    <tr>

        <td>이메일</td>

        <td><input type="text" name="email"></td>

    </tr>

    <tr>

        <td>내용</td>

        <td><textarea cols="50" rows="20" name="content"></textarea></td>

    </tr>

    <tr>

        <td>비밀번호</td>

        <td><input type="password" name="passwd"></td>

    </tr>

    <tr>

        <td colspan="2" align="center">

        <input type="submit" value="글쓰기">

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

        <input type="button" value="목록보기">

        </td>

    </tr>

</table>

</form>

</body>

</html>

 


  • BoardVO.java: 게터 세터 자바빈즈

 

package com.board;

public class BoardVO {

    private int num;

    private String writer;

    private String subject;

    private String email;

    private String content;

    private String ip;

    private int readcount;

    private int ref;

    private int re_step;

    private int re_level;

    private String passwd;

    private String reg_date;

    public int getNum() {

        return num;

    }

    public void setNum(int num) {

        this.num = num;

    }

    public String getWriter() {

        return writer;

    }

    public void setWriter(String writer) {

        this.writer = writer;

    }

    public String getSubject() {

        return subject;

    }

    public void setSubject(String subject) {

        this.subject = subject;

    }

    public String getEmail() {

        return email;

    }

    public void setEmail(String email) {

        this.email = email;

    }

    public String getContent() {

        return content;

    }

    public void setContent(String content) {

        this.content = content;

    }

    public String getIp() {

        return ip;

    }

    public void setIp(String ip) {

        this.ip = ip;

    }

    public int getRef() {

        return ref;

    }

    public void setRef(int ref) {

        this.ref = ref;

    }

    public int getRe_step() {

        return re_step;

    }

    public void setRe_step(int re_step) {

        this.re_step = re_step;

    }

    public int getRe_level() {

        return re_level;

    }

    public void setRe_level(int re_level) {

        this.re_level = re_level;

    }

    public String getPasswd() {

        return passwd;

    }

    public void setPasswd(String passwd) {

        this.passwd = passwd;

    }

    public String getReg_date() {

        return reg_date;

    }

    public void setReg_date(String reg_date) {

        this.reg_date = reg_date;

    }

    public int getReadcount() {

        return readcount;

    }

    public void setReadcount(int readcount) {

        this.readcount = readcount;

    }

}

  • BoardDAO.java: CRUD 메소드

 

package com.board;

import java.sql.Connection;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Statement;

import java.util.ArrayList;

import javax.naming.Context;

import javax.naming.InitialContext;

import javax.sql.DataSource;

public class BoardDAO {

    

    //디비셋팅

    private static BoardDAO instance=new BoardDAO();

    

    public static BoardDAO getInstance() {

        return instance;

    }

    

    private Connection getConnection() throws Exception{

        Context initCtx=new InitialContext();

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

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

        return ds.getConnection();

    }

    

    //추가

    public void boardInsert(BoardVO board) {

        Connection con=null;

        PreparedStatement ps=null;

        

        try {

            con=getConnection();

            //writer, email, content, passwd, num, subject

            String sql="INSERT INTO BOARD(num,writer,subject,email,content,passwd,ip)"

                    + "VALUES (board_seq.nextval,?,?,?,?,?,?)";

            ps=con.prepareStatement(sql);

            ps.setString(1, board.getWriter());

            ps.setString(2, board.getSubject());

            ps.setString(3, board.getEmail());

            ps.setString(4, board.getContent());

            ps.setString(5, board.getPasswd());

            ps.setString(6, board.getIp());

            ps.executeUpdate();

        } catch (Exception e) {

            e.printStackTrace();

        } finally {

            closeConnection(con,ps);

        }

    }

    

    //전체보기

    public ArrayList<BoardVO> boardList(){

        Connection con=null;

        Statement st=null;

        ResultSet rs=null;

        ArrayList<BoardVO> arr=new ArrayList<BoardVO>();

        try {

            con=getConnection();

            String sql="select * from board";

            st=con.createStatement();

            rs=st.executeQuery(sql);

            while(rs.next()) {

                BoardVO board=new BoardVO();

                board.setNum(rs.getInt("num"));

                board.setEmail(rs.getString("email"));

                board.setIp(rs.getString("ip"));

                board.setReadcount(rs.getInt("readcount"));

                board.setSubject(rs.getString("subject"));

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

                board.setReg_date(rs.getString("reg_date"));

                arr.add(board);

            }

        } catch (Exception e) {

            e.printStackTrace();

        } finally {

            closeConnection(con, st, rs);

        }

        return arr;

    }

    

    //검색 전체보기

    public ArrayList<BoardVO> boardList(String field, String word){

        Connection con=null;

        Statement st=null;

        ResultSet rs=null;

        ArrayList<BoardVO> arr=new ArrayList<BoardVO>();

        try {

            con=getConnection();

            String sql="select * from board where "+field+" like '%"+word+"%'";

            st=con.createStatement();

            rs=st.executeQuery(sql);

            while(rs.next()) {

                BoardVO board=new BoardVO();

                board.setNum(rs.getInt("num"));

                board.setEmail(rs.getString("email"));

                board.setIp(rs.getString("ip"));

                board.setReadcount(rs.getInt("readcount"));

                board.setSubject(rs.getString("subject"));

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

                board.setReg_date(rs.getString("reg_date"));

                arr.add(board);

            }

        } catch (Exception e) {

            e.printStackTrace();

        } finally {

            closeConnection(con, st, rs);

        }

        return arr;

    }

    

    //상세보기

    public BoardVO boardView(int num) {

        Connection con=null;

        Statement st=null;

        ResultSet rs=null;

        BoardVO board=null;

        

        try {

            con=getConnection();

            String sql="select * from board where num="+num;

            st=con.createStatement();

            rs=st.executeQuery(sql);

            if(rs.next()) {

                board=new BoardVO();

                board.setNum(rs.getInt("num"));

                board.setContent(rs.getString("content"));

                board.setEmail(rs.getString("email"));

                board.setSubject(rs.getString("subject"));

                board.setIp(rs.getString("ip"));

                board.setPasswd(rs.getString("passwd"));

                board.setRe_level(rs.getInt("re_level"));

                board.setRe_step(rs.getInt("re_step"));

                board.setRef(rs.getInt("ref"));

                board.setReg_date(rs.getString("reg_date"));

                board.setReadcount(rs.getInt("readcount"));

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

            }

        }catch (Exception e) {

            e.printStackTrace();

        }finally {

            closeConnection(con, st, rs);

        }

        return board;

    }

    

    //수정

    public int boardUpdate(BoardVO board) {

        Connection con=null;

        PreparedStatement ps=null;

        ResultSet rs=null;

        

        int flag=0;

        String sql="";

        try {

            con=getConnection();

            sql="select passwd from board where num="+board.getNum();

            ps=con.prepareStatement(sql); //passwd 검색

            rs=ps.executeQuery();

            if(rs.next()) {

                if(rs.getString("passwd").equals(board.getPasswd())) { //비번 일치

                    sql="UPDATE BOARD SET subject=?, email=?, content=?, reg_date=sysdate where num=?";

                    ps=con.prepareStatement(sql);

                    ps.setString(1, board.getSubject());

                    ps.setString(2, board.getEmail());

                    ps.setString(3, board.getContent());

                    ps.setInt(4, board.getNum());

                    flag=ps.executeUpdate(); //업데이트 된 수를 flag에 담는다.

                }

            }

        }catch (Exception e) {

            e.printStackTrace();

        }finally {

            closeConnection(con, ps);

        }

        return flag;

    }

    

    //삭제

    public int boardDelete(int num) {

        int flag=0;

        Connection con=null;

        Statement st=null;

        try {

            con=getConnection();

            String sql="DELETE FROM board WHERE num="+num;

            st=con.createStatement();

            flag=st.executeUpdate(sql);

        } catch (Exception e) {

            e.printStackTrace();

        } finally {

            closeConnection(con, st, null);

        }

        return flag;

    }

    

    //검색

    

    //개수

    public int boardCount() {

        Connection con=null;

        Statement st=null;

        ResultSet rs=null;

        int count=0;

        try {

            con=getConnection();

            st=con.createStatement();

            String sql="select count(*) from board";

            rs=st.executeQuery(sql);

            if(rs.next()) {

                count=rs.getInt(1);

            }

        } catch (Exception e) {

            e.printStackTrace();

        } finally {

            closeConnection(con, st, rs);

        }

        return count;

    }

    

    //검색 개수

        public int boardCount(String field, String word) {

            Connection con=null;

            Statement st=null;

            ResultSet rs=null;

            int count=0;

            try {

                con=getConnection();

                st=con.createStatement();

                String sql="select count(*) from board where "+field+" like '%"+word+"%'";

                rs=st.executeQuery(sql);

                if(rs.next()) {

                    count=rs.getInt(1);

                }

            } catch (Exception e) {

                e.printStackTrace();

            } finally {

                closeConnection(con, st, rs);

            }

            return count;

        }

    

    //닫기 closeConnection

        private void closeConnection(Connection con, PreparedStatement ps) {

            try {

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

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

            } catch (SQLException e) {

                e.printStackTrace();

            }

        }

        private void closeConnection(Connection con, Statement st, ResultSet rs) {

            try {

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

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

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

            } catch (SQLException e) {

                e.printStackTrace();

            }

        }

}


  • writePro.jsp: useBean 사용하여 writeForm에서 보낸 값들이 DB에 입력되도록 하는 로직

 

<%@page import="com.board.BoardDAO"%>

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

    pageEncoding="UTF-8"%>

<%

    request.setCharacterEncoding("utf-8");

%>

<jsp:useBean id="board" class="com.board.BoardVO"/>

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

<%

    BoardDAO dao=BoardDAO.getInstance();

    String ip=request.getRemoteAddr();

    board.setIp(ip);

    dao.boardInsert(board);

    response.sendRedirect("list.jsp");

%>


  • list.jsp: 작성한 글 목록 폼. 제목을 클릭하면 글 내용을 볼 수 있도록 상세보기 폼으로 넘어감

 

 

<%@page import="com.board.BoardVO"%>

<%@page import="com.board.BoardDAO"%>

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

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

    pageEncoding="UTF-8"%>

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>Insert title here</title>

<link rel="stylesheet"

href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">

<style>

div.divCss{

    text-align: right;

    background-color:  darkgray;

    padding-right: 20px;

}

a:hover { text-decoration: none;  }

a:link {text-decoration: none;  }

a:visited {text-decoration: none; }

</style>

</head>

<%

    BoardDAO dao=BoardDAO.getInstance();

    String field="", word="";

    ArrayList<BoardVO> arr=null;

    int count=0;

    if(request.getParameter("word")!=null){

        field=request.getParameter("field");

        word=request.getParameter("word");

        arr=dao.boardList(field,word);

        count=dao.boardCount(field,word);

    }else{

        arr=dao.boardList();

        count=dao.boardCount();

    }

%>

<body>

<div align="right">

    <a href=""></a>님 반갑습니다.

    <a href="">로그아웃</a>

    <br>전체 게시글 수: <span id="cntSpan"><%=count %></span><br>

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

</div>

    <table class="table table-striped">

    <thead>

        <tr>

            <th scope="col">번호</th>

            <th>제목</th>

            <th>작성자</th>

            <th>작성일</th>

            <th>조회수</th>

            <th>IP주소</th>

        </tr>

    </thead>

    <tbody>

<%

    for(BoardVO vo: arr){

%>

        <tr>

            <th scope="row"><%=vo.getNum()%></th>       

            <td><a href="boardView.jsp?num=<%=vo.getNum()%>"><%=vo.getSubject() %></a></td>        

            <td><%=vo.getWriter() %></td>       

            <td><%=vo.getReg_date()%></td>      

            <td><%=vo.getReadcount() %></td>    

            <td><%=vo.getIp() %></td>   

        </tr>       

<%

    }

%>  

    </tbody>

    </table>

<br><br>

<form action="list.jsp" name="search" method="get">

    <table align=center>

        <tr>

            <td>

            <select name="field" size=1>

                <option value="subject">제목

                <option value="writer">작성자

            </select>

            <input type="text" size=16 name="word">

            <input type="submit" value="찾기">

            </td>

        </tr>

    </table>

</form>

</body>

</html>


  • boardView.jsp: 상세보기 폼. 글수정, 글삭제, 답글쓰기, 글목록 버튼클릭.

 

 

<%@page import="com.board.BoardVO"%>

<%@page import="com.board.BoardDAO"%>

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

    pageEncoding="UTF-8"%>

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>Insert title here</title>

<%

    request.setCharacterEncoding("utf-8");

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

    BoardDAO dao=BoardDAO.getInstance();

    BoardVO board=dao.boardView(num);

%>

</head>

<script>

function del(){

    if(confirm("정말 삭제할까요?")){

        location.href="deletePro.jsp?num=<%=num%>";

    }

}

</script>

<body>

<h2>글 내용 보기</h2>

<table border=1 width=500>

    <tr>

        <td>글번호</td>

        <td><%=board.getNum() %></td>

        <td>조회수</td>

        <td><%=board.getReadcount() %></td>

    </tr>

    <tr>

        <td>작성자</td>

        <td><%=board.getWriter() %></td>

        <td>작성일</td>

        <td><%=board.getReg_date() %></td>

    </tr>

    <tr>

        <td>글제목</td>

        <td colspan="3"><%=board.getSubject() %></td>

    </tr>

    <tr>

        <td>글내용</td>

        <td colspan="3"><%=board.getContent() %></td>

    </tr>

    <tr>

        <td colspan="4">

        <input type="button" value="글수정" onclick="location.href='updateForm.jsp?num=<%=num%>'">

        <input type="button" value="글삭제" onclick="del()">

        <input type="button" value="답글쓰기" onclick="">

        <input type="button" value="글목록" onclick="location.href='list.jsp'">

        </td>

    </tr>

</table>

</body>

</html>


  • updateForm.jsp: 글 수정하기 폼.

 

 

<%@page import="com.board.BoardVO"%>

<%@page import="com.board.BoardDAO"%>

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

    pageEncoding="UTF-8"%>

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>Insert title here</title>

<%

    request.setCharacterEncoding("utf-8");

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

    BoardDAO dao=BoardDAO.getInstance();

    BoardVO board=dao.boardView(num);

%>

</head>

<body>

<h1>글 수정하기</h1>

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

<input type="hidden" name="num" value="<%=num%>">

<table border=1>

    <tr>

        <td>이름</td>

        <td><%=board.getWriter()%></td>

    </tr>

    <tr>

        <td>제목</td>

        <td><input type="text" name="subject" value="<%=board.getSubject()%>"></td>

    </tr>

    <tr>

        <td>이메일</td>

        <td><input type="text" name="email" value="<%=board.getEmail()%>"></td>

    </tr>

    <tr>

        <td>내용</td>

        <td><textarea cols="50" rows="20" name="content"><%=board.getContent()%></textarea></td>

    </tr>

    <tr>

        <td>비밀번호</td>

        <td><input type="password" name="passwd"></td>

    </tr>

    <tr>

        <td colspan="2" align="center">

        <input type="submit" value="수정">

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

        <input type="button" value="목록보기" onclick="location.href='list.jsp'">

        </td>

    </tr>

</table>

</form>

</body>

</html>

 


  • updatePro.jsp: 글 수정 로직

 

<%@page import="com.board.BoardDAO"%>

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

    pageEncoding="UTF-8"%>

<%

    request.setCharacterEncoding("utf-8");

%>

<jsp:useBean id="board" class="com.board.BoardVO"/>

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

<%

    BoardDAO dao=BoardDAO.getInstance();

    String ip=request.getRemoteAddr();

    board.setIp(ip);

    int flag=dao.boardUpdate(board);

    if(flag==1){ //정상처리

        response.sendRedirect("list.jsp");

    }else{ //비번오류

%>

        <script>

            alert("비밀번호가 일치하지 않습니다.");

            history.back(); //history.go(-1); 이전 페이지로 넘어감

        </script>

<%

    }

%>

 


  • deletePro.jsp: 글 삭제 로직

 

<%@page import="org.json.simple.JSONObject"%>

<%@page import="org.json.simple.JSONArray"%>

<%@page import="com.board.BoardVO"%>

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

<%@page import="com.board.BoardDAO"%>

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

    pageEncoding="UTF-8"%>

<%

    request.setCharacterEncoding("utf-8");

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

    BoardDAO dao=BoardDAO.getInstance();

    int flag=dao.boardDelete(num);

    response.sendRedirect("list.jsp");

%>

 

 

 

 

 

 

'Learning > JSP' 카테고리의 다른 글

서블릿  (0) 2020.07.27
게시판 2  (0) 2020.07.23
회원가입2  (0) 2020.07.22
회원가입  (0) 2020.07.20
주소록 생성하기2  (0) 2020.07.16