Jam's story

[JSP] 게시판 - 목록, 글쓰기 기능 , 페이징 처리 본문

JSP

[JSP] 게시판 - 목록, 글쓰기 기능 , 페이징 처리

애플쩀 2022. 6. 20. 16:59

게시판 만드는 순서 

1. sqldeveloper 실행 +  scott 계정으로 접속.   

2. TBL_CSTVSBOARD  테이블 생성     
 SEQ_TBL_CSTVSBOARD 시퀀스 확인 SEQ_TBL_CSTVSBOARD 시퀀스

3.  days05 폴더 안에  board 폴더 생성   

4.  days05.board 패키지 생성         
ㄱ. BoardDTO          ㄴ. BoardDAO           ㄷ. BoardDAOImpl                       
                                           
5.      /jspPro/cstvsboard/list.htm  ->  서블릿 클래스   List.java 추가  ->  days05/board/list.jsp 포워딩.   

6.     /jspPro/cstvsboard/write.htm   글쓰기   링크 태그 클릭 서블릿클래스 Write.java 추가 ->   doGet(){}      -> 포워딩   write.jsp   

6-2. write.jsp            새 게시글 정보 입력 한 후          "작성완료" 버튼 클릭  ->               /jspPro/cstvsboard/write.htm  +  POST 방식    -> Write.java 서블릿 -> doPost(){   dao.새 게시글 쓰기()  DB 저장  }     
7.  페이징 처리            <<  1 2 3 4 5 6 7 8 9 10 »                         
이전버튼   시작번호   ,끝번호  , 다음버튼                               
PageBlock.java  클래스 선언                

 

 SEQ_TBL_CSTVSBOARD 시퀀스만드는 쿼리 

 

  CREATE TABLE "SCOTT"."TBL_CSTVSBOARD" 
   (   "SEQ" NUMBER NOT NULL ENABLE, 
   "WRITER" VARCHAR2(20 BYTE) NOT NULL ENABLE, 
   "PWD" VARCHAR2(20 BYTE) NOT NULL ENABLE, 
   "EMAIL" VARCHAR2(100 BYTE), 
   "TITLE" VARCHAR2(200 BYTE) NOT NULL ENABLE, 
   "WRITEDATE" DATE DEFAULT SYSDATE, 
   "READED" NUMBER DEFAULT 0, 
   "TAG" NUMBER(1,0) DEFAULT 0, 
   "CONTENT" CLOB, 
    PRIMARY KEY ("SEQ")
  USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS 
  STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
  PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
  TABLESPACE "USERS"  ENABLE
   ) SEGMENT CREATION IMMEDIATE 
  PCTFREE 10 PCTUSED 40 INITRANS 1 MAXTRANS 255 NOCOMPRESS LOGGING
  STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
  PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
  TABLESPACE "USERS" 
 LOB ("CONTENT") STORE AS BASICFILE (
  TABLESPACE "USERS" ENABLE STORAGE IN ROW CHUNK 8192 RETENTION 
  NOCACHE LOGGING 
  STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
  PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)) ;

 

포워드와 리다이렉트의 차이점

포워드 :
client가 웹브라우저에서 요청시 Forward는 client에게 보여지지 않는 페이지에서 작업을 하게 된다. 그러므로 client는 페이지의 이동을 모르게 되며, URL또한 변경이 되지 않는다.
Client가 요청을 하게 될 때 생성되는 객체는 계속 사용이 가능하며 다른 페이지 에서도 그 객체를 사용할 수 있다.

리다이렉트 :
client가 웹브라우저에서  요청시 Redirect는 client에게 페이지의 이동을 모두 노출시킨다. client가 요청시 새로운 객체를 생성하며 기존의 객체는 사라지게 되며, URL이 페이지 이동시마다 변경된다이전의 전송값을 이동한 페이지에서 사용 불가능하다

 

days05.board 패키지 생성 

BoardDTO.java

package days05.board;

import java.util.Date;

public class BoardDTO {
	 private int seq;
	   private String writer;
	   private String pwd;
	   private String email;
	   private String title;
	   private Date   writedate;
	   private int readed;
	   private int tag;
	   private String content;
	
	   public BoardDTO() {
		super();
		// TODO Auto-generated constructor stub
	}

	public BoardDTO(int seq, String writer, String pwd, String email, String title, Date writedate, int readed, int tag,
			String content) {
		super();
		this.seq = seq;
		this.writer = writer;
		this.pwd = pwd;
		this.email = email;
		this.title = title;
		this.writedate = writedate;
		this.readed = readed;
		this.tag = tag;
		this.content = content;
	}

