반응형

# Spring WEB MVC_03버전_05 게시판 웹 계층 구현(등록 및 조회)

## 게시물 등록

### BoardController

  • 게시물 등록 기능 작업
  • 한글깨짐 확인 -> web.xml에 필터 추가.
  • @RequestMapping(value="/register.do", method=RequestMethod.POST) public String registerPOST(BoardVO board) { // 게시물 등록 service.register(board); return "redirect:/list.do"; // 등록 후 게시물 보기로 이동. }

### web.xml

  • 한글깨짐 방지 기능 -> web.xml 필터 추가.
<!-- Character Encoding -->
	<filter>
		<filter-name>encodingFilter</filter-name>
		<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
		
		<init-param>
			<param-name>encoding</param-name>
			<param-value>utf-8</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>encodingFilter</filter-name>
		<url-pattern>/*</url-pattern> 
	</filter-mapping>

## 게시판 조회

### boardList.jsp

  • 게시물 제목 클릭 시 해당 게시물의 번호값 가져가도록 a 태그 추가.
 <%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<html lang="en">
<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<script type="text/javascript">
	$(document).ready(function() {
		$("#regBtn").click(()=>{
			location.href="<c:url value='/register.do'/>";
		});
	});
</script>
</head>
<body>
 
<div class="container">
  <h2>메인화면</h2>
  <div class="panel panel-default">
    <div class="panel-heading">Spring WEB MVC 게시판 만들기
    	<button id="regBtn" type="button" class="btn btn-xs pull-right btn-primary">게시물작성</button>
    </div>
    <div class="panel-body">
		<div class="table-responsive">          
			<table class="table table-hover">
				<thead>
					<tr>
						<th>게시물 번호</th>
						<th>제목</th>
						<th>조회수</th>
						<th>등록자</th>
						<th>등록일</th>
					</tr>
				</thead>
				<tbody>
					<c:forEach var="vo" items="${list}">
						<tr>
							<td>${vo.idx}</td>
							<td><a href="<c:url value='/get.do?bno=${vo.idx}'/>">${vo.title}</a></td>
							<td>${vo.count}</td>
							<td>${vo.writer}</td>
							<td><fmt:formatDate pattern="yyyy-MM-dd" value="${vo.indate}"/></td>
						</tr>
					</c:forEach>
				</tbody>
			</table>
		</div>
    </div>
    <div class="panel-footer">메인화면 JSP</div>
  </div>
</div>

</body>
</html>

### BoardController

@RequestMapping(value="/get.do")
public String get(@RequestParam("bno")int bno, Model model) {
  BoardVO board = service.get(bno);
  model.addAttribute("board", board);
  return "get";
}

### get.jsp 생성

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
	<meta charset="UTF-8">
	<title>Insert title here</title>
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
	<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
	<h2>Board Read</h2>
	<div class="panel panel-default">
		<div class="panel-heading">Board Read Page</div>
		<div class="panel-body">
			<div class="form-group">
				<label>Bno</label>
				<input type="text" class="form-control" name="idx" value="${board.idx}" readonly="readonly">
			</div>
			<div class="form-group">
				<label>Title</label>
				<input type="text" class="form-control" name="title" value="${board.title}" readonly="readonly">
			</div>
			<div class="form-group">
				<label>Contents</label>
				<textarea rows="3" class="form-control" name="contents" readonly="readonly">${board.contents}</textarea>
			</div>
			<div class="form-group">
				<label>Writer</label>
				<input type="text" class="form-control" name="writer" value="${board.writer}" readonly="readonly">
			</div>
			<button class="btn btn-default">Modify</button>
			<button class="btn btn-info">List</button>
		</div>
		<div class="panel-footer">상세보기 JSP</div>
	</div>
</div>
</body>
</html>

 

# Spring WEB MVC_03버전_06 게시판 웹 계층 구현(수정 페이지)

## get.jsp

  • 리스트 버튼 클릭 시 리스트로 이동.
  • 수정하기 버튼 클릭 시 수정하기 화면으로 이동.
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<script>
	$(document).ready(()=>{
		$("#list").click(()=>{
			location.href="<c:url value='/list.do'/>";
		});
	});
	
	$(document).ready(()=>{
		$("#modify").click(()=>{
			// 게시물 번호 넘기는 방법1.
			// var idx = $("#idx").val();
			// location.href="<c:url value='/modify.do'/>?bno=" + idx;
			
			// 게시물 번호 넘기는 방법2.
			location.href="<c:url value='/modify.do'/>?bno=${board.idx}";
		});
	});
</script>
</head>
<body>
<div class="container">
	<h2>Board Read</h2>
	<div class="panel panel-default">
		<div class="panel-heading">Board Read Page</div>
		<div class="panel-body">
			<div class="form-group">
				<label>Bno</label>
				<input type="text" class="form-control" name="idx" id="idx" value="${board.idx}" readonly="readonly">
			</div>
			<div class="form-group">
				<label>Title</label>
				<input type="text" class="form-control" name="title" value="${board.title}" readonly="readonly">
			</div>
			<div class="form-group">
				<label>Contents</label>
				<textarea rows="3" class="form-control" name="contents" readonly="readonly">${board.contents}</textarea>
			</div>
			<div class="form-group">
				<label>Writer</label>
				<input type="text" class="form-control" name="writer" value="${board.writer}" readonly="readonly">
			</div>
			<button class="btn btn-default" id="modify">Modify</button>
			<button class="btn btn-info" id="list">List</button>
		</div>
		<div class="panel-footer">상세보기 JSP</div>
	</div>
</div>
</body>
</html>

## BoardController

  • 수정하기 버튼 클릭 시 수정 화면으로 이동되도록 진행.
@RequestMapping(value="/modify.do", method=RequestMethod.POST)
public String modifyGET(@RequestParam("bno")int bno, Model model) {
  BoardVO board = service.get(bno);
  model.addAttribute("board", board);
  return "modify";
}

## modify.jsp 생성

  • 리스트로 이동하는 기능만 추가.
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<script>
	$(document).ready(()=>{
		$("#list").click(()=>{
			location.href="<c:url value='/list.do'/>";
		});
	});
</script>
</head>
<body>
 
<div class="container">
	<h2>Board Modify Page</h2>
	<div class="panel panel-default">
		<div class="panel-heading">Board Modify Page</div>
		<div class="panel-body">
			<form action="<c:url value='/modify.do'/>" method="post">
				<div class="form-group">
					<label>Bno</label>
					<input type="text" class="form-control" name="idx" id="idx" value="${board.idx}" readonly="readonly">
				</div>
				<div class="form-group">
					<label>Title</label>
					<input type="text" class="form-control" name="title" id="title" value="${board.title}">
				</div>
				<div class="form-group">
					<label>Text area</label>
					<textarea rows="3" class="form-control" name="contents" >${board.contents}</textarea>
				</div>
				<div class="form-group">
					<label>Writer</label>
					<input type="text" class="form-control" name="writer" value="${board.writer}" readonly="readonly">
				</div>
				<button type="submit" class="btn btn-primary">Modify</button>
				<button id="remove" type="button" class="btn btn-danger">Remove</button>
				<button id="list" type="button" class="btn btn-info">List</button>
			</form>
		</div>
		<div class="panel-footer">게시물 수정하기 JSP</div>
	</div>
</div>

</body>
</html>

 

# Spring WEB MVC_03버전_07 게시판 웹 계층 구현(수정, 삭제 기능)

## 게시물 삭제 기능

### modify.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<script>
	$(document).ready(()=>{
		$("#list").click(()=>{
			location.href="<c:url value='/list.do'/>";
		});
	});
	
	$(document).ready(()=>{
		$("#remove").click(()=>{
			location.href="<c:url value='/remove.do'/>?bno=${board.idx}";
		});
	});
</script>
</head>
<body>
 
<div class="container">
	<h2>Board Modify Page</h2>
	<div class="panel panel-default">
		<div class="panel-heading">Board Modify Page</div>
		<div class="panel-body">
			<form action="<c:url value='/modify.do'/>" method="post">
				<div class="form-group">
					<label>Bno</label>
					<input type="text" class="form-control" name="idx" id="idx" value="${board.idx}" readonly="readonly">
				</div>
				<div class="form-group">
					<label>Title</label>
					<input type="text" class="form-control" name="title" id="title" value="${board.title}">
				</div>
				<div class="form-group">
					<label>Text area</label>
					<textarea rows="3" class="form-control" name="contents" >${board.contents}</textarea>
				</div>
				<div class="form-group">
					<label>Writer</label>
					<input type="text" class="form-control" name="writer" value="${board.writer}" readonly="readonly">
				</div>
				<button type="submit" class="btn btn-primary">Modify</button>
				<button id="remove" type="button" class="btn btn-danger">Remove</button>
				<button id="list" type="button" class="btn btn-info">List</button>
			</form>
		</div>
		<div class="panel-footer">게시물 수정하기 JSP</div>
	</div>
</div>

</body>
</html>

### BoardController

  • 게시물 삭제 기능
@RequestMapping(value="/remove.do")
public String remove(@RequestParam("bno")int bno) {
  service.remove(bno);
  return "redirect:/list.do";
}

## 게시물 수정 기능

### BoardController

  • 게시물 수정 기능
@RequestMapping(value="/modify.do", method=RequestMethod.POST)
public String modifyPOST(BoardVO board) {
  service.modify(board);
  return "redirect:/list.do";
}

## 게시물 조회수 기능

### BoardMapper

package kr.inflearn.mapper;

import java.util.List;

import org.apache.ibatis.annotations.Mapper;

import kr.inflearn.model.BoardVO;

// 영속 계층
@Mapper
public interface BoardMapper {
	public List<BoardVO> getList();		// 게시물 리스트 가져오기
	public void insert(BoardVO board);	// 게시물 등록
	public BoardVO read(int bno);		// 게시물 상세보기
	public int delete(int bno);			// 게시물 삭제
	public int update(BoardVO board);	// 게시물 수정
	public void count(int bno);			// 조회수 증가
}

### BoardMapper.xml

<update id="count" parameterType="Integer">
  update tb_board set count = count + 1
  where idx = #{idx}
</update>

### BoardService

  • 게시물 상세보기에 mode 추가
package kr.inflearn.service;

import java.util.List;

import kr.inflearn.model.BoardVO;

public interface BoardService {
	public List<BoardVO> getList();				// 게시물 리스트 가져오기
	public void register(BoardVO board);			// 게시물 등록
	public BoardVO get(int bno, String mode);		// 게시물 상세보기
	public int remove(int bno);				// 게시물 삭제
	public int modify(BoardVO board);			// 게시물 수정
}

### BoardController

  • get에 mode 추가. 단순히 상세보기 시에는 mode가 "get", 수정버튼을 눌러 수정화면진입 시에는 "modify"
@RequestMapping(value="/get.do")
public String get(@RequestParam("bno")int bno, Model model) {
  BoardVO board = service.get(bno, "get");
  model.addAttribute("board", board);
  return "get";
}

@RequestMapping(value="/modify.do", method=RequestMethod.GET)
public String modifyGET(@RequestParam("bno")int bno, Model model) {
  BoardVO board = service.get(bno, "modify");
  model.addAttribute("board", board);
  return "modify";
}

### BoardServiceImpl

  • 상세보기 시에만 조회수 카운트 될 수 있도록 처리
@Override
public BoardVO get(int bno, String mode) {
  if (mode.equals("get")) {	// 상세보기 시에만 조회수 카운트
  	mapper.count(bno);
  }
  return mapper.read(bno);
}

## 완성화면

1. 메인 (게시물 리스트 페이지)

  • http://localhost:8081/board/list.do

2. 게시물 작성 페이지

  • http://localhost:8081/board/register.do

3. 게시물 상세보기 페이지

  • http://localhost:8081/board/get.do?bno=4

4. 게시물 수정 페이지

  • http://localhost:8081/board/modify.do?bno=4

반응형
반응형

# Spring WEB MVC_03버전_04 게시판 서비스 계층 구현

## BoardService 인터페이스 생성

  • src/main/java > kr.inflean.service 우 클릭 > New > interface > BoardService 이름으로 생성
package kr.inflearn.service;

import java.util.List;

import kr.inflearn.model.BoardVO;

public interface BoardService {
	public List<BoardVO> getList();		// 게시물 리스트 가져오기
	public void register(BoardVO board);	// 게시물 등록
	public BoardVO get(int bno);		// 게시물 상세보기
	public int remove(int bno);			// 게시물 삭제
	public int modify(BoardVO board);	// 게시물 수정
}

## BoardServiceImpl 생성

  • 구현 클래스 생성
  • src/main/java > kr.inflean.service 우 클릭 > New > class > BoardServiceImpl 이름으로 생성
package kr.inflearn.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import kr.inflearn.mapper.BoardMapper;
import kr.inflearn.model.BoardVO;

@Service
public class BoardServiceImpl implements BoardService {
	
	@Autowired
	private BoardMapper mapper;		// DI (의존성 주입)
	
	@Override
	public List<BoardVO> getList() {
		return mapper.getList();
	}

	@Override
	public void register(BoardVO board) {
		mapper.insert(board);
	}

	@Override
	public BoardVO get(int bno) {
		return mapper.read(bno);
	}

	@Override
	public int remove(int bno) {
		return mapper.delete(bno);
	}

	@Override
	public int modify(BoardVO board) {
		return mapper.update(board);
	}

	
}

## root-context

  • root-context에 아래 component-scan 추가.
<context:component-scan base-package="kr.inflearn.service" />

 

# Spring WEB MVC_03버전_05 게시판 웹 계층 구현

## BoardController

  • 게시물 리스트 작업
package kr.inflearn.web;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import kr.inflearn.model.BoardVO;
import kr.inflearn.service.BoardService;

@Controller
public class BoardController {

	@Autowired
	private BoardService service;
	
	@RequestMapping("/list.do")
	public String list(Model model) {
		List<BoardVO> list = service.getList();		
		model.addAttribute("list", list);
		return "boardList";
	}
	
}

## servlet-context 수정

  • 설정되어 있는 prefix views > board로 변경
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  <beans:property name="prefix" value="/WEB-INF/board/" />
  <beans:property name="suffix" value=".jsp" />
</beans:bean>

## web.xml

  • 요청 mapping 변경 기존 / > *.do 로 변경
<servlet-mapping>
  <servlet-name>appServlet</servlet-name>
  <url-pattern>*.do</url-pattern>
</servlet-mapping>

## boardList.jsp 생성

<div class="container">
  <h2>Panel Heading</h2>
  <div class="panel panel-default">
    <div class="panel-heading">Panel Heading</div>
    <div class="panel-body">Panel Content</div>
  </div>
</div>
<div class="table-responsive">          
  <table class="table">
    <thead>
      <tr>
        <th>#</th>
        <th>Firstname</th>
        <th>Lastname</th>
        <th>Age</th>
        <th>City</th>
        <th>Country</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>1</td>
        <td>Anna</td>
        <td>Pitt</td>
        <td>35</td>
        <td>New York</td>
        <td>USA</td>
      </tr>
    </tbody>
  </table>
  </div>
 <%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html lang="en">
<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
 
<div class="container">
  <h2>메인화면</h2>
  <div class="panel panel-default">
    <div class="panel-heading">Spring WEB MVC 게시판 만들기</div>
    <div class="panel-body">
		<div class="table-responsive">          
			<table class="table table-hover">
				<thead>
					<tr>
						<th>게시물 번호</th>
						<th>제목</th>
						<th>조회수</th>
						<th>등록자</th>
						<th>등록일</th>
					</tr>
				</thead>
				<tbody>
					<c:forEach var="vo" items="${list}">
						<tr>
							<td>${vo.idx}</td>
							<td>${vo.title}</td>
							<td>${vo.count}</td>
							<td>${vo.writer}</td>
							<td>${vo.indate}</td>
						</tr>
					</c:forEach>
				</tbody>
			</table>
		</div>
    </div>
    <div class="panel-footer">메인화면 JSP</div>
  </div>
</div>

</body>
</html>

## 작업내역 검토

 

# Spring WEB MVC_03버전_06 게시판 웹 계층 구현 (등록 UI 작업)

## BoardVO

  • 기존 indate 타입을 String > Date로 변경
package kr.inflearn.model;

import java.util.Date;

public class BoardVO {
	private int idx;
	private String title;
	private String contents;
	private int count;
	private String writer;
	private Date indate;
	
	public int getIdx() {
		return idx;
	}
	public void setIdx(int idx) {
		this.idx = idx;
	}
	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title;
	}
	public String getContents() {
		return contents;
	}
	public void setContents(String contents) {
		this.contents = contents;
	}
	public int getCount() {
		return count;
	}
	public void setCount(int count) {
		this.count = count;
	}
	public String getWriter() {
		return writer;
	}
	public void setWriter(String writer) {
		this.writer = writer;
	}
	public Date getIndate() {
		return indate;
	}
	public void setIndate(Date indate) {
		this.indate = indate;
	}	
}

## 글쓰기 기능 작업

### boardList.jsp

  • fmt taglib 추가 후 fmt사용하여 표시되는 데이터 형식 변경
<%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
 <%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<html lang="en">
<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<script type="text/javascript">
	$(document).ready(function() {
		$("#regBtn").click(()=>{
			location.href="<c:url value='/register.do'/>";
		});
	});
</script>
</head>
<body>
 
<div class="container">
  <h2>메인화면</h2>
  <div class="panel panel-default">
    <div class="panel-heading">Spring WEB MVC 게시판 만들기
    	<button id="regBtn" type="button" class="btn btn-xs pull-right btn-primary">게시물작성</button>
    </div>
    <div class="panel-body">
		<div class="table-responsive">          
			<table class="table table-hover">
				<thead>
					<tr>
						<th>게시물 번호</th>
						<th>제목</th>
						<th>조회수</th>
						<th>등록자</th>
						<th>등록일</th>
					</tr>
				</thead>
				<tbody>
					<c:forEach var="vo" items="${list}">
						<tr>
							<td>${vo.idx}</td>
							<td>${vo.title}</td>
							<td>${vo.count}</td>
							<td>${vo.writer}</td>
							<td><fmt:formatDate pattern="yyyy-MM-dd" value="${vo.indate}"/></td>
						</tr>
					</c:forEach>
				</tbody>
			</table>
		</div>
    </div>
    <div class="panel-footer">메인화면 JSP</div>
  </div>
</div>

</body>
</html>

### BoardController

@RequestMapping(value="/register.do", method=RequestMethod.GET)

-> value : 넘어오는 요청 경로
-> method : GET, POST 방식 설정
  • 동일한 url이더라도 GET, POST 방식에 따른 처리 분류
@RequestMapping(value="/register.do", method=RequestMethod.GET)
public String registerGET() {
	return "register";			// 게시물 등록 화면.(register.jsp)
}

@RequestMapping(value="/register.do", method=RequestMethod.POST)
public String registerPOST() {			// 게시물 등록
	return "redirect:/list.do";		// 등록 후 게시물 보기로 이동.
}


=> @GetMapping("/register.do")
=> @PostMapping("/register.do")
등의 방법으로도 가능.

### register.jsp 생성

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
 
<div class="container">
  <h2>Panel Heading</h2>
  <div class="panel panel-default">
    <div class="panel-heading">Panel Heading</div>
    <div class="panel-body">Panel Content</div>
  </div>
</div>

</body>
</html>
<form action="/action_page.php">
  <div class="form-group">
    <label for="email">Email address:</label>
    <input type="email" class="form-control" id="email">
  </div>
  <div class="form-group">
    <label for="pwd">Password:</label>
    <input type="password" class="form-control" id="pwd">
  </div>
  <div class="checkbox">
    <label><input type="checkbox"> Remember me</label>
  </div>
  <button type="submit" class="btn btn-default">Submit</button>
</form>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html lang="en">
<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
 
<div class="container">
	<h2>Board Register</h2>
	<div class="panel panel-default">
		<div class="panel-heading">Board Register</div>
		<div class="panel-body">
			<form action="<c:url value='/register.do'/>" method="post">
				<div class="form-group">
					<label>Title</label>
					<input type="text" class="form-control" name="title">
				</div>
				<div class="form-group">
					<label>Text area</label>
					<textarea rows="3" class="form-control" name="contents" ></textarea>
				</div>
				<div class="form-group">
					<label>Writer</label>
					<input type="text" class="form-control" name="writer">
				</div>
				<button type="submit" class="btn btn-default">등록</button>
				<button type="reset" class="btn btn-default">취소</button>
			</form>
		</div>
		<div class="panel-footer">게시물 쓰기 JSP</div>
	</div>
</div>

</body>
</html>

## 작업내역 확인

반응형
반응형

# Spring WEB MVC_03버전_02 게시판 만들기

  • 이클립스 전자정부 프레임워크 3.10.0
  • 데이터베이스 : MySQL

## SpringMVC03 생성

  • File > New > Spring Legacy Project > 프로젝트명은 SpringMVC03, Templates은 Spring MVC Project 선택 후 Next > 패키지 명 kr.inflearn.web 로 생성

## pom.xml

  • 스프링 버전 4.2.4로 변경
<properties>
  <java-version>1.6</java-version>
  <org.springframework-version>4.2.4.RELEASE</org.springframework-version>
  <org.aspectj-version>1.6.10</org.aspectj-version>
  <org.slf4j-version>1.6.6</org.slf4j-version>
</properties>
  • 자바 버전 1.8로 변경
<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-compiler-plugin</artifactId>
  <version>2.5.1</version>
  <configuration>
    <source>1.8</source>
    <target>1.8</target>
    <compilerArgument>-Xlint:all</compilerArgument>
    <showWarnings>true</showWarnings>
    <showDeprecation>true</showDeprecation>
  </configuration>
</plugin>
  • 설정 완료 후 생성한 프로젝트 우 클릭 > Maven > Update Project.. 진행하여 변경사항 적용.

## 패키지 생성

  • src/main/java 우 클릭 > New > Package > kr.inflearn.mapper 이름의 패키지 생성 (mapper)
  • src/main/java 우 클릭 > New > Package > kr.inflearn.model 이름의 패키지 생성 (model)
  • src/main/java 우 클릭 > New > Package > kr.inflearn.service 이름의 패키지 생성 (service)

## 폴더명 변경

  • src > main > webapp > WEB-INF > views 폴더명 board로 변경

## BoardController 생성

  • kr.inflearn.web 우 클릭 > New > Class > BoardController 이름으로 생성

## board.sql 생성

  • kr.inflearn.mapper 우 클릭 > New > Other > General > File > board.sql 생성
  • 생성 후 Data Source Exploere 탭에서 MySQL 연결된 상태에서 테이블 생성 작업 진행.
create table tb_board(
	idx int not null auto_increment,			-- 아이디 (자동증가)
	title varchar(100) not null,				-- 제목
	contents varchar(4000) not null,			-- 내용
	count int,						-- 조회수
	writer varchar(30) not null,				-- 등록자
	indate datetime default now() not null,			-- 등록일
	primary key(idx)
);
  • 테이블 생성 후 아래와 같이 임시 데이터 넣어서 테스트 진행
insert into tb_board(title, contents, count, writer)
values('게시판 만들기', '게시판 만들기', 0, '관리자');

select * from tb_board;

## BoardVO 생성

  • kr.inflearn.model 우 클릭 > New > Class > BoardVO 이름으로 생성
  • 테이블과 동일한 구조로 생성
package kr.inflearn.model;

public class BoardVO {
	private int idx;
	private String title;
	private String contents;
	private int count;
	private String writer;
	private String indate;
	
	public int getIdx() {
		return idx;
	}
	public void setIdx(int idx) {
		this.idx = idx;
	}
	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title;
	}
	public String getContents() {
		return contents;
	}
	public void setContents(String contents) {
		this.contents = contents;
	}
	public int getCount() {
		return count;
	}
	public void setCount(int count) {
		this.count = count;
	}
	public String getWriter() {
		return writer;
	}
	public void setWriter(String writer) {
		this.writer = writer;
	}
	public String getIndate() {
		return indate;
	}
	public void setIndate(String indate) {
		this.indate = indate;
	}
	
	@Override
	public String toString() {
		return "BoardVO [idx=" + idx + ", title=" + title + ", contents=" + contents + ", count=" + count + ", writer="
				+ writer + ", indate=" + indate + "]";
	}	
}

 

# Spring WEB MVC_03버전_03 게시판 영속계층 구현(Mapper Interface + XML)

## BoardMapper 인터페이스 생성

  • kr.inflearn.mapper 우 클릭 > New > Interface > BoardMapper 이름으로 생성
package kr.inflearn.mapper;

import java.util.List;

import org.apache.ibatis.annotations.Mapper;

import kr.inflearn.model.BoardVO;

// 영속 계층
@Mapper
public interface BoardMapper {
	public List<BoardVO> getList();		// 게시물 리스트 가져오기
	public void insert(BoardVO board);	// 게시물 등록
	public BoardVO read(int bno);		// 게시물 상세보기
	public int delete(int bno);			// 게시물 삭제
	public int update(BoardVO board);	// 게시물 수정
}

## Mapper 생성

  • 아래 MyBatis 사이트에서 Exploring Mapped SQL Statements 참고하여 작성 진행
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.mybatis.example.BlogMapper">
  <select id="selectBlog" resultType="Blog">
    select * from Blog where id = #{id}
  </select>
</mapper>
 

mybatis – MyBatis 3 | Getting started

It's very important to understand the various scopes and lifecycles classes we've discussed so far. Using them incorrectly can cause severe concurrency problems. Dependency Injection frameworks can create thread safe, transactional SqlSessions and mappers

mybatis.org

  • kr.inflearn.mapper 우 클릭 > New > Other > XML File > BoardMapper 이름으로 생성
  • 일반적으로 Mapper 인터페이스의 이름과 Mapper 파일의 이름을 동일하게 만들어주는게 좋다.
  • Mapper 인터페이스와 Mapper 파일의 연동을 위해 namespace 일치 시키기.
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="kr.inflearn.mapper.BoardMapper">
	
    <select id="getList" resultType="boardVO">
        select * from tb_board
    </select>
    
    <insert id="insert" parameterType="boardVO">
        insert into tb_board(title, contents, count, writer)
        values(#{title}, #{contents}, #{count}, #{writer})
    </insert>
    
    <select id="read" parameterType="Integer" resultType="boardVO">
        select * from tb_board where idx = #{idx}
    </select>
    
    <delete id="delete" parameterType="Integer">
       delete * from tb_board where idx = #{idx} 
    </delete>
    
    <update id="update" parameterType="boardVO">
        update tb_board set title = #{title}, contents = #{contents}
        where idx = #{idx}
    </update>
    
</mapper>

## root-context

  • Mapper 패키지 스캔하여 BoardMapper 인터페이스와 BoardMapper.xml 연결 등의 작업 진행
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mybatis-spring="http://mybatis.org/schema/mybatis-spring"
	xsi:schemaLocation="http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring-1.2.xsd
	http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
	http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
	
	<!-- Root Context: defines shared resources visible to all other web components -->
	
	<!-- MyBatis SqlSessionFactory -->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
	    <property name="dataSource"  ref="dataSource"/>
	    <property name="configLocation" value="/WEB-INF/mybatis/config.xml"/>
	</bean>
	<!-- JDBC 연결(DataSource) -->
	<bean id="dataSource" class="org.springframework.jdbc.datasource.SimpleDriverDataSource">
		<property name="driverClass" value="${driver}"/>
		<property name="url" value="${url}"/>
		<property name="username" value="${username}"/>
		<property name="password" value="${password}"/>
	</bean>
	<!-- db.properties 파일 연결 -->
	<bean id="propertyPlaceholderConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
	    <property name="locations" value="/WEB-INF/mybatis/db.properties"/>
	</bean>
	
	<mybatis-spring:scan base-package="kr.inflearn.mapper" />
</beans>

## config.xml

  • WEB-INF > New > Folder > mybatis 이름의 폴더 생성
  • mybatis 폴더에 config.xml 생성
<?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="kr.inflearn.model.BoardVO" alias="boardVO"/>
	</typeAliases>
</configuration>

## root-context

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mybatis-spring="http://mybatis.org/schema/mybatis-spring"
	xsi:schemaLocation="http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring-1.2.xsd
	http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
	http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
	
	<!-- Root Context: defines shared resources visible to all other web components -->
	
	<!-- MyBatis SqlSessionFactory -->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
	    <property name="dataSource"  ref="dataSource"/>
	    <property name="configLocation" value="/WEB-INF/mybatis/config.xml"/>
	</bean>
	<!-- JDBC 연결(DataSource) -->
	<bean id="dataSource" class="org.springframework.jdbc.datasource.SimpleDriverDataSource">
		<property name="driverClass" value="${driver}"/>
		<property name="url" value="${url}"/>
		<property name="username" value="${username}"/>
		<property name="password" value="${password}"/>
	</bean>
	<!-- db.properties 파일 연결 -->
	<bean id="propertyPlaceholderConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
	    <property name="locations" value="/WEB-INF/mybatis/db.properties"/>
	</bean>
	
	<mybatis-spring:scan base-package="kr.inflearn.mapper" />
</beans>
반응형
반응형

# Spring WEB MVC_03버전_01 Tier 방식

  • 사용자의 요구사항을 반영하기 위한 별도의 중간계층 필요. => Service 계층.
  • Controller가 해야 할 일을 Service 계층에서 처리.

## 웹 프로젝트의 3-Tier 방식

1. Presentation Tier (Layer : 계층)

  • 웹 계층 및 화면 계층
  • Controller (FrontController + POJO) : 호출하는 방식을 아래와 같이 테이블로 정리하면 좋다.
요청 메서드
/memberList.do mebmerList
/memberInsert.do memberInsert
  • JSP를 이용한 화면 구성

2. Business Tier (Service Layer)

  • 비즈니스 계층
  • 고객의 요구사항을 반영해주는 계층
  • 로직을 기준으로 처리.
  • 메서드 이름의 경우 현실적인 로직의 이름을 붙이는 것이 관례. (등록의 경우 Register / 회원 검색의 경우 get / 수정의 경우 modify 등... )

3. Persistence Tier (DB 관점, DAO)

  • 영속 계층
  • 데이터에 대한 CRUD (생성, 읽기, 수정, 삭제) 작업 진행.
  • 테이블 설계를 기준으로 VO 클래스를 작성. (MemberVO, BoardVO 등..)
  • Mapper 인터페이스 + @ (어노테이션), XML (xml의 경우 파일이 존재해야 함)
  • Mapper 인터페이스에 메서드 생성 시 데이터베이스를 기준으로 메서드 이름을 설계한다.
반응형

+ Recent posts