ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • JSP - 게시판 만들기 연습
    기타/Servlet 2020. 12. 15. 16:04

    JSP코드, 서블릿(자바언어), MyBatis 프레임웍을 활용한 인터페이스를 구현한 소스 및 실행화면 캡쳐 

     

    1. 다운로드 받은 유틸들을 폴더에 넣어준다.

     

     

    2. 로그문 출력을 도와줄 log4j.properties 파일을 만든다

    # Root logger option
     # Log4j Setting file
    log4j.rootLogger=DEBUG, console, R
    
    # root 설정
     # Daily file log
    log4j.appender.R=org.apache.log4j.DailyRollingFileAppender
    log4j.appender.R.File=J:\\logs/member.log
    log4j.appender.R.DatePattern='.'yyyy-MM-dd
    log4j.appender.R.layout=org.apache.log4j.PatternLayout
    log4j.appender.R.layout.ConversionPattern=[%d{HH:mm:ss}][%-5p](%F:%L)-%m%n
    
    
    # Console log (콘솔 로그)
    log4j.appender.console=org.apache.log4j.ConsoleAppender
    log4j.appender.console.layout=org.apache.log4j.PatternLayout
    log4j.appender.console.layout.ConversionPattern=[%d{HH:mm:ss}][%-5p](%F:%L)-%m%n
    log4j.appender.console.ImmediateFlush=true

    log4j.appender.R.File= 실제 폴더가 있는 링크로 경로지정

     

     

    3. MyBatis 프레임웍 사용을 위한 패키지를 만들어 준다.

     

     

    4. com.mvctest.bean 패키지 안에 MvcBoard.java 파일을 만들어준다

    package com.mvctest.bean;
    
    import java.sql.Timestamp;
    public class MvcBoard {
    
    	private long bId; // 자동증가
    	private String mId; // 게시자 아이디
    	private String bTitle;// 게시글제목
    	private String bContent;// 게시글 내용
    	private Timestamp bDate; // 게시일시
    	private int bHit; // 게시글읽은 횟수
    	private int bGroup;// 소속 본글 bId
    	private int bStep;// 댓글의 게시순서
    	private int bIndent;// 리스트에 댓글의 댓글 등 들여쓰기
    	
        //bean 파일은 기본생성자가 있어야한다.
    	public MvcBoard() { }
    
    	public long getbId() {
    		return bId;
    	}
    
    	public void setbId(long bId) {
    		this.bId = bId;
    	}
    
    	public String getmId() {
    		return mId;
    	}
    
    	public void setmId(String mId) {
    		this.mId = mId;
    	}
    
    	public String getbTitle() {
    		return bTitle;
    	}
    
    	public void setbTitle(String bTitle) {
    		this.bTitle = bTitle;
    	}
    
    	public String getbContent() {
    		return bContent;
    	}
    
    	public void setbContent(String bContent) {
    		this.bContent = bContent;
    	}
    
    	public Timestamp getbDate() {
    		return bDate;
    	}
    
    	public void setbDate(Timestamp bDate) {
    		this.bDate = bDate;
    	}
    
    	public int getbHit() {
    		return bHit;
    	}
    
    	public void setbHit(int bHit) {
    		this.bHit = bHit;
    	}
    
    	public int getbGroup() {
    		return bGroup;
    	}
    
    	public void setbGroup(int bGroup) {
    		this.bGroup = bGroup;
    	}
    
    	public int getbStep() {
    		return bStep;
    	}
    
    	public void setbStep(int bStep) {
    		this.bStep = bStep;
    	}
    
    	public int getbIndent() {
    		return bIndent;
    	}
    
    	public void setbIndent(int bIndent) {
    		this.bIndent = bIndent;
    	}
    
    	@Override
    	public String toString() {
    		return "MvcBoard [bId=" + bId + ", mId=" + mId + ", bTitle=" + bTitle + ", bContent=" + bContent + ", bDate="
    				+ bDate + ", bHit=" + bHit + ", bGroup=" + bGroup + ", bStep=" + bStep + ", bIndent=" + bIndent + "]";
    	}
    }

    bean 파일은 미리 생성해 놓은 MVC_BOARD 테이블을 토대 만들었다

     

     

    5. com.mvctest.dao 패키지 안에 MvcBoardDAO.java 인터페이스를 만들어 준다.

    만들어준 인터페이스 안에는 웹 페이지에서 사용할 기능들을 생각하며 작성해준다.

    public interface MvcBoardDAO {
    // 웹페이지에서 사용할 기능을 특화 
    	public void write(MvcBoard bean);
    
    	public List<MvcBoard> list();
    
    	public MvcBoard contentView(long bId);
    
    	public void modify(MvcBoard bean);
    
    	public void delete(long bId);
    
    	public MvcBoard reply_view(long bId);
    
    	public void reply(MvcBoard bean);
    
    	public void replyShape(HashMap<String, Integer> map);
    
    	public void upHit(long bId);
    }
    

     

     

    6. com.mvctest.common 패키지에 SMC.xml을 만들어 준다.

    <?xml version="1.0" encoding="UTF-8"?>
    <!-- 약속처럼 외워야하는 부분 -->
    <!DOCTYPE configuration
    PUBLIC "-//mybatis.org//DTD config 3.0//EN"
    "http://mybatis.apache.org/dtd/mybatis-3-config.dtd">
    
    <configuration>
    
    	<typeAliases>
    		<typeAlias type="com.mvctest.bean.MvcBoard" alias="board" />
    	</typeAliases>
    	
    	<environments default="development">
    		<environment id ="development">
    			<transactionManager type="JDBC" /> 
    			
    			<dataSource type = "UNPOOLED">
    				<property name="driver" value="oracle.jdbc.driver.OracleDriver"/>
    				<property name="url" value="jdbc:oracle:thin:@127.0.0.1:1521:xe"/>
    				<property name="username" value="mvcboard"/>
    				<property name="password" value="mvcboard"/>
    			</dataSource>
    
    		</environment>
    	</environments>
    	
    	<mappers>
    		<mapper resource = "com/mvctest/xml/MvcBoard.xml" />
    	</mappers>
    	
    </configuration>

     

    사용한 모델명 = "com.mvctest.bean.MvcBoard" 이 너무 길기 때문에 별칭 board를 만들어 준다.

    <typeAlias type="com.mvctest.bean.MvcBoard" alias="board" />

     

    <enviroment>을 이용해 어느 DB에 접속 할 것인지 설정해준다.

    <mapper>을 이용해 어떤 SQL들을 사용할지 불러와준다.

     

     

    7. mybatis를 부릴떄 사용할 수 있는 유틸리티 클래스

    //mybatis를 부릴떄 사용할 수 있는 유틸리티 클래스
    public class MBUtils {
    	public static SqlSessionFactory getSqlSessionFatory() {
    		String resource = "com/mvctest/common/SMC.xml" ;
    		InputStream reader = null;
    		try {
    			reader = Resources.getResourceAsStream(resource);
    		} catch (IOException e) {
    			e.printStackTrace();
    			throw new IllegalArgumentException(e);
    		}
    		return new SqlSessionFactoryBuilder().build(reader);
    	}
    	
    	public static SqlSession getSession() {
    		return getSqlSessionFatory().openSession(true);
    	}
    }
    

    실사용할 XML의 링크를 적어준다. 이때 구분은 '/'로 할것에 유의

     

     

    8. 질의문이 적힌 MvcBoard.xml을 생성해준다.

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE mapper
    PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
    "mybatis.org/dtd/mybatis-3-mapper.dtd"> 
    
    <mapper namespace = "com.mvctest.dao.MvcBoardDAO">
    	<resultMap id = "result" type = "board">
    		<result property = "bId" column="BID"/> 
    		<result property = "mId" column="MID"/> 
    		<result property = "bTitle" column="BTITLE"/> 
    		<result property = "bContent" column="BCONTENT"/> 
    		<result property = "bDate" column="BDATE"/> 
    		<result property = "bHit" column="BHIT"/> 
    		<result property = "bGroup" column="BGROUP"/> 
    		<result property = "bStep" column="BSTEP"/> 
    		<result property = "bIndent" column="BINDENT"/> 
    	</resultMap>
    
    	<insert id = "write" parameterType="board"> 
    		INSERT INTO MVC_BOARD(
    		BID,MID,BTITLE,BCONTENT,BDATE,BHIT,BGROUP,BSTEP,BINDENT
    		) VALUES(
    		MVC_BOARD_SEQ.NEXTVAL,#{mId},#{bTitle},#{bContent},
    		SYSDATE,0,MVC_BOARD_SEQ.CURRVAL,0,0
    		) 
    	</insert>
    	
    	<select id="list" resultMap = "result">
    		SELECT BID,MID,BTITLE,BCONTENT,BDATE,BHIT,BGROUP,BSTEP,BINDENT
    		FROM MVC_BOARD 
    		ORDER BY BGROUP DESC, BSTEP ASC
    	</select>
    	
    	<select id = "contentView" parameterType="long" resultMap="result">
    		SELECT * FROM 
    		MVC_BOARD 
    		WHERE BID = #{value}
    	</select>
    	
    	<update id = "modify" parameterType="board">
    		UPDATE MVC_BOARD 
    		SET BTITLE = #{bTitle}, BCONTENT=#{bContent}
    		WHERE BID = #{bId}
    	</update>
    	
    	<delete id="delete" parameterType="long">
    		DELETE FROM MVC_BOARD WHERE BID = #{value}
    	</delete> 
    	
    	<select id = "reply_view" parameterType="long" resultMap="result">
    		SELECT * FROM 
    		MVC_BOARD 
    		WHERE BID = #{value}
    	</select>
    	
    	<insert id="reply" parameterType="board">
    		<![CDATA[
    		INSERT INTO MVC_BOARD(
    		BID,MID,BTITLE,BCONTENT,BDATE,BHIT,BGROUP,BSTEP,BINDENT
    		) VALUES(
    		MVC_BOARD_SEQ.NEXTVAL, #{mId}, #{bTitle}, #{bContent},
    		SYSDATE,0,#{bGroup},#{bStep}+1,#{bIndent}+1
    		) 
    		]]>
    	</insert>
    	
    	<update id="replyShape" parameterType="hashMap">
    		<![CDATA[
    		UPDATE MVC_BOARD SET BSTEP = #{bStep}+1 
    		WHERE BGROUP = #{bGroup} 
    		AND BSTEP > #{bStep}
    		]]>
    	</update>
    	
    	<update id = "upHit" parameterType = "long">
    		UPDATE MVC_BOARD SET BHIT = BHIT + 1 
    		WHERE BID = #{value}
    	</update>
    </mapper>

    여기의 타입명 board는 SMC.xml에서 만들어준 alias="board" 와 같은 이름이여야한다.

    <resultMap id = "result" type = "board">
    <insert id = "write" parameterType="board"> 

     

     

    9. 다음은 실제 웹 상에서 보일 jsp 페이지를 만들자

    각각 쓰기, 목록, 읽기, 답글 확인이 있다.

    <body>
    <h1>게시글 작성</h1>
    <form action="write.do" method="post">
    	<table >
    		<tr>
    			<th>게시자id</th>
    			<td><input type="text" name="mId" size="50"></td>
    		</tr>
    		<tr>
    			<th>제목</th>
    			<td><input type="text" name="bTitle" size="50"></td>
    		</tr>
    
    		<tr>
    			<th>내용</th>
    			<td><textarea name="bContent" rows="20" cols="50"></textarea></td>
    		</tr>
    		<tr>
    			<td colspan="2"><input type="submit" value="입력">
    				&nbsp;&nbsp; <a href="list.do">목록보기</a></td>
    		</tr>
    	</table>
    </form>
    </body>
    </html>

    form action을 이용해 입력값을 list.do 라는 페이지에 post 타입으로 넘겨준다.

     

    <h1>게시글목록</h1>
    <%
    	List<MvcBoard> list = (List<MvcBoard>) request.getAttribute("list");
      if (list == null) {
          SqlSession mysession = MBUtils.getSession();
          MvcBoardDAO dao = mysession.getMapper(MvcBoardDAO.class);
          list = dao.list();
          request.setAttribute("list", list);
          mysession.close();
      }
    %>
    
    <table>
    	<colgroup>
    		<col width="5%">
    		<col width="10%">
    		<col width="*">
    		<col width="25%">
    		<col width="10%">
    	</colgroup>
    	<tr>
    		<th>No</th>
    		<th>게시자</th>
    		<th>제목</th>
    		<th>날짜</th>
    		<th>조회수</th>
    	</tr>
    <%
    	for (MvcBoard x : list) {
    	%>
    		<tr>
    			<td class="tc"><%=x.getbId() %></td>
    			<td class="tc"><%=x.getmId() %></td>
    			<td><a href="content_view.do?bId=<%=x.getbId()%>"><%=x.getbTitle() %></a></td>
    			<td class="tc"><%=x.getbDate() %></td>
    			<td class="tc"><%=x.getbHit()%></td>
    		</tr>
    	<%
    	}
    %>
    </table>
    
    <a class="center" href="write.jsp">글작성</a>
    <%
    List<MvcBoard> list = (List<MvcBoard>) request.getAttribute("list");
    if (list == null) {
      SqlSession mysession = MBUtils.getSession();
      MvcBoardDAO dao = mysession.getMapper(MvcBoardDAO.class);
      list = dao.list();
      request.setAttribute("list", list);
      mysession.close();
    }
    %>

    일단 DB에서 글 목록을 가져와야 한다.

     

    글 목록이 저장될 list란 이름의 리스트를 담아 반환해주는 List<MvcBoard>를 생성

    getAtrribute(String name) 메소드를 이용해 list의 값을 구해주며

    지정한 이름의 속성이 존재하지 않을 경우 null을 리턴한다.

     

    getSession을 이용해 값을 가져올 db와 연결한다.

    연결된 db를 getMapper을 이용해 SQL지문 인터페이스 클래스와 연결

    setAttribute로 사용할 MvcBoardDAO에서 이름 정한 list 질의를 선택해준다.

     

    table로 html 코딩을 해준다.

    <%
    for (MvcBoard x : list) {
    %>
    	<tr>
    		<td class="tc"><%=x.getbId() %></td>
    		<td class="tc"><%=x.getmId() %></td>
    		<td><a href="content_view.do?bId=<%=x.getbId()%>"><%=x.getbTitle() %></a></td>
    		<td class="tc"><%=x.getbDate() %></td>
    		<td class="tc"><%=x.getbHit()%></td>
    	</tr>
    <%
    }
    %>

    이제 list를 위에서 만들었으니 for문을 이용해 list값을 뿌려준다.

    제목은 클릭시 view페이지로 넘어가야 니까 a 태그로 링크를 걸어준다.

     

    <h1>글읽기</h1>
    <form action="modify.do" method="post">
    <table>
    	<colgroup>
    		<col width="20%">
    		<col width="*">
    	</colgroup>
    	<tr class="hidden">
    		<td colspan="2">
    			<input type="hidden" name="bId" value="${content_view.bId }"/>
    		</td>
    	</tr>
    	<tr>
    		<th>번호</th>
    		<td>${content_view.bId }</td>
    	</tr>
    	<tr>
    		<th>히트</th>
    		<td>${content_view.bHit }</td>
    	</tr>
    	<tr>
    		<th>게시자</th>
    		<td>${content_view.mId }</td>
    	</tr>
    	<tr>
    		<th>제목</th>
    		<td>
    			<input class="w90"  type="text" name="bTitle" value="${content_view.bTitle }"/>
    		</td>
    	</tr>
    	<tr>
    		<th>내용</th>
    		<td>
    			<textarea class="w90" name="bContent" >${content_view.bContent }</textarea>
    		</td>
    	</tr>
    	<tr>
    		<td colspan="2" class="center">
    			<input type="submit"  value="수정"/>&nbsp;&nbsp;
    			<a href="delete.do?bId=${content_view.bId}">삭제</a>
    			<a href="reply_view.do?bId=${content_view.bId}">댓글달기</a>
    			<a href="list.do">목록</a>
    		</td>
    	</tr>
    </table>
    </form>
    <input type="hidden" name="bId" value="${content_view.bId }"/>

    bid는 값이 있어야 하지만 눈으로 보일 필요는 없어서 hidden으로 감춰준다.

     

    <tr>
    	<th>제목</th>
        <td>
        	<input class="w90"  type="text" name="bTitle" value="${content_view.bTitle }"/>
        </td>
    </tr>
    <tr>
    	<th>내용</th>
        <td>
        	<textarea class="w90" name="bContent" >${content_view.bContent }</textarea>
        </td>
    </tr>

    value 값으로 ${ } 정보를 기본 가져오면서 수정도 할 수 있게 만들었다.

    실제 페이지에서는 읽기 페이지와 수정 페이지가 별도로 분리되어 볼 수 있는데 이번은 게시판 작성의 흐름을 위해서 합친 것같다.

    분리하려면 수정.jsp 파일 만들어서 연결시켜주면 될듯

     

    <h1>댓글쓰기</h1>
    <form action="reply.do" method="post">
    <table>
    	<colgroup>
    		<col width="20%">
    		<col width="*">
    	</colgroup>
    	<tr class="hidden">
    		<td colspan="2">
    			<input type="hidden" name="bId" value="${reply_view.bId }"/>
    			<input type="hidden" name="bGroup" value="${reply_view.bGroup }"/>
    			<input type="hidden" name="bStep" value="${reply_view.bStep }"/>
    			<input type="hidden" name="bIndent" value="${reply_view.bIndent }"/>
    		</td>
    	</tr>
    	<tr>
    		<th>번호</th>
    		<td>${reply_view.bId }</td>
    	</tr>
    	<tr>
    		<th>히트</th>
    		<td>${reply_view.bHit }</td>
    	</tr>
    	<tr>
    		<th>게시자</th>
    		<td><input type="text" name="mId" value=""/></td>
    	</tr>
    	<tr>
    		<th>제목</th>
    		<td><input class="w90" type="text" name="bTitle" value="[답글] ${reply_view.bTitle}"/></td>
    	</tr>
    	<tr>
    		<th>내용</th>
    		<td>
    			<textarea name="bContent" > → ${reply_view.bContent }에 대한 답글</textarea>
    		</td>
    	</tr>
    	<tr>
    		<td colspan="2" class="center">
    			<input type="submit"  value="답변하기"/>&nbsp;&nbsp;
    			<a href="list.do">목록</a>
    		</td>
    	</tr>
    </table>
    </form>

    글쓰기 파일과 비슷하게 만들면 된다.

    대신 bGroup, bStep, bIndent은 보여줄 필요가 없어서 감춰주기

     

     

    10. 만든 것들을 제어할 MVCBoardController.java 서블릿 파일을 만들어준다.

    @WebServlet(description = "웹을컨트롤하는 서블릿", urlPatterns = { "*.do" })
    public class MVCBoardController extends HttpServlet {
    	private static final long serialVersionUID = 1L;
    
    	/**
    	 * @see HttpServlet#HttpServlet()
    	 */
    	public MVCBoardController() {
    		super();
    	}
    
    	/**
    	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
    	 *      response)
    	 */
    	protected void doGet(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		actionDo(request, response);
    	}
    
    	/**
    	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
    	 *      response)
    	 */
    	protected void doPost(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		actionDo(request, response);
    	}
    
    	private void actionDo(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		request.setCharacterEncoding("UTF-8");
    		
    		// 주의 
    		String uri = request.getRequestURI(); // 프로토콜+도메인+기타
    		String contextPath = request.getContextPath();// 프로토콜+도메인
    		String command = uri.substring(contextPath.length());// xxxxxx.do
    
    		BCommand bcommand = null;
    		String viewPage = null;
    		
    		if (command.equals("/write.do")) {
    			bcommand = new BWriteCommand();
    			bcommand.execute(request, response);
    			viewPage = "list.do";
    			
    		} else if (command.equals("/list.do")) {
    			bcommand = new BListCommand();
    			bcommand.execute(request, response);
    			viewPage = "list.jsp";
    			
    		} else if (command.equals("/content_view.do")) {
    			bcommand = new BContentCommand();
    			bcommand.execute(request, response);
    			viewPage = "content_view.jsp";
    		
    		} else if (command.equals("/delete.do")) {
    			bcommand = new BDeleteCommand();
    			bcommand.execute(request, response);
    			viewPage = "list.do";
    			
    		} else if (command.equals("/reply_view.do")) {
    			bcommand = new BReplyViewCommand();
    			bcommand.execute(request, response);
    			viewPage = "reply_view.jsp";
    			
    		}else if (command.equals("/reply.do")) {
    			bcommand = new BReplyCommand();
    			bcommand.execute(request, response);
    			viewPage = "list.do";
    			
    		}else if (command.equals("/modify.do")) {
    			bcommand = new BModifyCommand();
    			bcommand.execute(request, response);
    			viewPage = "list.do";
    		}
    		
    		// 교통순경(배차계)
    		RequestDispatcher dispatcher = request.getRequestDispatcher(viewPage);
    		dispatcher.forward(request, response);
    		
    		System.out.println("개발중 일단 작업종료!");
    
    	}
    
    }

    actionDo를 이용해 get과 post 둘다 같은 곳으로 호출한다.

    command를 이용하여 각각 해당 페이지의 작업을 수행할 클래스에게 내용을 할당한다.

     

    request.getRequestURI() 함수 = 프로젝트 + 파일경로

    ex) http://localhost:8000/jsp08_mvctest/list.jsp

    [return] /jsp08_mvctest/list.jsp

     

    request.getContextPath() 함수 = 프로젝트 Path만 가져온다

    ex) http://localhost:8000/jsp08_mvctest/list.jsp

    [return] /jsp08_mvctest

     

    request.getRequestURL() 함수 = 전체경호

    ex) http://localhost:8000/jsp08_mvctest/list.jsp

    [return] http://localhost:8000/jsp08_mvctest/list.jsp

     

    String.substring(start, length) = 문자열을 추출하는 메서드

    문자열에서 특정 부분만 골라낼때 사용하는 메서드

    start+length 위치까지를 탐색구간으로 설정함

     

    RequestDispatcher

    특정 자원에 처리를 요청하고 처리 결과를 다른 자원에 보내는 역할을 하는 인터페이스

    request에 담긴 정보를 저장하고 있다가 그 다음 페이지에도 계쏙 해당 정보를 볼 수 있게 계속 저장하는 기능

    ex) a.jsp에 담긴 param이라는 파라미터를 b.jsp  / c.jsp 에서도 받아 볼 수 있는 것

    *getRequestDispatcher("이동위치") 하지만 viewPage라는 변수를 이용해서 소스를 깔끔하게 정리

     

    forward()

    다른 자원의 수행 결과가 대신 클라이언트로 응답되도록 하는 기능의 메소드

     

    즉 command에서 실행한 작업을 저장해서 지정한 페이지로 값을 볼 수 있게 해준다.

     

     

    11. command를 연결할 인터페이스 BCommand.java를 만들어준다.

    public interface BCommand {
    	public void execute(HttpServletRequest request, HttpServletResponse response);
    }
    

     

     

    12. 실제 작업을 해줄 command 클래스들을 만들어 준다

    public class BWriteCommand implements BCommand {
    
    	@Override
    	public void execute(HttpServletRequest request, HttpServletResponse response) {
    		String mId = request.getParameter("mId");
    		String bTitle = request.getParameter("bTitle");
    		String bContent = request.getParameter("bContent");
    		
    		// 마이바티스가 다오 부리는 작업 
    		SqlSession mysession = MBUtils.getSession();
    		MvcBoardDAO dao = mysession.getMapper(MvcBoardDAO.class);
    		MvcBoard bean = new MvcBoard();
    		bean.setmId(mId);
    		bean.setbTitle(bTitle);
    		bean.setbContent(bContent);
    		dao.write(bean);
    		mysession.close();
    		
    	}
    
    }
    public class BReplyViewCommand implements BCommand {
    
    	@Override
    	public void execute(HttpServletRequest request, HttpServletResponse response) {
    		long bId = Long.parseLong(request.getParameter("bId"));
    		SqlSession mysession = MBUtils.getSession();
    		MvcBoardDAO dao = mysession.getMapper(MvcBoardDAO.class);
    		dao.upHit(bId);
    		MvcBoard bean = dao.reply_view(bId);
    		request.setAttribute("reply_view", bean);
    		mysession.close();
    		
    	}
    
    }
    public class BReplyCommand implements BCommand {
    
    	@Override
    	public void execute(HttpServletRequest request, HttpServletResponse response) {
    		String mId = request.getParameter("mId");
    		String bTitle = request.getParameter("bTitle");
    		String bContent = request.getParameter("bContent");
    		int bGroup = Integer.parseInt(request.getParameter("bGroup"));
    		int bStep = Integer.parseInt(request.getParameter("bStep"));
    		int bIndent = Integer.parseInt(request.getParameter("bIndent"));
    		
    		SqlSession mysession = MBUtils.getSession();
    		MvcBoardDAO dao = mysession.getMapper(MvcBoardDAO.class);
    		HashMap<String, Integer> map = new HashMap<>();
    		map.put("bGroup", new Integer(bGroup));
    		map.put("bStep", new Integer(bStep));
    		dao.replyShape(map);
    		MvcBoard bean = new MvcBoard();
    		bean.setmId(mId);
    		bean.setbTitle(bTitle);
    		bean.setbContent(bContent);
    		bean.setbGroup(bGroup);
    		bean.setbStep(bStep);
    		bean.setbIndent(bIndent);
    		dao.reply(bean);
    	}
    
    }
    
    public class BModifyCommand implements BCommand {
    
    	@Override
    	public void execute(HttpServletRequest request, HttpServletResponse response) {
    		//수정할 글 아이디를 가져오는 작업
    		long bId = Long.parseLong(request.getParameter("bId"));
    		
    		//수정할 내용을 가져오는 작업
    		String bTitle = request.getParameter("bTitle");
    		String bContent = request.getParameter("bContent");
    		
    		// 마이바티스가 다오 부리는 작업 
    		SqlSession mysession = MBUtils.getSession();
    		MvcBoardDAO dao = mysession.getMapper(MvcBoardDAO.class);
    		MvcBoard bean = new MvcBoard();
    		bean.setbId(bId);
    		bean.setbTitle(bTitle);
    		bean.setbContent(bContent);
    		dao.modify(bean);
    		mysession.close();
    		
    	}
    
    }
    public class BListCommand implements BCommand {
    
    	@Override
    	public void execute(HttpServletRequest request, HttpServletResponse response) {
    		SqlSession mysession = MBUtils.getSession();
    		MvcBoardDAO dao = mysession.getMapper(MvcBoardDAO.class);
    		List<MvcBoard> beans = dao.list();
    		request.setAttribute("list", beans);
    		mysession.close();
    	}
    
    }
    public class BDeleteCommand implements BCommand {
    
    	@Override
    	public void execute(HttpServletRequest request, HttpServletResponse response) {
    		long bId = Long.parseLong(request.getParameter("bId"));
    		SqlSession mysession = MBUtils.getSession();
    		MvcBoardDAO dao = mysession.getMapper(MvcBoardDAO.class);
    		dao.delete(bId);
    		mysession.close();
    				
    		
    	}
    
    }
    public class BContentCommand implements BCommand {
    
    	@Override
    	public void execute(HttpServletRequest request, HttpServletResponse response) {
    		// 넘겨받는 값은 모두 문자열 이므로 값을 숫자로 바꿔준다.
    		long bId = Long.parseLong(request.getParameter("bId"));
    		SqlSession mysession = MBUtils.getSession();
    		MvcBoardDAO dao = mysession.getMapper(MvcBoardDAO.class);
    		dao.upHit(bId);
    		MvcBoard bean = dao.contentView(bId);
    		request.setAttribute("content_view", bean);
    		mysession.close();
    	}
    
    }

     

    13. 해당 jsp 파일을 서버에서 돌리면 이런 결과들이 나온다.

     

    '기타 > Servlet' 카테고리의 다른 글

    request, response, doPost(), doGet() 설명  (0) 2020.12.16
    MyBatis에 대한 설명  (0) 2020.12.15
    JSP-JDBC/mybatis 연습예제  (0) 2020.12.11
    JSP - 자바빈(Bean)  (0) 2020.12.10
    JSP - 예외처리 (Exception)  (0) 2020.12.10

    댓글

Designed by Tistory.