	public BoardDTO(int seq, String writer, String email, String title, Date writedate, int readed) {
		super();
		this.seq = seq;
		this.writer = writer; 
		this.email = email;
		this.title = title;
		this.writedate = writedate;
		this.readed = readed; 
	}	
	public int getSeq() {
		return seq;
	}

	public void setSeq(int seq) {
		this.seq = seq;
	}

	public String getWriter() {
		return writer;
	}

	public void setWriter(String writer) {
		this.writer = writer;
	}

	public String getPwd() {
		return pwd;
	}

	public void setPwd(String pwd) {
		this.pwd = pwd;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public Date getWritedate() {
		return writedate;
	}

	public void setWritedate(Date writedate) {
		this.writedate = writedate;
	}

	public int getReaded() {
		return readed;
	}

	public void setReaded(int readed) {
		this.readed = readed;
	}

	public int getTag() {
		return tag;
	}

	public void setTag(int tag) {
		this.tag = tag;
	}

	public String getContent() {
		return content;
	}

	public void setContent(String content) {
		this.content = content;
	}

	@Override
	public String toString() {
		return "BoardDTO [seq=" + seq + ", writer=" + writer + ", pwd=" + pwd + ", email=" + email + ", title=" + title
				+ ", writedate=" + writedate + ", readed=" + readed + ", tag=" + tag + ", content=" + content + "]";
	}
	   
	   
}

 

BoardDAO.java

package days05.board;

import java.sql.SQLException;
import java.util.ArrayList;

public interface BoardDAO {
	// 1. 모든 게시글 목록 반환하는 메서드 선언
	public abstract ArrayList<BoardDTO> select( ) throws SQLException;

	// 2. 새로운 게시글 추가하는 메서드 선언
		public abstract int insert( BoardDTO dto ) throws SQLException;
		
		//9.  현재페이지에 해당되는 게시글 목록 반환 하는 메소드 선언 중복선언 오버로딩 
		//한페이지에 몇개, 몇번페이지를 볼껀지 
		public abstract ArrayList<BoardDTO> select(int currentPage,int numberPerPage) throws SQLException;

		// 7. 총 레코드수 반환하는 메서드
		   int getTotalRecords() throws SQLException;
		   
		   // 8. 총 페이지수 반환하는 메서드
		   int getTotalPages( int numberPerPage ) throws SQLException;

		   // 8. 총 페이지수 반환하는 메서드(검색)
		   int getTotalPages(int numberPerPage, int searchCondition, String searchWord) throws SQLException;
}

 

BoardDAOImpl.java

package days05.board;

import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

public class BoardDAOImpl implements BoardDAO{

	// 필드
	private Connection conn = null;
	private PreparedStatement pstmt = null;
	private ResultSet rs = null;

	// 생성자
	public BoardDAOImpl() {}
	// 1. 생성자를 통해서 의존성 주입( DI )
	public BoardDAOImpl( Connection conn ){
		this.conn = conn;
	}
	// 2. setter 를 통해서 의존성 주입( DI )
	public void setConn( Connection conn ) {
		this.conn = conn;
	}

	public Connection getConn() {
		return conn;
	}

	@Override
	public ArrayList<BoardDTO> select() throws SQLException {

		ArrayList<BoardDTO>  list = null;
		BoardDTO dto = null;

		int seq;
		String writer; 
		String email;
		String title;
		Date   writedate;
		int readed; 

		String sql =   "SELECT seq,  writer, email, title, readed , writedate "
				+ "FROM tbl_cstvsboard "
				+ "ORDER BY seq DESC";

		//System.out.println(  sql );

		this.pstmt = this.conn.prepareStatement(sql);
		this.rs  = this.pstmt.executeQuery();

		if( this.rs.next() ) {
			list = new ArrayList<BoardDTO>();
			do {

				seq = this.rs.getInt("seq");
				writer = this.rs.getString("writer");
				email = this.rs.getString("email");
				title = this.rs.getString("title");
				writedate = this.rs.getDate("writedate");
				readed = this.rs.getInt("readed");

				dto = new BoardDTO(seq, writer, email, title, writedate, readed);

				list.add(dto);
			} while ( this.rs.next() );
		} // if

		this.rs.close();
		this.pstmt.close();

		return list;
		
	} // select
	
