HTML을 이용하여 뷰를 만들수도 있지만 에러 메세지 출력을 편하게 하기 위해서는 <form> 태그를 사용하는 편이 좋다.
1. jsp 파일 상단에 라이브러리 추가
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
2. jsp 파일 작성
* 주의할 점
<form:form> 태그에서 commandName은 Controller에서 뷰로 쏴주는 이름을 그대로 넣어야한다.
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>자유게시판</title>
<link href="<c:url value="/resources/css/board.css"/>" rel='stylesheet'>
</head>
<body>
<div id="wrap" align="center">
<h1>자유게시판 - 글쓰기</h1>
<form:form action="/board/free/write" method="post" commandName="board">
<table>
<tr>
<th>게시판 선택</th>
<td>
<form:radiobutton path="boardType" value="1" label="자유게시판"/>
<form:radiobutton path="boardType" value="2" label="회원게시판"/>
</td>
</tr>
<tr>
<th>제목</th>
<td><form:input path="title"/></td>
</tr>
<tr>
<th>작성자</th>
<td><form:input path="writer"/></td>
</tr>
<tr>
<th>내용</th>
<td><form:textarea path="content" cols="70" rows="15"/></td>
</tr>
<tr>
<th>비밀번호</th>
<td><form:password path="password"/></td>
</tr>
</table>
<input type="submit" value="등록">
<input type="reset" value="취소">
<input type="button" value="목록으로" onclick="location.href='/board/free/list'">
</form:form>
<!-- 기존 코드와 비교
<form method="post" action="/board/free/write">
<table>
<tr>
<th>게시판 선택</th>
<td>
<input type="radio" name="boardType" value="1"
checked="checked" required>자유게시판
<input type="radio" name="boardType" value="2">회원게시판
</td>
</tr>
<tr>
<th>제목</th>
<td><input type="text" name="title" required></td>
</tr>
<tr>
<th>작성자</th>
<td><input type="text" name="writer" required></td>
</tr>
<tr>
<th>내용</th>
<td><textarea name="content" cols="70" rows="15" required></textarea></td>
</tr>
<tr>
<th>비밀번호</th>
<td><input type="password" name="password" required></td>
</tr>
</table>
<br>
<input type="submit" value="등록">
<input type="reset" value="취소">
<input type="button" value="목록으로" onclick="location.href='/board/free/list'">
</form> -->
</div>
</body>
</html>
3. Controller GET 요청에서 추가 작업 필요
model.addAttribute("board", new BoardVO());
<form:form> 태그에서는 커맨드 객체를 요구하므로 GET 요청 단계에서 VO를 만들어서 model로 넘겨줘야한다.
// INSERT
@RequestMapping(value="/write")
public String insertFreePost(Model model) {
model.addAttribute("board", new BoardVO()); // <form:form> 태그 쓰려면 필요
return "board/free/free_insert";
}
@RequestMapping(value="/write", method=RequestMethod.POST)
public String insertFreePost(@ModelAttribute("board") BoardVO board) {
// 커맨드 객체명이 다르다면 @ModelAttribute 추가해주기
boardService.insertPost(board);
return "redirect:/free/list";
}
'SPRING' 카테고리의 다른 글
REST API란? (0) | 2020.11.04 |
---|---|
@Param 어노테이션 언제 쓰는지? (0) | 2020.10.25 |
mybatis 환경설정 : <typeAliases> (0) | 2020.10.15 |
스프링 유효성 검증 : @Valid 어노테이션 (0) | 2020.10.15 |
쿠키 @CookieValue (0) | 2020.10.13 |