728x90

new 😁dynamic project

src

    -kosta.action

        -Action.java(interface) -> public ActionForward execute(HttpServletRequest request, HttpServletResponse response) throws                                                             Exception;

        -ActionForward.java (private boolean isRedirect, private String path => get,set메소드

        -InsertAction.java (actionforward forward, BoardService service(getInstance), service.insertBoardService(request);, do로 가면 redirect , setPath ("listAction.do"), return forward; 

        -InsertActionForm.java (boardService 불필요, forward만 선언 다만 패스선언해줄때 "/insert_form.jsp"

        -ListAction.java

        -DetailAction.java

        -UpdateAction.java

        -UpdateActionForm.java

        -DeleteAction.java

        -InsertReplyAction.java

    -kosta.controller

        -Controller.java(Servlet) ->/board/* , doProcess -> requestURI, contextPath, command(requestURI.substring(contextPath.length()+7), 

        action, actionForward 생성, forward if, else처리

    -kosta.mapper

        -BoardMapper.java(interface) sososososososos simple

        -Board.xml  ->  mapper namespace = "kosta.mapper.BoardMapper" sql문 insert id = insertBoard, parameterType = "Board"

    -kotsa.model

        -Board.java  -> implements Serializable

        -BoardDAO2.java    -> getInstance안에 return dao만들고 sqlsessionfactory getsqlsessionfactory() 안에 resource = "mybatis-config.xml"이랑 연결하고 inputstream in 과 함께 try catch절 in = Resources.getResourceAsStream(resource);  return new SqlSessionFactoryBuilder().build(in);

    public int insertBoard(Board board) 

 SqlSession sqlSession = getSqlSessionFactory().openSession();

try  re = sqlSession.getMapper(BoardMapper.class).insertBoard(board);  if(re>0) {

               sqlSession.commit(); 

            }else {

               sqlSession.rollback();

            }

         }

        -BoardService.java -> private static boardservice, dao, public static BoardService getinstance() 안에 dao = boardDAO.getInstance, return service;  public int insertBoardService(___request)throws exception -> board하나만들어서 setTitle(request.getParameter("title") return dao.insertBoard(board);

 

        -Reply.java   r_no, r_title, r_writer, r_contents, r_regdate, int seq(맨 뒤에 추가)

        -Search.java   string[] area, string searchKey

        -ListModel.java

        -FileDownloadHelper.java(주어짐)

        -ImageUtil.java(주어짐)

    -mybatis-config.xml  => kosta.model.Board , Board , mapper resource = "kosta/mapper/Board.xml"

 

 

int insertBoard(Board board)

int updateBoard(Board board)

int deleteBoard(int seq)

List<Board> listBoard(Search search, RowBounds row)

Board detailBoard(int seq)

int insertReply(Reply reply)

List<Reply> listReply(int seq)

int countBoard(Search search)

 

webcontent

    -META-INF

    -WEB-INF

        lib(cos.jar추가)

    -upload

    -index.html   location.href = "board/listAction.do"

    -insert_form.jsp   <form action="insertAction.do" method="post" enctype="multipart/form-data">

    -list.jsp

    -detail.jsp

    -update_form.jsp   <form action="updateAction.do"  <input type="hidden" name="seq" value="${board.seq }">

    -download.jsp(주어짐)

 

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>   

<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>   

 

--프로젝트 생성

--JNDI세팅 context사이에 추가

<Resource auth="Container" driverClassName="oracle.jdbc.driver.OracleDriver" maxActive="100" maxIdle="30" maxWait="10000" name="jdbc/oracle" password="1234" type="javax.sql.DataSource" url="jdbc:oracle:thin:@localhost:1521:XE" username="kosta202"/>

--패키지 생성

--테이블 생성

 

--컨트롤러 생성 Controller (servlet), doGet(), doPost() ->doProcess()생성

--index.html (URL에서 식별하기 위한 문자열 추출)

 

--Action(인터페이스), ActionForward.java

InsertActionForm.do => Controller식별 => InsertActionForm.do => Controller해당뷰 이동 => insert_form.jsp출력

 

--BoardService, BoardDAO (연관관계 : service에는 dao객체가 필요함)

--dao와 mybatis연결 (mybatis-config.xml => SqlSession객체) 

--myBatis-config.xml

--BoardMapper(interface)

--Board.xml

 

--insertAction.do => Controller => InsertAction execute() => boardService(Request.getParameter("") board안에 set으로 넣어주고 => service에서 dao -insertBoard() => Redirect : listAction.do 

--listAction.do => ListAction생성 => Service : listBoardService() => Dao listBoard() => Board.mapper listBoard()추가 => sqlSession => listBoard(Board.xml) => list리턴 => request.setAttribute(key, value) => list.jsp 

--list.jsp=> 제목=>detailAction.do? post.seq => detailAction생성=> 글번호 전달 =>Service detailBoardService(seq) => dao detailBoard(seq)=>Board객체 리턴 => request.setAttribute("board", board)=>detail.jsp

 

 

 

 


 

--insertAction.java

public ActionForward execute(HttpServletRequest request, HttpServletResponse response) throws Exception {

                ActionForward forward = new ActionForward();

                BoardService service = BoardService.getInstance();

                

                service.insertBoardService(request);

                

                forward.setRedirect(true);

                forward.setPath("listAction.do");

                

                return forward;

        }

--listAction.java

public ActionForward execute(HttpServletRequest request, HttpServletResponse response) throws Exception {

                ActionForward forward = new ActionForward();

                BoardService service = BoardService.getInstance();

                

                //Search search = new Search();

                ListModel listModel = service.listBoardService(request);

                request.setAttribute("listModel", listModel);

                

                forward.setRedirect(false);

                forward.setPath("/list.jsp");

                

                

                return forward;

        }

--mycontroller

@WebServlet("/board/*") //board이후에 나오는 요청은 다 내가 담당할거야 - 각각의 로직에 대한 URL구분

public class MyController extends HttpServlet {

        private static final long serialVersionUID = 1L;

 

    public MyController() {

        super();

    }   

   

    public void doProcess(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

       

        String requestURI = request.getRequestURI();

        

        //insertFormAction.do만 추출하기

        String contextPath = request.getContextPath();

        String command = requestURI.substring(contextPath.length()+7);

        

        Action action = null;

        ActionForward forward = null;

        

        if(command.equals("insertActionForm.do")) {

                action = new InsertActionForm();

                try {

                        forward = action.execute(request, response);

                        } catch (Exception e) {

                                e.printStackTrace();

                        }

        }

        if(forward !=null) {

                if(forward.isRedirect()) {

                        response.sendRedirect(forward.getPath());

                }else {

                        RequestDispatcher dispatcher = request.getRequestDispatcher(forward.getPath());

                        dispatcher.forward(request, response);

                }

        }

    }

 

 

--Board.xml

<select id="listBoard" parameterType="Search" resultType="Board" >

                select * from board

                        <if test="area != null">

                                <where>

                                        <!-- where (title LIKE %aa% OR writer LIKE %aa% 조건이3개 이므로 여러개일때 -->

                                        <foreach collection="area" item = "item" separator="OR" open ="(" close=")" >

                                                <!-- item은 리터럴 형식이라 $사요으 searchKey만 변수로 가져와서 # -->

                                                ${item} LIKE #{searchKey}

                                        </foreach>

                                </where>

                        </if>

                order by seq desc

        </select> 

 

<!--전체 글갯수를 알고싶어요 -->

        <select id="countBoard" parameterType="Search" resultType = "int">

                select count(*) from board

                <if test="area != null">

                                <where>

                                        <!-- where (title LIKE %aa% OR writer LIKE %aa% 조건이3개 이므로 여러개일때 -->

                                        <foreach collection="area" item = "item" separator="OR" open ="(" close=")" >

                                                <!-- item은 리터럴 형식이라 $사요으 searchKey만 변수로 가져와서 # -->

                                                ${item} LIKE #{searchKey}

                                        </foreach>

                                </where>

                        </if>

        </select>

 

--boardDAO

  private static BoardDAO2 dao = new BoardDAO2();

     

      public static BoardDAO2 getInstance() {

         return dao;

      }

      public SqlSessionFactory getSqlSessionFactory() {

         String resource = "mybatis-config.xml";

         InputStream in = null;

        

         try {

            in = Resources.getResourceAsStream(resource);

         } catch (Exception e) {

            e.printStackTrace();

         }

         return new SqlSessionFactoryBuilder().build(in);

      }

 public List<Board> listBoard(Search search, int startRow) {

          SqlSession sqlSession = getSqlSessionFactory().openSession();

          List<Board> list = null;

         

          try {

                  list = sqlSession.getMapper(BoardMapper.class).listBoard(search, new RowBounds(startRow, 2));

                

                 

          } catch (Exception e) {

                  e.printStackTrace();

          }finally {

                  if(sqlSession!=null) {

                          sqlSession.close();

                  }

          }

          return list;

      }

 

--boardservice

private static BoardService service = new BoardService();

        private static BoardDAO2 dao;

        private static final int PAGE_SIZE=2;//페이지 당 글갯수 = 2

        

        public static BoardService getInstance() {

                dao = BoardDAO2.getInstance();

                return service;

        }

        

        public int insertBoardService(HttpServletRequest request)throws Exception{

                request.setCharacterEncoding("utf-8"); //boardService에 만들어주는 것이 더 타당

                

                //파일업로드(경로,파일크기,인코딩방식,파일이름 중첩정책)

                String uploadPath = request.getRealPath("upload");

                int size = 20 * 1024 * 1024; //20MB

                

                //실질적인 파일업로드가 이뤄지는 곳

                MultipartRequest multi = new MultipartRequest(request, uploadPath, size, "utf-8", new DefaultFileRenamePolicy());

                

                

                Board board = new Board();

                board.setTitle(multi.getParameter("title"));

                board.setWriter(multi.getParameter("writer"));

                board.setContents(multi.getParameter("contents"));

                board.setFname("");

                

                //파일업로드 DB(파일이름 저장)

                if(multi.getFilesystemName("fname")!=null) {

                        String fname = (String)multi.getFilesystemName("fname");

                        board.setFname(fname);

                        

                //썸네일 이미지(gif, jpg) => aa.gif, aa.jpg

                String pattern = fname.substring(fname.indexOf(".")+1);//gif

                String head = fname.substring(0,fname.indexOf("."));//aa

                

                //원본 File객체

                String imagePath = uploadPath + "\\"+fname;

                File src = new File(imagePath);

                

                //썸네일 File객체

                String thumPath = uploadPath + "\\" + head + "_small."+pattern;

                File dest = new File(thumPath);

                

                if(pattern.equals("gif")|| pattern.equals("jpg")) {

                        ImageUtil.resize(src, dest, 100, ImageUtil.RATIO);

                }

                        

                }

                

                return dao.insertBoard(board);

                

        }

public ListModel listBoardService(HttpServletRequest request) throws Exception{

                

                 request.setCharacterEncoding("utf-8");

                 Search search = new Search();

                 HttpSession session = request.getSession();

                

                 //검색할 경우

                 if(request.getParameterValues("area")!=null) {

                         session.removeAttribute("search");

                         search.setArea(request.getParameterValues("area")); //search객체 안에 담음

                         search.setSearchKey("%"+request.getParameter("searchKey")+"%"); //%%안에 문자열  넣을때 ''사용 안해도 됨

                         session.setAttribute("search", search);

                 }

                

                //검색 후 페이지를 출력할 경우

                 else if(session.getAttribute("search")!=null) {

                         search = (Search)session.getAttribute("search");

                 }

                

                //페이지처리

                //페이지당 글갯수(PAGE_SIZE), 총글갯수, 총페이지수, 전체페이지

                

                //총글갯수(DB에 물어보기)

                int totalCount = dao.countBoard(search);

                

                //총페이지수

                int totalPageCount = totalCount/PAGE_SIZE;

                if(totalCount%PAGE_SIZE> 0) {

                        totalPageCount++;

                }

                

                //현재페이지

                String pageNum = request.getParameter("pageNum");

                if(pageNum == null) {

                        pageNum = "1";

                }

                int requestPage = Integer.parseInt(pageNum);

                

                //startPage

                //startPage = 현재페이지 - (현재페이지-1) % 5

                int startPage = requestPage - (requestPage-1)%5;

                

                //endPage

                int endPage = startPage + 4;

                if(endPage>totalPageCount) {

                        endPage = totalPageCount;

                }

                //startRow = (현재페이지-1) * (페이지당 글갯수)

                int startRow = (requestPage-1)*PAGE_SIZE;

                

                List<Board> list = dao.listBoard(search, startRow);

                

                ListModel listModel =

                                new ListModel(list, requestPage, totalPageCount, startPage, endPage);

        

                return listModel;

        }

 

 

--listmodel

public class ListModel {

        private List<Board> list;

        private int requestPage;

        private int totalPageCount;

        private int startPage;

        private int endPage;

 

--mybatis

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

<!DOCTYPE configuration

  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"

  "http://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>

        <typeAliases>

                <typeAlias type="kosta.model.Board" alias = "Board"/>

                <typeAlias type="kosta.model.Reply" alias = "Reply"/>

                <typeAlias type="kosta.model.Search" alias = "Search"/>

        </typeAliases>

        

        <environments default="development">

                <environment id="development">

                        <transactionManager type="JDBC"/>

                        <dataSource type="JNDI">

                                <property name="data_source" value="java:comp/env/jdbc/oracle"/>

                        </dataSource>

                </environment>          

        </environments>

        

        <mappers>

                <mapper resource="kosta/mapper/Board.xml"/>

        </mappers>

        

</configuration>

--detail.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>글세부보기</title>

</head>

<body>

        <ul>

                <li>${board.seq}</li>

                <li>${board.title}</li>

                <li>${board.writer}</li>

                <li><a href = "/MVC/download.jsp?filename=${board.fname }">${board.fname}</a></li>

                <li>${board.contents}</li>

                <li>${board.hitcount}</li>

        </ul><br>

        

        <div>

                <h3>댓글목록</h3>

                <table border="1">

                        <tr>

                                <td>댓글번호</td>

                                <td>댓글제목</td>

                                <td>댓글작성자</td>

                                <td>댓글내용</td>

                                <td>댓글날짜</td>

                        </tr>

                        <c:forEach var="reply" items="${replies}">

                                <tr>

                                        <td>${reply.r_no}</td>

                                        <td>${reply.r_title}</td>

                                        <td>${reply.r_writer}</td>

                                        <td>${reply.r_contents}</td>

                                        <td>${reply.r_regdate}</td>

                                </tr>

                        </c:forEach>

                </table>

        </div>

        <br>

        

        <form action = "insertReplyAction.do" method = "post">

                <input type = "hidden" name = "seq" value = "${board.seq}">

                댓글제목 : <input type = "text" name = "r_title"><br>

                댓글작성자 : <input type = "text" name = "r_writer"><br>

                댓글내용 : <input type = "text" name = "r_contents"><br>

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

        </form>

        <br>

        

        

        <a href = "updateFormAction.do?seq=${board.seq}">글수정</a>

        <a href = "deleteAction.do?seq=${board.seq}">글삭제</a>

</body>

</html>

 

--list.jsp

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

    pageEncoding="UTF-8"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>   

<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>   

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>글 목록</title>

</head>

<body>

        <a href = "insertActionForm.do">글쓰기</a>

        <table border = "1">

                <tr>

                        <td>글번호</td>

                        <td>이미지</td>

                        <td>글제목</td>

                        <td>작성자</td>

                        <td>작성일자</td>

                        <td>조회수</td>

                </tr>

                

                

                <c:forEach var = "board" items = "${listModel.list}">

             <tr>

                        <td>${board.seq }</td>

                        <td>

                                        <c:if test="${board.fname != null }">

                                                <c:set var="head" value="${fn:substring(board.fname,

                                                                                                0, fn:length(board.fname)-4) }"></c:set>

                                                <c:set var="pattern" value="${fn:substring(board.fname,

                                                fn:length(head) +1, fn:length(board.fname)) }"></c:set>

                                        

                                                <c:choose>

                                                        <c:when test="${pattern == 'jpg' || pattern == 'gif' }">

                                                                <img src="/MVC/upload/${head }_small.${pattern}">

                                                        </c:when>

                                                        <c:otherwise>

                                                                <c:out value="NO IMAGE"></c:out>

                                                        </c:otherwise>

                                                </c:choose>

                                        </c:if>

                        </td>                   

                        <td><a href = "detailAction.do?seq=${board.seq}">${board.title}</a></td>

                        <td>${board.writer}</td>

                        <td>

                                <fmt:parseDate var= "dt" value = "${board.regdate}" pattern="yyyy-MM-dd HH:mm:ss"/>

                                <fmt:formatDate value="${dt}" pattern = "yyyy/MM/dd"/>

                        </td>

                        <td>${board.hitcount}</td>

                </tr>

                </c:forEach>

        </table>

        

        <br><br>

        

        <!-- 페이지처리 영역 -->

        <!-- 이전영역 -->

        <c:if test="${listModel.startPage>5}">

                <a href="listAction.do?pageNum=${listModel.startPage-1}">[이전]</a>

        </c:if>

        <!-- 페이지목록 -->

        <c:forEach var="pageNo" begin="${listModel.startPage }" end ="${listModel.endPage }" >

                <c:if test="${listModel.requestPage == pageNo }"><b></c:if>

                        <a href ="listAction.do?pageNum=${pageNo}">[${pageNo}]</a>

                <c:if test="${listModel.requestPage == pageNo }"></b></c:if>

        </c:forEach>

        

        <!-- 이후영역 -->

        <c:if test="${listModel.endPage<listModel.totalPageCount}">

                <a href="listAction.do?pageNum=${listModel.endPage + 1}">[이후]</a>

        </c:if>

        

        <form action = "listAction.do" method = "post">

                <input type ="checkbox" name = "area" value ="title">제목

                <input type ="checkbox" name = "area" value ="writer">작성자

                <input type = "text" name = "searchKey" size = "10">

                <input type = "submit" value = "검색"><br>

                <a href = "listAction.do">list로 다시 돌아가기</a>

        </form>

        

        

        

</body>

</html>

 

--index.html

<head>

<meta charset="UTF-8">

<title>Insert title here</title>

<script type="text/javascript">

        location.href = "board/listAction.do"

</script>

</head>

 

 

 

728x90

+ Recent posts