	@Override
	public int insert(BoardDTO dto) throws SQLException {
		int rowCount = 0;
		String sql = "INSERT INTO tbl_cstvsboard (seq, writer, pwd, email, title, tag, content) "
				+ "VALUES (SEQ_TBL_CSTVSBOARD.NEXTVAL, ?, ?, ? , ? , ? , ? )";

		this.pstmt = this.conn.prepareStatement(sql);

		// writer, pwd, email, title, tag, content
		//  ?, ?, ? , ? , ? , ? 파라미터 설정.
		this.pstmt.setString(1,  dto.getWriter() );
		this.pstmt.setString(2,  dto.getPwd() );
		this.pstmt.setString(3,  dto.getEmail() );
		this.pstmt.setString(4,  dto.getTitle() );
		this.pstmt.setInt(5, dto.getTag());
		this.pstmt.setString(6,  dto.getContent() );

		rowCount = this.pstmt.executeUpdate();  // 자동 커밋

		this.pstmt.close();

		return rowCount;
	} // insert
	
	
	@Override
	public ArrayList<BoardDTO> select(int currentPage, int numberPerPage) throws SQLException {
		
		ArrayList<BoardDTO>  list = null;
		BoardDTO dto = null;

		int seq;
		String writer; 
		String email;
		String title;
		Date   writedate;
		int readed; 


		int begin =  (currentPage -1)*numberPerPage +1  ;
		int end   = begin+ numberPerPage -1 ;

		String sql =    "SELECT * "
				+ "FROM (  "
				+ "    SELECT ROWNUM no, t.* "
				+ "    FROM ( "
				+ "        SELECT seq,  writer, email, title, readed , writedate   "
				+ "        FROM tbl_cstvsboard   "
				+ "        ORDER BY seq DESC "
				+ "    ) t "
				+ ") m "
				+ "WHERE m.no BETWEEN   ?  AND ? " ;

		//System.out.println(  sql );

		this.pstmt = this.conn.prepareStatement(sql);
		// "WHERE m.no BETWEEN   ?  AND ? " ;
		this.pstmt.setInt(1, begin);
		this.pstmt.setInt(2, end);

		this.rs  = this.pstmt.executeQuery();

		if( this.rs.next() ) {
			list = new ArrayList<BoardDTO>();
			do {

				seq = this.rs.getInt("seq");
				writer = this.rs.getString("writer");
				email = this.rs.getString("email");
				title = this.rs.getString("title");
				writedate = this.rs.getDate("writedate");
				readed = this.rs.getInt("readed");

				dto = new BoardDTO(seq, writer, email, title, writedate, readed);

				list.add(dto);
			} while ( this.rs.next() );
		} // if

		this.rs.close();
		this.pstmt.close();

		return list;
		
	} // select
	
	@Override
	public int getTotalRecords() throws SQLException {
		String sql = "SELECT COUNT(*) "
				+ " FROM tbl_cstvsboard";
		int totalRecords = 0;

		this.pstmt =  this.conn.prepareStatement(sql);
		this.rs =  this.pstmt.executeQuery();

		this.rs.next();
		totalRecords = rs.getInt(1);

		this.rs.close();
		this.pstmt.close();

		return totalRecords;
	}
	
	@Override
	public int getTotalPages(int numberPerPage) throws SQLException {
		String sql = "SELECT  CEIL( COUNT(*) / ? )"
				+ " FROM tbl_cstvsboard";
		int totalPages = 0;

		this.pstmt =  this.conn.prepareStatement(sql);
		this.pstmt.setInt(1, numberPerPage);
		this.rs =  this.pstmt.executeQuery();

		this.rs.next();
		totalPages = rs.getInt(1);

		this.rs.close();
		this.pstmt.close();

		return totalPages;
	}
	
	@Override
	public int getTotalPages(int numberPerPage, int searchCondition, String searchWord) throws SQLException {
		String sql = "SELECT  CEIL( COUNT(*) / ? )"
				+ " FROM tbl_cstvsboard ";
		switch ( searchCondition) {
		case 1: // 제목			
			sql += " WHERE REGEXP_LIKE(title, ? , 'i') ";
			break;
		case 2: // 내용
			sql += " WHERE REGEXP_LIKE(content, ? , 'i') ";
			break;
		case 3: // 작성자		
			sql += " WHERE REGEXP_LIKE(writer, ? , 'i') ";
			break;
		case 4: // 제목	+ 내용
			sql += " WHERE REGEXP_LIKE(title, ? , 'i') OR  REGEXP_LIKE(content, ? , 'i') ";
			break;
		}
		
		int totalPages = 0;

		this.pstmt =  this.conn.prepareStatement(sql);
		
		this.pstmt.setInt(1, numberPerPage);
		this.pstmt.setString(2, searchWord);	
		
		if( searchCondition == 4) { 
			this.pstmt.setString(3, searchWord); 
		} 
		
		this.rs =  this.pstmt.executeQuery();

		this.rs.next();
		totalPages = rs.getInt(1);

		this.rs.close();
		this.pstmt.close();

		return totalPages;
	}

} // class

 

PageBlock.java

package days05.board;

public class PageBlock {
	private int currentPage;
	   private int numberPerPage = 10;
	   private int numberOfPageBlock = 10;
	   private int startOfPageBlock = 1;  // 시작 번호
	   private int endOfPageBlock ;  // 끝 번호
	   private boolean prev, next;
	   
	   
	public int getCurrentPage() {
		return currentPage;
	}
	public void setCurrentPage(int currentPage) {
		this.currentPage = currentPage;
	}
	public int getNumberPerPage() {
		return numberPerPage;
	}
	public void setNumberPerPage(int numberPerPage) {
		this.numberPerPage = numberPerPage;
	}
	public int getNumberOfPageBlock() {
		return numberOfPageBlock;
	}
	public void setNumberOfPageBlock(int numberOfPageBlock) {
		this.numberOfPageBlock = numberOfPageBlock;
	}
	public int getStartOfPageBlock() {
		return startOfPageBlock;
	}
	public void setStartOfPageBlock(int startOfPageBlock) {
		this.startOfPageBlock = startOfPageBlock;
	}
	public int getEndOfPageBlock() {
		return endOfPageBlock;
	}
	public void setEndOfPageBlock(int endOfPageBlock) {
		this.endOfPageBlock = endOfPageBlock;
	}
	public boolean isPrev() {
		return prev;
	}
	public void setPrev(boolean prev) {
		this.prev = prev;
	}
	public boolean isNext() {
		return next;
	}
	public void setNext(boolean next) {
		this.next = next;
	}  

}

 

 

 MemberInfo.java

package days05;

import java.util.Date;

public class MemberInfo {

	private String id;
	private String passwd;
	private String name;
	private Date registerDate;
	
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getPasswd() {
		return passwd;
	}
	public void setPasswd(String passwd) {
		this.passwd = passwd;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Date getRegisterDate() {
		return registerDate;
	}
	public void setRegisterDate(Date registerDate) {
		this.registerDate = registerDate;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	private String email;
}

 

List.java - 목록과 관련된 서블릿

package days05;

import java.io.IOException;
import java.sql.Connection;
import java.util.ArrayList;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.util.DBconn;

import days05.board.BoardDAOImpl;
import days05.board.BoardDTO;
import days05.board.PageBlock;

/**
 * Servlet implementation class List
 */
@WebServlet("/cstvsboard/list.htm")
public class List extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public List() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
    //	list.htm
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("List.doGet()호출");
		
		int currentPage=1;
		 int numberPerPage = 10; //페이지당게시글수
		 int numberOfPageBlock = 10; //페이징블럭스
		 ArrayList<BoardDTO> list=null;
		 
		 int totalRecords, totalPages=0;
		 
	       Connection conn = DBconn.getConnection();
	        BoardDAOImpl dao = new BoardDAOImpl(conn);
	        try {
	        	try {
	        		//번호를 눌러도 상태가 변하지 않았는데 
	        		//list.jsp의 경로 url부분의 currentpage를 여기서currentPage로 적어서 안됏었다. 
	        		currentPage=Integer.parseInt(request.getParameter("currentpage"));
				} catch (Exception e) {
				
				}
	        	
				 list=dao.select(currentPage,numberPerPage);
				 
				 //페이징처리 위한 부분
				 totalRecords=dao.getTotalRecords(); //총레코드
				 totalPages=dao.getTotalPages(numberPerPage); //총페이지수
			} catch (Exception e) {
				// TODO: handle exception
				System.out.println("do get exception");
				e.printStackTrace();
			}
	        DBconn.close();
	        request.setAttribute("list", list);
	        
	     // 페이징 처리 부분
	        PageBlock pageBlock = new PageBlock();
	           pageBlock.setCurrentPage(currentPage);
	           pageBlock.setNumberPerPage(numberPerPage);
	           pageBlock.setNumberOfPageBlock(numberOfPageBlock);
	           
	           int startOfPageBlock = 1;
	           int endOfPageBlock ;
	           // ****
	           startOfPageBlock = (currentPage -1) /numberOfPageBlock * numberOfPageBlock +1 ;
	           endOfPageBlock = startOfPageBlock + numberOfPageBlock -1;
	           if(  endOfPageBlock > totalPages ) endOfPageBlock = totalPages;
	           
	           pageBlock.setStartOfPageBlock(startOfPageBlock);
	           pageBlock.setEndOfPageBlock(endOfPageBlock);
	           
	           if( startOfPageBlock != 1 ) pageBlock.setPrev( true );
	           if( endOfPageBlock != totalPages ) pageBlock.setNext( true );
	        
	        request.setAttribute("pageBlock", pageBlock);
	        request.setAttribute("pageBlock", pageBlock);
		 String path = "/days05/board/list.jsp";
		RequestDispatcher dispatcher = request.getRequestDispatcher(path);
		dispatcher.forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

 

 

list.jsp - 목록 화면

<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@include file="/include.jspf" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<link rel="shortcut icon" type="image/x-icon" href="../images/SiSt.ico">
<title>2022. 6. 20.-오후 12:43:18</title>
<style>
table, td, th {
   border: solid 1px gray;
}

table {
   border-spacing: 3px;
   border-collapse: separate;
}

table, tr, td {
   /* border-radius: 3px; */
   /* padding:3px;  */
   
}

tbody tr  td:nth-of-type(2) {
   text-align: left;
}

a {
   text-decoration: none;
   color: black;
}

a:hover {
   color: red;
}
</style>
<!-- 페이징 처리 style -->
<style>
.pagination {
   margin: 0 auto;
   display: flex;
   justify-content: center;
}

.pagination a {
   color: black;
   float: left;
   padding: 4px 8px;
   text-decoration: none;
   transition: background-color .3s;
}

.pagination a.active {
   background-color: dodgerblue;
   color: white;
}

.pagination a:hover:not (.active ) {
   background-color: #ddd;
}
</style>
<style>
.searchWord {
   background-color: yellow;
   color: red;
}
</style>
<style>
.title {
   display: inline-block;
   white-space: nowrap;
   width: 90%;
   overflow: hidden;
   text-overflow: ellipsis;
}
</style>
</head>
<body>
<h3></h3>
    <div align="center">
  <h2>목록 보기</h2>
  <a href="<%=contextPath %>/cstvsboard/write.htm">글쓰기</a>
  <table style="width:600px;">
    <thead>
      <tr>
        <th width="10%">번호</th>
        <th width="45%">제목</th>
        <th width="17%">작성자</th>
        <th width="20%">등록일</th>
        <th width="10%">조회</th>
      </tr>
    </thead>
    <tbody>
<!--    	list 가 비었는지? -->
     <c:if test="${ empty list }">
        <tr>
          <td colspan="5">등록된 게시글이 없습니다.</td>
        </tr>
      </c:if>
      <c:if test="${ not empty list }">
     <!--  list에 있는 것을 하나하나 dto에 담아서 출력하겠다.  -->
         <c:forEach items="${ list }" var="dto" >
            <tr>
              <td>${ dto.seq }</td>
              <td>${ dto.title }</td>
              <td>${ dto.writer }</td>
              <td>${ dto.writedate }</td>
              <td>${ dto.readed }</td>
            </tr>
         </c:forEach>         
      </c:if>      
    </tbody>
    <tfoot>
<tr>
        <td colspan="5" align="center">
           <div class="pagination"> 
          <%--     <a href="#" class="active">1</a> 
           <a href="<%=contextPath%>/cstvsboard/list.htm?currentpage=1"> 1 </a>  
             <a href="<%=contextPath%>/cstvsboard/list.htm?currentpage=2"> 2 </a>
             <a href="<%=contextPath%>/cstvsboard/list.htm?currentpage=3"> 3 </a>
             <a href="<%=contextPath%>/cstvsboard/list.htm?currentpage=4"> 4 </a>
             <a href="<%=contextPath%>/cstvsboard/list.htm?currentpage=5">5 </a>
             <a href="<%=contextPath%>/cstvsboard/list.htm?currentpage=6"> 6 </a>
             <a href="<%=contextPath%>/cstvsboard/list.htm?currentpage=7"> 7 </a>
             <a href="<%=contextPath%>/cstvsboard/list.htm?currentpage=8"> 8 </a>
             <a href="<%=contextPath%>/cstvsboard/list.htm?currentpage=9"> 9 </a>
             <a href="<%=contextPath%>/cstvsboard/list.htm?currentpage=10"> 10 </a>
			<a href="<%=contextPath%>/cstvsboard/list.htm?currentpage=11"> &raquo; </a>
             <a href="#"> &raquo; </a>         --%>
             
            <c:if test="${ pageBlock.prev }">
                <a href="<%= contextPath %>/cstvsboard/list.htm?currentpage=${ pageBlock.startOfPageBlock -1 }">&laquo;</a>
             </c:if>
             <c:forEach begin="${ pageBlock.startOfPageBlock }" end="${ pageBlock.endOfPageBlock}" step="1" var="i">
               <c:if test="${i==pageBlock.currentPage}">
               <a href="#" class="active">${i }</a>
               </c:if>
               <c:if test="${i!=pageBlock.currentPage}">
               <a href="<%= contextPath %>/cstvsboard/list.htm?currentpage=${ i}">${ i }</a>
               </c:if>
             </c:forEach>
             <!-- >> -->
             <c:if test="${ pageBlock.next }">
                <a href="<%= contextPath %>/cstvsboard/list.htm?currentpage=${ pageBlock.endOfPageBlock +1 }">&raquo;</a>
             </c:if>
           </div>     
        </td>
      </tr>    
      <tr>
        <td colspan="5" align="center">
          <form>
       <select name="searchCondition" id="searchCondition">
              <option value="1">title</option>
              <option value="2">content</option>
              <option value="3">writer</option>
              <option value="4">title+content</option>
            </select>
            <input type="text" name="searchWord" id="searchWord" />
            <input type="submit" value="search" />
          </form>
        </td>
      </tr> 
    </tfoot>
    </table>
    </div>
</body>
</html>

 

 

Write.java 서블릿

package days05;

import java.io.IOException;
import java.sql.Connection;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.util.DBconn;

import days05.board.BoardDAOImpl;
import days05.board.BoardDTO;


@WebServlet("/cstvsboard/write.htm")
public class Write extends HttpServlet {
   private static final long serialVersionUID = 1L;
       

    public Write() {
        super();
       
    }


   protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      System.out.println(">write.doGet() 호출됨");
      
      
      String path = "/days05/board/write.jsp";
      RequestDispatcher dispatcher = request.getRequestDispatcher(path);
      dispatcher.forward(request, response);
      
   }//doGet


   protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      //톰캣 8 post 요청
	   request.setCharacterEncoding("UTF-8");
      System.out.println(">write.doPost() 호출됨");
      
      //1.파라미터 -> BoardDTO dto 생성
        String writer = request.getParameter("writer");
        String pwd = request.getParameter("pwd");
        String email = request.getParameter("email");
        String title = request.getParameter("title");
        String content = request.getParameter("content");
        int tag = Integer.parseInt(request.getParameter("tag"));
        
        BoardDTO dto = new BoardDTO();
        dto.setWriter(writer);
        dto.setPwd(pwd);
        dto.setEmail(email);
        dto.setTitle(title);
        dto.setContent(content);
        dto.setTag(tag);
      
      
      
      //2. insert(dto)
       Connection conn = DBconn.getConnection();
       BoardDAOImpl dao = new BoardDAOImpl(conn);
       int rowCount=0;
       try {
         rowCount = dao.insert(dto);
      } catch (Exception e) {
         System.out.println(">Write.java doPost() Exception..");
         e.printStackTrace();
      }
       DBconn.close();
        
        
        
      //3. list.htm 리다이렉트 요청 -> List.java 서블릿 호출 -> list.java 포워딩
      String location = "/jspPro/cstvsboard/list.htm";
      if(rowCount ==1 ) location += "?write=success";
      response.sendRedirect(location);
      

   }//doPost

}

 

write.jsp 

<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ include file="/include.jspf" %>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>2022. 6. 20. - 오후 2:48:41</title>
<link rel="shortcut icon" type="image/x-icon" href="../images/SiSt.ico">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

<style>
table, td, th {
	border: solid 1px gray;
}

table {
	border-spacing: 3px;
	border-collapse: separate;
}

table, tr, td {
	/* border-radius: 3px; */
	/* padding:3px;  */
	
}
</style>

</head>
<body>

<h3>days05/board/write.jsp</h3>

<div align="center">
  <h2>글 쓰기</h2>
  <!-- 
  action 생략 : http://localhost/jspPro/cstvsboard/write.htm
   -> Write.java 서블릿 
   -> doPost()
    -->
  <form method="post">
  
  <table style="padding: 2px; width: 600px">
			<tr>
				<td colspan="2" align="center"><b>글을 적어주세요</b></td>
			</tr>
			<tr>
				<td align="center">이름</td>
				<td><input type="text" name="writer" size="15"
					autofocus="autofocus" required="required"></td>
			</tr>
			<tr>
				<td align="center">비밀번호</td>
				<td><input type="password" name="pwd" size="15" required="required"></td>
			</tr>
			<tr>
				<td align="center">Email</td>
				<td><input type="email" name="email" size="50" ></td>
			</tr>
			<tr>
				<td align="center">제목</td>
				<td><input type="text" name="title" size="50" required="required"></td>
			</tr>
			<tr>
				<td align="center">내용</td>
				<td><textarea name="content" cols="50" rows="10"></textarea></td>
			</tr>
			<tr>
				<td align="center">HTML</td>
				<td><input type="radio" name="tag" value="1" checked>적용
					<input type="radio" name="tag" value="0">비적용</td>
			</tr>
			<tr>
				<td colspan="2" align="center">
				  <input type="submit" value="작성 완료">
				  &nbsp;&nbsp;&nbsp; 
				  <input type="reset" value="다시 작성">
				  &nbsp;&nbsp;&nbsp; 
				  <a href="<%= contextPath %>/cstvsboard/list.htm">Home</a>
				</td>
			</tr>
		</table>
  
  </form>
</div>

</body>
</html>

 

ex04.jsp

<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<link rel="shortcut icon" type="image/x-icon" href="../images/SiSt.ico">
<title>2022. 6. 20.-오후 12:17:24</title>
<a href="/jspPro/cstvsboard/list.htm">글목록</a><br>
<a href="/jspPro/cstvsboard/write.htm">글쓰기</a><br>
</head>
<body>
<h3></h3>

</body>
</html>

 

href에서 마지막 경로가 /cstvsboard/list.htm로 끝나면 서블릿클래스에서 애노테이션이@WebServlet("/cstvsboard/list.htm") 로 설정되어있는 서블릿이 실행된다. 

 

 

페이징처리 

 

 <c:if test="${ pageBlock.prev }">
                <a href="<%= contextPath %>/cstvsboard/list.htm?currentpage=${ pageBlock.startOfPageBlock -1 }">&laquo;</a>
             </c:if>
             <c:forEach begin="${ pageBlock.startOfPageBlock }" end="${ pageBlock.endOfPageBlock}" step="1" var="i">
               <a href="<%= contextPath %>/cstvsboard/list.htm?currentpage=${ i}">${ i }</a>
             </c:forEach>
             <!-- >> -->
             <c:if test="${ pageBlock.next }">
                <a href="<%= contextPath %>/cstvsboard/list.htm?currentpage=${ pageBlock.endOfPageBlock +1 }">&raquo;</a>
             </c:if>

1dlfEo

   if( startOfPageBlock != 1 ) pageBlock.setPrev( true );
	           if( endOfPageBlock != totalPages ) pageBlock.setPrev( true );

이부분을 next로 바꿈 

if( startOfPageBlock != 1 ) pageBlock.setPrev( true );
	           if( endOfPageBlock != totalPages ) pageBlock.setNext( true );

그리고나서  해결

 

 

 

 

 

현재페이지 표시 

foreach문 안에 if 문을 넣어줌  active 클래스 주기

현재페이지라면,  현재페이지가 아니라면 

  <c:forEach begin="${ pageBlock.startOfPageBlock }" end="${ pageBlock.endOfPageBlock}" step="1" var="i">
               <c:if test="${i==pageBlock.currentPage}">
               <a href="#" class="active">${i }</a>
               </c:if>
               <c:if test="${i!=pageBlock.currentPage}">
               <a href="<%= contextPath %>/cstvsboard/list.htm?currentpage=${ i}">${ i }</a>
               </c:if>
             </c:forEach>

 

 

http://localhost/jspPro/cstvsboard/view.htm?seq=362

1)View.java 서블릿 doGet(){}

2)해당게시글 조회수 1증가 + 

dto=dao.조회수증가메소드(seq)

request.setAttribute("dto",dto);

 

BoardDAO 인터페이스 메소드 추가 

BoardDAOImpl 클래스 메소드 오버라이딩 코딩 

3)view.jsp 포워딩 

화면게시글 정보 출력코딩 

 

 

View.java서블릿 

package days05.board;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.util.DBconn;

/**
 * Servlet implementation class View
 */
@WebServlet("/cstvsboard/view.htm")
public class View extends HttpServlet {
   private static final long serialVersionUID = 1L;
       

    public View() {
        super();

    }

    
   protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      ///cstvsboard/view.htm?seq=364
      System.out.println(">View.doGet() 호출됨");
      
      int seq = Integer.parseInt(request.getParameter("seq"));
      
      Connection conn = DBconn.getConnection();
        BoardDAOImpl dao = new BoardDAOImpl(conn);
        BoardDTO dto = null;
        try {
           //트랜잭션 처리 + 서비스 클래스
           //ㄱ.
           dao.increaseReaded(seq);
           //ㄴ.
           dto = dao.view(seq);
           request.setAttribute("dto", dto);
   
        } catch (SQLException e) {
            System.out.println(">View.doGet() Exception");
            e.printStackTrace();
        }
        DBconn.close();
        
        //view.jsp 포워딩
        String path = "/days05/board/view.jsp";
      RequestDispatcher dispatcher = request.getRequestDispatcher(path);
      dispatcher.forward(request, response);
      
   }


   protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


   }

}

 

 

view.jsp

<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@include file="/include.jspf" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<link rel="shortcut icon" type="image/x-icon" href="../images/SiSt.ico">
<title>2022. 6. 21.-오전 10:32:35</title>
<style>
  table{
     border-spacing: 3px;
     border-collapse: separate; 
   }
   table,  tr, td {
      border:solid 1px gray;
      /* border-radius: 3px;  
      padding:3px;   */ 
   }
   
 #tblContent{
   width:600px;
 } 
</style>
</head>
<body>
<h3></h3>
<div align="center">
  <h2>내용보기</h2>
  <!-- <table id="tblContent" class="table"> -->
  <table id="tblContent">
   <tr>
       <td>이름</td>
       <td>${ dto.writer }</td>
       <td>등록일</td>
       <td>${ dto.writedate }</td>
   </tr>
   <tr>
       <td>Email</td>
       <td><a href="mailto:${ dto.email }">${ dto.email }</a></td>
       <td>조회</td>
       <td>${ dto.readed }</td>
   </tr>
   <tr>
        <td>제목</td>
        <td colspan="3">${ dto.title }</td>
   </tr>
   <tr>
       <td colspan="4" style="padding:15px;height: 200px;text-align: left;vertical-align: top">
       ${ dto.content }
       </td>
   </tr>
   <tr>
       <td colspan="4" align="center">
           <a class="btn btn-secondary"  href="<%= contextPath %>/cstvsboard/edit.htm?seq=${ dto.seq }" id="editLink">수정하기</a>
           <a class="btn btn-secondary"  href="<%= contextPath %>/cstvsboard/delete.htm?seq=${ dto.seq }" id="deleteLink">삭제하기</a>
           <a class="btn btn-secondary"  href="<%= contextPath %>/cstvsboard/list.htm" id="homeLink">HOme</a>
       </td>
   </tr>
</table>
</div>
</body>
</html>

내용이 출력되고 조회수도 증가되는 것을 볼 수 있다.

수정하기 

1./cstvsboard/edit.htm?seq=641 get방식요청 =>

Edit.java 서블릿 get방식이니까 doGet(){   seq에 따른 dto 정보를 얻어옴  }

포워딩 

edit.jsp 

 

2.edit.jsp

이름: [] 

제목: [안녕/hello]

내용: []

등 출력

 [저장][취소]

 

3. 저장버튼을 눌렀을때 

/cstvsboard/edit.htm => post 방식요청 => Edit.java 서블릿  doPost(){

파라미터를 가지고 dto 생성  dao.update(dto)/dao.edit(dto)

}

 

 

삭제

 

'JSP' 카테고리의 다른 글

[JSP] 로그인 화면  (0) 2022.06.22
[JSP] 클라이언트와 대화 - 쿠키  (0) 2022.06.21
[JSP]자바빈즈  (0) 2022.06.20
[JSP] 페이지 모듈화와 요청 흐름 ->공통적인 부분 처리  (0) 2022.06.20
[JSP] 에러처리  (0) 2022.06.20
Comments